The API Documentation can be found athttp://weather.weatherbug.com/corporate/products/API/help.aspx and outlines the XML schema, providing details on how to execute searches for weather and forcasts for cities across the United States.
Setting up your Project to use the Bing Maps SDK
Lets take a few moments to get our project set up. I am a creature of habit and have adopted a project structure that works well for me, which is outlined below. We will use this layout for the projects in this demo:
||This is a Web Appliction Project that will hold Class files which perform all core business functions for the entire application. We use the Web Application Project template because it provides references to System features that we commonly need (like System.Web).
||This is also a Web Applicaiton Project for the same reasons as above. This project will hold our Linq to Sql object and any other data-centric related classes
||This is a Solution Folder (see below) which I use as a place to hold DLL’s for related components so that they can be centrally stored and referenced by any project in the Solution. I have a physical folder which I place these DLL’s into, this folder is located at the same level as the website. One benefit is that you have included the referenced DLL’s in the actual project rather then referencing something that is installed on your Dev machine (and most likely wont be on the persons machine that takes this project over after you leave the company). This way you can keep everything that is needed by the project in one place so that it can be easily found even years after the project hasn’t been worked on.
||This is a WCF Service Application (Add New Project => Visual C# => Web => WCF Service Application) and will host all our web services. The methods within our services will simply be wrappers for the related BusinessLogic functions, delegating all the work to the appropriate business logic functions and simply returning the response to the caller. Our web services are dumb and we want to keep them that way, they should not contain any logic whatsoever.
||This is an MS Test project and holds our unit tests that validate the applications business logic and help up build our applicaiton. You will need Visual Studio .NET Pro or higher in order to have the MS Test Suite.
Unit tests are extremely useful as a mechanism to ensure your business logic works the way you expect, I literally use them to create my business rules.
Tests have their place, they are not the end-all-be-all, striving for 100% code-coverage is not only unrealistic but a waste of time (in my opinion). Unit test are most effective as a means to develop your applications business rules and validate that we have covered any breaking changes during project refactoring, and thats what we will use them for here.
||This is an ASP.NET Web Application Project and will host our Silverlight App
||This is a Silverlight Navigation Application, although you could have just used the Silverlight Application tempate with the same result and will use the Bing Maps Silverlight SDK.
You may notice that each project is neatly tucked into a “folder” with an appropriate name (like UI for User Interface). These are “Solution Folders” and can be added to any project by simply right-clicking on the Solution => Add => New Solution Folder (at the very bottom). They are a great way to organize your project into smaller, easier to understand, parts.
Adding the appropriate DLL’s and references
Lets get started with adding the necessary DLL’s for the Bing Maps API, the first thing we want to do itcopy them from their installation location into a local directory that is part of the project.
We do this to guarantee that we will always have access to the related components we need even if the software is no longer installed on our Dev machine, something that’s especially helpful to the developer who takes over this project when your done and doesn’t have the Bing Map SDK installed (the project will compile and run for him because all the needed DLL’s are located within the project structure itself)
After adding the necessary DLLs to our Dependencies folder lets go ahead and add a new Silverlight Project to our Solution file. Right click on the “UI” folder and select “Add => New Item => Silverlight Navigation Appliction”, name it SilverlightAppliction (so we know what it is) and press the Add button
After adding the Silverlight Application we need to add the references to the Bing Map DLL’s. To do this right click on the Reference folder of the SilverlightApplication project and select “Add Reference”
Select the “Browse” tab, then navigate to our Dependencies folder and select the two DLL’s we want to reference.
Working with Maps in Expression Blend
We are now done with most of the boring set-up work, it’s time to get our hands dirty. Add a folder to your Silverlight Application, call it Controls (or whatever you want). Right click on this folder and select “Add => New Item => Sivlerlight User Control”, name it InteractiveMap.xaml and press the “Add” button.
Now start up Expression Blend, and open the project. Once the project is loaded into Blend navigate to the User Control you just added (i.e. InteractiveMap.xaml) and open it.
Controls that are provided by external DLLs, even those controls that you may have created in this Silverlight Project, can be accessed from Blend and dragged onto the Designer surface in order to add them to your Silverlight Page/UserControl. This is a very useful and easy “drag and drop” way of adding items to your Silverlight pages and is something you will find yourself doing on a regular basis.
Follow the 4 steps outlined below:
Now that we have the Map on our page we need to add the Application Credentials in order to use it on our website.
So now we have completed the necessary steps to get started with our weather map. It’s time to add a MapItemsControl to the map, this in turn will allow us to customize the Push-Pin feature. We will over-ride the Push-Pins default template which will instead show our custom weather images (thunderstorms, rain, sunny, etc…) and when clicked on will pop up a Child Window that displays additional weather details for that location.
Setting up your web services
Lets get started with setting up the Web Service. Right click on the folder named Services and select “Add => New Project”. Under the “Visual C#” section select “Web” then “WCF Service Application”. Name the Project “Services” and click the “Add” button.
IMPORTANT: Under the Visual C# section, make sure you select “Web” then “WCF Service Application” and NOT “WCF”. Choosing the former provides access to the Silverlight-Enabled WCF Service template where as the latter does not.
Once you have added the Web Service Project delete the default Service1.svc it auto-created for you. Make sure you remove the bindings and behaviors nodes for this service from the Web.config file as well.
Now lets add some new services to your solution. Right click on the Services project and select “Add => New Item”, under the Visual C# node select “Web” then select “Silverlight-Enabled WCF Service”, name the service WeatherServices.svc and press the “Add” button.
In the code-behind file for the service we need to add a ServiceBehavior attribute with the following properties. Then lets clean up this file by removing the generic “DoWork()” method that was automatically added for us.
Once we have our file cleaned up we will create the method signatures that will be called by our down-stream clients (namely our Silverlight Application). These methods are simply wrappers that forward the request to the appropriate method located inside our BusinessLogic project, returning the results to the caller.
Once we have completed setting up our wrapper methods lets view the page in a browser to ensure all is working properly.
IMPORTANT: It’s important to note that we need to set fixed port numbers for our projects because our downstream clients (our Silverlight app and whatever we may build in the future that hits our web service) will need a consistent URI. This should be done for both our Services project as well as our Website project (although the website really doesn’t require a fixed port #)
Using Linq to SQL with our Weather Data
You may be asking “Why would I need Linq to SQL if the weather data comes from an external provider?”. This is a good question that has an equally good answer. By creating a Data Model that has the column names and data types we want and always returning this data structure to our callers we guarantee consistency to downstream clients (a.k.a our Silverlight App). This is accomplished by massaging the data returned by the weather providers (i.e. WeatherBug, NOAA, etc…) into the data model we define in our Linq to SQL dbml class file.
We also can leverage Linq to SQL’s additonal features such as automatic output Serialization (so the data can be directly returned in a SOAP call) and a simply interface to design and modify our data model, not the mention being able to query our data using Linq even if it’s never stored in the database, in fact we really don’t need a database at all to user Linq to SQL.
However if we do decide that a database may be beneficial to us we can use it to save the data that is returned from the weather service providers, either for historical purposes or simply as a temporary “Cache” type feature to reduce the number of hits we make to the providers services.
We will discuss each of these as we come across them, but for now lets just go ahead and get started.
The sample code for this project is available for download at the top and bottom of the page, the ZIP file includes a Database backup (.bak) of the SQL database we are creating here. I used SQL Express 2005 to develop this database.
Lets set up our Linq to SQL file so that it Serializes the output in order to use it as return values in a Web Service call. Serialization formats the data into SOAP 1.2 compliant XML.
Since we may store the Latitude and Longitude of our weather data, and we may also wish to use this information in future calculations, we need to extend the Percision of the decimal values to support 13 decimal places, as shown below.
Parsing the weather: extracting weather data from xml into a custom data model
Because we may use multiple weather data providers in order to obtain weather information for a specific location we well need to use a custom data model, one that contains the files and name we like, then extract the data from the providers supplied XML into our schema. To do this we will use Linq to XML in order to query the data for the information we want, we will store the results of these queries into our Data Model object and return it to the downstream client. We can also save this to the database for historical purposes or to act as a cache mechanism to avoid hitting the weather service providers to frequently. Then extraction is performed in a single method called ConvertToWeatherDataSchema from within our WeatherBugApi.cs file, located in the BusinessLogic project. Why do we have it here? Because every data provider will have a different schema for their xml so it makes sense to centralize that extraction into the Business Logic class responsible for interacting with the provider, in this case thats WeatherBug.
Using Unit Tests to Help Build Our Business Logic
Data consumption by your Silverlight app
Connecting your Silverlight to your Web Services
Styling the maps Push-Pin to show current weather conditions
The Bing Map has whats called a Push-Pin, which looks just like it sounds and it tied to a specific location on the map. Since we want to show weather conditions rather then push pins we will over-ride the default Push-Pin template and replace it with our own version, on that shows a sun when its sunny, rain when its rainy, etc…
The first step is to generate a DataTemplate for the MapItemControl
We will use a single xaml page that will contain logic which determines which determines based on the weather condition which Silverlight control should be shown for that location on the map. It will also handle the Mouse Click Event which loads up a cusom ChildWindow we created that shows additonal details about the condition for that location.
Displaying additional weather details for a location
When our Bing maps is first created we set a Zoom Level and tell the map to center itself over the USA by passing in a Latitude and Longitude coordinates.
In this project we make use of a Controller file that is responsible for making our web service calls. It then executes a method that we pass to it as a delegate, which is provided with the data from our call.
The code sample below shows how to set the initial view of the map as well as the instantiation of the controller object (passing into its constructor the method that we want fired when data is returned from a web service call)
Once the controller object has been intantiated we call a LoadData() method that executes a method, located within the controller file, and passes it the zip codes for the cities we wish to receive weather data for. Natuarally you would want these zip codes to somehow be dynamic (maybe the user would select a city or area they live near and you could look up the zip codes via PostCode database likeZipCode Download which is not only extensive but pretty cheap too).
When the web service, fired by the Controller file, returns it will call our RequestForData method, passing to it the result of the call (success or failure) and the data returned from the weather data provider which can then be bound to our MapItemControl called ListOfItems.
When all is said and done the Map is displayed with our custom weather items shown for each city.
Clicking on any of the weather items displays additonal details about that city’s current weather.
IMPORTANT: It appears that Bing Maps has a bug that prevents the map from rendering until the browser window size is changed, if you run the code you will see a blank screen, just change the window size slightly and you will see the map render. Hopefully the Bing Maps team will resolve this bug in a future update.
As you can imagine, this system could easily be expaned to display all kinds of weather related events including forcasts and even weather along a specific travel route.
I hope you have enjoyed this white paper on using the Bing Maps SDK for Silverlight.