Creating a Weather Map using the Bing Silverlight Map SDK and WeatherBug

What’s Covered in this Series:

  1. Getting Started with the Bing Maps Silverlight SDK
  2. Getting up and running with the WeatherBug API
  3. Setting up your Project to use Bing Maps
    1. Adding the appropriate DLL’s and references
    2. Working with Maps In Expression Blend
  4. Setting up your web services
  5. Using Linq to SQL with weather data
  6. Parsing the data: extracting weather data from xml into a custom data model
  7. Using Unit Tests to help build our business logic
  8. Data consumption within your Silverlight app
  9. Connecting your Silverlight to your Web Services
  10. Styling the maps Push-Pin to show current weather conditions
  11. Displaying additional weather details for a location

UPDATE: (02/12/2010)    The code has been updated to use the <OBJECT> tag to declare the Silverlight control on the Default.aspx page (in the Website project), and the reference to System.Web.Silverlight has been removed. This is to bring the code up to the Silverlight 3 spec as the <asp:Silverlight> tag and System.Web.Silverlight have been deprecated. This also eliminates the “Communication exception unhandled by user code” error some people are experiencing.

The inspiration for this white paper came from an article written by Andrej Tozon entitled Create a Silverlight Europe weather map and was published on Silverlight Show. In that article Andrej covers some of the same concepts and shows how he developed a solution for showing European weather data. You can view his article here.

Getting Started with the Bing Maps Silverlight SDK

Bing Maps has a great API now available for use in your Silverlight applications. To use the controls in your projects you need to download and install the Bing Maps Silverlight Control SDK. One thing that is a little odd is that you are required to set up a Bing Maps Developer Account at and then generate Application Keys for the map, you can generate up to 5 keys per account. I’m not sure why this is a requirement, I imagine you can reuse the keys across multiple projects (not positive though so don’t quote me on that).


Once you have downloaded and installed the Bing Maps Silverlight Control SDK go to and register for a new account.




Getting up and running with the WeatherBug API

WeatherBug is a free weather data service founded in 1992 and based out of Germantown, Maryland USA. WeatherBug manages and operates the world’s largest proprietary weather network with over 8,000 Tracking Stations and more than 1,000 cameras strategically placed at schools, public safety facilities and televisions stations throughout the United States.

Setting up your WeatherBug account is extremely easy, taking less then 5 minutes. Weather information is obtained by performing a RESTful web service call, with the response from WeatherBug being in XML format.

We will parse the returned data and store it into our own customized and Serialized data model, this allows us to intergrate with other weather data providers such as the National Environmental Agency, which provides weather data for major cities in Europe, and the National Weather Service SOAP Web Services without affecting any down-stream consumers (namely our Silverlight application which will use Bing Maps) due to differences in each providers data schema.

We won’t cover any weather data providers other then WeatherBug but this project is architected to easily allow for the integration of other service providers.

Go to and select the WeatherBug API option from the home page.


Complete the registration form which will email you information you will need on how to complete your registration. Don’t forget to thank WeatherBug for providing such an awesome service by including the WeatherBug logo on your site where you display the weather data they provide.



Sign up for the Commercial API since we will be using this data on a website.







The API Documentation can be found at 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:

BusinessLogic: 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).
DataModel:  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
Dependencies:  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.
Services:  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.
UnitTests:  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.

Website: This is an ASP.NET Web Application Project and will host our Silverlight App
SilverlightApplication: 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.

Silverlight Straight Talk: The Awesomeness, Disadvantages, and Difficulties in Silverlight

Building Silverlight application takes time, effort, patients, and tools (yes, you have to have some tools). In this post we will cover: where to get the necessities and some useful additional tools, as well as straight talk about the awesomeness, disadvantages, and difficulties of building Silverlight applications.  We will also cover the basics of XAML, referencing and using related assemblies, and the how Expression Blend and Visual Studio make it all happen.



Where to Get the Necessities

Must Have tools

  • Visual Studio.NET 2008 or 2010 (available from the link above)
  • Expression Blend 3 (available from the link above)
  • Silverlight Spy
  • Fiddler Debugging Tool
  • FireFox with FireBug(Tools àAdd-ons àGet Add-ons)

Useful Additions

Straight Talk: the Awesomeness, Disadvantages, and Difficulties in Silverlight

  1. You, as a developer, now can and should learn how to developer professional grade User Interfaces that offer end users an engaging and user friendly experience. You will take on both the role of Designer and Developer.
  2. The things that you wished you could do in C# instead of JavaScript can now be done, this frees you from the limitations of the typical web application.
  3. The learning curve: its steep (but not mount Everest)
  4. XAML, it’s a whole new world.
    • Its an unfamiliar landscape that takes time getting used to (remember the first time you ever worked with HTML and CSS, its just like that)
    • Its very picky and unforgiving, one wrong move and you get an very unhelpful BAD PARSER error forcing you to literally dig through all of your code to try and figure out what the problem it.
    • Blend, it’s a whole new tool (even if you already know Adobe Photoshop)
    • You have to find your way around the tool, its not obvious how to do a lot of things , expect to spend lots of time and energy getting used to it
  5. Visual Studio and Blend: it takes two to tango
    • You really must have Blend in order to develop complex (or even average) Silverlight applications
    • Animation and themes are pretty much done exclusively in Blend.
    • All your C# coding is done in Visual Studio
    • Reliable Error message don’t exist, this increases the time and difficulty in tracking down issues.
  6. Gotcha’s that will drive you nuts
    • If you don’t explicitly set the Forecolor (a.k.a the font color) on your TextBlock then your text wont show up (even though it looks fine in Blend)
    • Your project can get out of synch when working in both Blend and Visual Studio, if your not careful you can end up undoing a lot of your code
    • The Design View in Blend can screw you! Don’t rely on it exclusively, instead always be looking at the Code Window (Split View) when working with the designer
    • No Project Refresh in Blend: After adding items to your project through visual studio you have to trick Blend into reloading the project in order to work with the additions.
    • Bland fails to apply namespace properly when using it to add new User Controls
    • Selecting an Image source through the designer copies the image to the Silverlight Application Root
    • Blend doesn’t recognize Web Service References and will indicate that you have errors when you really don’t
    • Error Message are worthless.

Understanding the basics

  1. UI layout
    • Grids: they are very much like HTML Tables
    • Stack panels: this is like an HTML Div where you set the “orientation” of its contents to one of two setting, either Horizontal (default) or Vertical
    • Canvases: just like it sounds, it’s basically a container where you position its content using Canvas.Top=“x” and Canvas.Left=“x”. Very similar to using a Top and Left in HTML/CSS
    • Margins: allow you to add spacing between items (left, top, right, bottom) in order to control its position relative to other objects. Just like Margin/Padding in HTML/CSS
  2. Animations
    • Visual State Manager: this is the build in “animation” that is applied to object. Is usually developed using Blend because it can be a nasty little bugger to work with by hand.
    • Animation using Blend: similar to how you animate object in Flash (“Tween” like features as well as Easing)
    • Behaviors: these are “In-Code” animations (basically taking an animation that Blend creates and writing it in C#). Can be reused through your project as well as other projects (by adding references to the DLL its contained within). Not easy to create because currently there isn’t any automation tools to write the C# code (you will be doing by hand, not fun).
  3. Events and Data-Binding
    • Getting a grip on Asynchronous Data Exchange: timing is everything, your data may take a long time to return (if it returns at all) and you need to let people know what’s happening during this time. Data returned is not guaranteed to be returned on the User Interface Thread, meaning it may be there but not show up in the UI
    • Data-Binding and why it’s so awesome in Silverlight: Binding objects to data is INSANELY easy. Objects look for data that it should bind to first in its own DataContext, then its Parent, then its parents parent, etc… until it finds (or doesn’t) what its looking for. Handles “not found” very graciously.
    • Accessing your web services: set-up to easily handle moving from Dev to Test and then into the Production Environment
    • Wiring events to User Controls: very similar to how you define it in ASP.NET web applications.

References assemblies & debugging your project

  1. Accessing and Using Shared Components
    • Using Blend’s Control Library to access items in referenced libraries. In Blend you can access controls that exist in references library (DLL’s).
    • Extending existing controls in order to customize them: accomplished in the same way as ASP.NET, simply create a Class file that inherits from the base control (i.e. the Textbox control) and add custom properties and methods to it. Then use these in your project in order to take advantage of the added functionality.
    • DLL’s as well as “Behavior” classes (just C# class files), many available for Free on the Web (visit  )
  2. Testing and Debugging your application
    • Using Fiddler to intercept web service requests (very useful to debug web-service requests and responses)
    • Using Silverlight Spy to identify User Interface elements (a must-have tool to drill down on the Silverlight objects displayed on the screen)
    • Unit Testing your Web Services and Business Logic

When ORM becomes a problem

ORM (Object Relational Mapping) systems are useful in getting you started with a project. They help you to quickly create objects that model your Data Source, letting you interact with the data in a simple and intuative manner.

While ORM is extremely useful, especially in smaller projects, this usefulness comes at a price. ORM becomes a problem in long-term maintenance as you are committed to the ORM you initially select, whether its Entity Framework, LINQ2SQL, SubSonic, NHibernate, or any other ORM Software Factory system that generates class based on the targeted data source you will need to select one and, in most cases, will be married to it throughout the development (and product) life cycle.

While this may not seem to be a deal breaker it is not until later, during the longer-term maintenance phase, that the price is paid. Developers who inherit the project from you will be forced to continue to use the ORM you selected, even if its no longer available. And if the ORM system is open-source, with its source code available for you to modify, upgrades (or downgrades) to a different version can cause major headaches which often result in the development team refusing to make changes to the ORM for fear of crashing the application (or even worse would be to cause lots of runtime errors that are only discovered after the upgrade).

Another disadvantage is that if the data source schema is changed the application is not shieldedfrom the change. The relational schema of the data is hard coded into the application via the generated classes. If the data model changes the ORM object won’t know until they are regenerated by the ORM software.
The moral of this story is to use caution when working with ORM systems. Anticipating and addressing these kinds of issues beforehand can help to avoid having your hands tied later down the line.