Adding Sorted Items to DropDownMenus at Runtime

I use drop down menus regularly. They are a very common control on most any website and often we are just getting a list of things out of a database and simply binding them to the drop down so the user can select one.

It’s very easy to bind items to an ASP.NET DropDownMenu. Removing items as well as adding items it just as easy. But what if you need to add items to the DropDownMenu when the list has already been DataBound and you need to ensure that all the items in the DropDown have been sorted (either by the Text or the Value)? This is a little bit tricky, which is why I’ve taken the time to show you how to do it (and so I can use this example next time I need it).



How to structure new projects in Visual Studio

Over the year’s I’ve continuously refined how I set up and organize my applications and folder structure in Visual Studio when starting a new project. Its taken some time but I have finally found a setup that works well for me so I put together a quick video showing how I do it.

Since I am always looking for “a better way” any feedback you wish to provide, good or bad, is appreciated.

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.

Using a Generic Method to Encode String Properties In Order To Avoid Cross Site Scripting Attacks

Cross Site Scripting Attacks (XSS Attacks) are a real problem, don’t make the mistake of thinking they aren’t in widespread use or that you are not vulnerable. During the development of your project you need to explicitly take steps  to avoid exposing your sites visitors to this serious issue. You can use the Microsoft Web Protection Library to reduce the risk of XSS attacks, get it here

Recently I developed a simple generic method that I can pass objects to which will loop over the properties and automatically HTML encode any that are strings. This is useful when you use ORM systems such as Linq2Sql or ADO.NET Entity Framework, which generate an object model of your database which often include properties of type String.

Here is how to call the method:


Here is the code:


Silverlight Navigation Framework: The NavigationContext and QueryString Parameters

In the Silverlight Navigation Framework moving between pages is pretty straight forward, however you can run into some odd errors that will throw you for a loop if your not careful. As with Asynchronous development as a whole, timing is everything, and the NavigationContext is no exception.

Following the typical scenario in Silverlight, when we want to navigate to a page and pass some information across the QueryString, we do something like the this:

Then in MyPage.xaml we would look at the NavigationContext to see if a QueryString namedMyQueryStringParam existed, and if found then we would access it’s value like so:


However, a problem will arise if you attempt to access the NavigationContext to early in the page life cycle, resulting in it being NULL at the time you attempt to access the it or any of its properties, such as QueryString parameter.

The solution to this problem is to overload the Loaded event for the Silverlight page by placing a statement like the following in the page Constructor:


Then from inside the overloaded Loaded event you will access the NavigationContext like the following:


This ensures that the NavigationContext object has had time to be initialized, providing access to its properties in order to extract any of the QueryString values that you need.

Silverlight Error: Element is already the child of another element

Often we have objects that we manipulate in code and need to add/remove from the visual surface of a Silverlight interface. One issue that may arise is the dreaded “Element is already the child of another element” error. In Silverlight you cannot add the same object to more then one parent container (or add the same object multiple times to the same parent, a.k.a. duplicate the control).

To check and see if your object currently has a parent you can use the

If this comparison yields NULL than you know you can safely add the object to an element on the page (like adding it as a Child to a <Grid> via the .Children.Add(<child object goes here>) call). Hope this helps.

Two Chefs in the Kitchen: The future of Silverlight with HTML 5

I have heard, and participated in, the HTML 5 vs. Silverlight argument. Often the dialog begins with something like “Silverlight is on deaths door, HTML 5 has fatally wounded Silverlight and it will officially become a corpse in the very near future”. I could not disagree more.

I do not see HTML 5 as a competitor to Silverlight. While they share some of the same abilities, to me they seem more like two chefs in a single kitchen: both can produce glorious meals simultaneously in different (or the same) ways, both can choose to work together to create a single unified experience or choose to do their own thing, merely existing within the same space at the same time.

Today the Silverlight Team blogged about The Future of Silverlight and how HTML 5 will play a role in that future

On the web, the purpose of Silverlight has never been to replace HTML; it’s to do the things that HTML (and other technologies) couldn’t in a way that was easy for developers to tap into. Microsoft remains committed to using Silverlight to extend the web by enabling scenarios that HTML doesn’t cover. From simple “islands of richness” in HTML pages to full desktop-like applications in the browser and beyond, Silverlight enables applications that deliver the kinds of rich experiences users want. We group these into three broad categories: premium media experiences, consumer apps and games, and business/enterprise apps.

I encourage you to Read the Entire Article and Subscribe to the Silverlight Team Blog. In my opinion Silverlight is here to stay, its a solid viable technology, and I am committed to continuing to use it to solve real world problems as I build software.

In this discussion of the future of Silverlight, there’s a critical point that is sometimes overlooked as Silverlight is still often referred to—even by Microsoft—as a browser plug-in. The web is evolving and Silverlight is evolving, too. Although applications running inside a web browser remain a focus for us, two years ago we began showing how Silverlight is much more than a browser technology.

Error: The default XML namespace of the project must be the MSBuild XML namespace

One day you get to work, your boss tells you that there is a project that he needs you to work on, you get the code from source control and open the project up in Visual Studio.NET

During project loading you get a series of crazy errors you have never seen before, ultimately ending in:

error : Unable to read the project file '.csproj'. .csproj(2,1): The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="" to the element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.

You scratch your head, with a big thought cloud overhead that reads “WTF???”


You notice that the Silverlight project (in my case the project’s called “SilverlightInterface”) failed to load and is “unavailable” in Solution Explorer:


So you try to “reload” it by right clicking on the (currently unavailable) project and selecting “Reload Project” from the menu, only to get an even nastier error message:


Looking at the Output Window you’re faced with a never-before-seen error which states something about the The default XML namespace of the project must be the MSBuild XML namespace.

Fortunately the solution is simple:

  1. In Windows Explorer navigate to the project
  2. Right Click on the .cproj file, select Properties, and un-check the “Read Only” checkbox
  3. Open up the .cproj file in Notepad
  4. On line 2 change xmlns=”″ to xmlns=”″ (notice this only difference is we changed 2008 to 2003)
  5. Save your changes
  6. In Visual Studio right click on the (currently unavailable) project and select “Reload Project”
  7. The project will now load normally and you can get on with your life

Error: Could not load file or assembly System.Windows.Interactivity

Silverlight 4 and Visual Studio.NET 2010 are awesome, however if you are required to create a Silverlight 3 application and currently are using Visual Studio.NET 2010 than the default target for your Silverlight app will be version 4. You will have to go into the Properties panel for the Silverlight app and change its target to point to SL 3.


While this is usually not an issue occasionally you may run into a deceiving error message. The project builds fine, you check the reference to the System.Windows.Interactivity assembly and it does exist, however when you go to view the XAML in the designer (either in VS or in Blend) you get the following error:




This is caused when your SL 3 app references any assembly that targets a newer version, for example Microsoft.Expression.Prototyping.Interactivity.dll or Microsoft.Expression.Interactions.dll that are found in Blend 4.



Removing the references to these assemblies will resolve the issue.


Error: This assembly may have been downloaded from the Web

If you’re like most programmers you get a LOT of stuff from the Internet, like sample projects, assembly’s (i.e. .DLL’s), etc… It seems like just about everything we do these days in software is somehow related to the Web, even if that means you are just blogging about it.

After upgrading a Silverlight project so that it can be developed on Visual Studio.NET 2010 I ran into a show-stopper error:

Could not load the assembly file:///.... .dll. This assembly may have been downloaded from the Web. If an assembly has been downloaded from the Web, it is flagged by Windows as being a Web file, even if it resides on the local computer. This may prevent it from being used in your project. You can change this designation by changing the file properties. Only unblock assemblies that you trust. See for more information.


The recommended solution is to “Unblock” the content through Windows Explorer, the only problem is that I was developing this application on a machine at my work and that machine’s Security Settings prevented the “Unblock” feature from Windows Explorer (you couldn’t even see the Unblock button), I thought I was totally screwed.

frustration After banging my head on the desk a few thousand times a co-worker finally suggested that I copy the DLL’s to a Fat32 drive (like an external Thumb drive), then copy them back to the orginal location (over-writing the originals with the copy).

I then simply needed to select “View All Files” for the project in Visual Studio, expand the Bin directory, and delete all the contents (I also removed the reference to the DLL and re-added it just to be safe).

Recompiling the project was successful and I could finally get back to work, what a pain in the a—, hope this helps you fix this issue if you run into it