Silverlight Top Tip: Startup page for Navigation Apps

If you’re working on a Silverlight Navigation Framework application, you’ll often want to debug a specific page, rather than always start at your home page and navigate to it.

My previous solution was just to edit the Source attribute in the Frame, setting it to the initial Url I wanted. But this is dodgy, as if you forget to reset it before doing a release, your customers will end up confused.

The better way, which has only just occurred to me, is to change the default startup path in the associated Web application. In the Properties for your web application, choose the Web section, then edit the Start Action section, choose ‘Specific Page’ then edit the url. By default (in my app at least) it’s just set to the html page. I changed it like this:

Add #/<url> to your Specific Page urlAnd my app now starts up on the Advanced page.Just add whatever you want your initial start parameters to be – you can include query string params or anything else that would make a valid url.

Much safer.


Why does Visual Studio always break on user-handled exceptions?

I’ve been suffering this for ages. I can’t believe it’s taken this long to find the simple answer.

Does your Debug->Exceptions dialog box look like this?

Mine does. And when you want to debug and catch your exceptions in Silverlight, you have to check the ‘Thrown’ box next to Common Language Runtime Exceptions. Easy.

Except that now, the debugger will break on every single exception thrown while your app is running. Not just exceptions in your code that you’re not handling, but exceptions in the framework too. These are perfectly normal, and are all handled, but they are being caught before any handling code is executed.

This is particularly annoying when doing WebClient operations, or using Isolated Storage. You often get exceptions thrown when using these features, which are always handled before your code even sees them, but the debugger catches them anyway and stops.

I knew there was a way around this, because I’d seen it on other installations of Visual Studio. This is what the Exceptions dialog could look like:

With this, the debugger will only break on exceptions that aren’t handled elsewhere in your app. Which is what you usually want. I knew this option existed, but my Bing-Fu failed me, and I couldn’t find how to enable it. (Partly because I couldn’t remember what the extra column was called – if you search for user-unhandled you can find the answer).

You enable it in the Tools->Options dialog, in the Debugging section:

Just check ‘Enable Just My Code (Managed only)’ and magically, the Debug->Exceptions dialog will light up with the User-unhandled column.

I wish I knew this months ago.

‘Cannot register duplicate name ‘XXX’ in this scope’ in VS 2010

Here’s a gotcha that was puzzling me yesterday.

I’ve just installed Visual Studio 2010 RC, and was trying it out on my current project. It’s a Silverlight Navigation-style project, but that’s not important to the bug.

I found one page where the Xaml designer wouldn’t handle the page properly – it was throwing exceptions, and the editor was showing an error in the Xaml. The line looked like this:

<local:SimpleConverter x:Name="SimpleConverter"/>

This is a value converter, designed to convert bindings from one type to another. The error it was showing was ‘Cannot register duplicate name ‘SimpleConverter’ in this scope’. This foxed me for a while – I thought perhaps because I was throwing exceptions when I didn’t recognise the type being converted, but even removing that and simplifying didn’t remove the error.

Then I noticed the key word in the error message: ‘Name’.

In Xaml you can use x:Name if you want something in the Xaml linked up to a class variable in your code-behind. But that was clearly causing issues with whatever the designer was doing behind the scenes. However, if you don’t need code-behind access (as I don’t in this case) you can use x:Key – and that’s the usual mechanism for naming resources.

Changing the resource to:

<local:SimpleConverter x:Key="SimpleConverter"/>

then the errors from the visual designer stop happening.

Of course, I’ve no idea if the errors are a bug in the designer, or if it’s just wrong to use x:Name in resources, but since I didn’t need the autowiring up of objects, it’s no problem to change it.

Silverlight 4 Beta Released

As I was expecting, Scott Guthrie presented the Beta of Silverlight 4 at PDC today. The number of new features it offers is fairly impressive, some of which appear to enable some really exciting possiblities, although playing with the beta bits, there are a few important restrictions. Let’s look at some of the new features first.

  • Printing support
    • Silverlight hasn’t had any real printing support. Silverlight 4 offers a Printing API, including print preview. This is pretty important for business apps, and will definitely be important for the things I’m currently working on.
  • Rich Text Editing
    • Something that could be done by rolling your own editing, this will enable a lot of interesting applications. So many apps require rich text input, and this will be a great help
  • Elevated Out of Browser
    • You can set your app to ask for ‘elevated’ privileges, and then you get access to a lot more goodies – full keyboard in full screen, no cross-browser restrictions, more (but not unrestricted) access to the user’s filesystem
  • WebBrowser control
    • lets you embed another web page in your silverlight app. This looks amazing, but there are some restrictions which might make it less useful. It only works in Out of Browser (for security), and loading HTML from any website requires elevated rights. But you can do things like use the browser output as a brush onto any elements. Scott demonstrated this by putting YouTube into an interactive jigsaw – a demo that I found particularly amusing, given that one of my first silverlight apps was a jigsaw. Here’s the Silverlight 2 version.
  • Webcam and microphone support – not something I desperately need, but it’s always been a top request
  • Clipboard support – something that almost works in SL3 but not in all browsers
  • Drag and drop support
    • this is something I’ve wanted for previous demos. Being able to drag & drop pictures on the app is a lot better than having to fire up a Load dialog.

There’s an awful lot more in there, too. Here’s the info on Silverlight.net.

Ordnance Survey maps in Bing Maps Silverlight control

The latest incarnation of Bing Maps (the web version) has the option of showing certain levels using Ordnance Survey mapping. This was of interest to me, because I’ve spent the last year working on prototypes of mapping applications using the Ordnance Survey 25k layer (the classic Rambling maps). Here’s an example.

They’ve also just released the Silverlight Map Component (which has been in CTP since March) as a V1.0 release. I’ve played quite a bit with the CTP, so I was interested to see how much it had changed. Turns out, not so much. My own OS map layer needed only a handful of changes, almost all around their (sensible) decision to remove the MapViewSpecification object (which made animating the map difficult, so it was good to see it go). But I also wanted to see if the Silverlight component could use the OS maps.

It doesn’t support them out of the box – the only modes offered are the standard RoadMode, and the two Aerial modes (with or without labels) so it’s necessary to roll your own.

The easiest way to put different tiles on the map is to create a custom TileLayer. All you really need to know, then, is how to construct the URL for the tiles you want.

Where do you find the tiles?

A little snooping is required. I fired up a browser, and a copy of Fiddler to watch the requests it was sending. For the OS map tiles, here’s what a typical URL looks like:


This is a fairly typical tile Url. The long number in the name of the image is something called a QuadKey – a way to encode x, y and zoom values in a single value. Here’s a good explanation. Luckily, the map control supplies a QuadKey object to do all the work.

To create a custom tile layer, here’s the code I used:

public class OsTileSource : TileSource
 public override Uri GetUri(int x, int y, int zoomLevel)
 QuadKey key = new QuadKey(x, y, zoomLevel);
 // http://ecn.t3.tiles.virtualearth.net/tiles/r031313112303.png?g=41&productSet=mmOS

 if (zoomLevel < 12)
 return new Uri("http://ecn.t2.tiles.virtualearth.net/tiles/r" + key.Key + ".png?g=373&mkt=en-gb&shading=hill", UriKind.Absolute);
 return new Uri("http://ecn.t2.tiles.virtualearth.net/tiles/r" + key.Key + ".png?g=41&productSet=mmOS", UriKind.Absolute);

You’ll notice that I had to do something different with lower zoom levels. The OS maps only exist above level 12, so below that, I use the normal road tiles.

To use this in the map, here’s what you do:

// Mercator mode means no underlying tiles
 map.Mode = new MercatorMode();
 MapTileLayer layer = new MapTileLayer();
 layer.TileSources.Add(new OsTileSource());

And it all works fine.

Of course, this is probably breaking the Bing Maps terms, but only slightly, since the same maps are available in the Ajax component. I’m sure they’ll turn up officially in the Silverlight component at some point.

Here’s a live example.

One final thought. It’s interesting that the Bing tiles are not the exact map tiles that the OS use. You can tell that by looking at the slightly lower zoom levels – the OS grid lines are not perpendicular. This is because the maps are originally projected onto the OS Grid Projection (which is ideal for a country the size of the UK), while Bing maps uses a Mercator projection (which is easier to manage for a world map). So for the Bing maps, the OS tiles have to be ‘crunched’ to project them onto the Mercator projection, hence the non-perpendicular grid lines.

The OS OpenSpace service provides an uncrunched set of map tiles, although it looks like they miss out the really nice 25k layer, so it would probably be possible to use those tiles, but you’d have to do more work, because those tiles are in the OS Grid Projection, which isn’t compatible with the Mercator projection.

How much more work? That’s a subject for another post. I’ve done exactly that as part of my BBC prototypes, so I have a Bing Maps component working in OSGB coordinates, using uncrunched 25K imagery (see this previous post talking about the problems of hosting map tiles) but the project isn’t yet available for public consumption. However, I’m hoping to give a presentation on the subject at the first Bing Maps UK user group meeting in January, so do come along if you’re interested.

P.S. I did this code in Visual Studio 2010 Beta 2, and the Map component works, live, in the VS designer. As I typed values into the Xaml for the Center and ZoomLevel, the map animated smoothly to that location. Very cool indeed.

Binding to a Silverlight Chart Series gives a null reference exception

This just wasted a good part of my day. I wanted to use a Silverlight Toolkit chart, and I wanted to use declarative databinding for the ColumnSeries (although LineSeries would fail similarly).

I have a DependencyObject as my datasource (although the same would probably happen with a POCO or an INotifyPropertyChanged object) with various dependency properties I want to bind. Here’s the kind of declaration that gives the error:

<chart:Chart x:Name="chart"
 <chart:ColumnSeries ItemsSource="{Binding Results, Mode=OneWay}"
 IndependentValuePath="GenreTitle" />

When the chart is created, I get a System.NullReferenceException when I set the value of Results.

At first, I thought my Results enumeration was somehow wrong, but the same data exactly worked perfectly in a ListBox and a DataGrid, so the data was probably OK.

It was simpler than that, though – I’d missed out the DependentValuePath. You need to specify both otherwise you (rightly) get a null reference exception.

Simple, but it took me a bit of puzzling to find it.

Why I Love Derren Brown

This week, Derren Brown predicted the lottery numbers.

Well, that’s what he said he was going to do, and that’s what he presented. He showed a set of six balls, kept them in full view throughout the live lottery broadcast, then revealed that the numbers on the other side of the balls were the winning numbers. Then he said his show on Friday would show how he did it.

Following the ‘revelation’ a lot of people are disappointed. They genuinely believed he would reveal the technique he used.

Strangely, they’re disappointed because they’ve believed everything he’s ever said previously, when the only thing they should actually believe is his standard ‘disclaimer’: That he uses ‘magic, suggestion, psychology, misdirection and showmanship’.

The prediction was a traditional mentalist prediction in every form. The performer has a ‘prediction’ which he places somewhere he can’t tamper with it, the event happens, then the performer reveals his prediction. This has been the form of this trick for decades.

I don’t think I’m revealing any deep secrets when I say that it’s impossible to guess the numbers, and almost impossible to accurately rig a lottery machine. So if you discount those possibilities, all that’s left is how to get the numbers onto the balls after they’ve come up on the broadcast. There are several ways this could have been done, ranging from an enormously complex split screen camera effect (which I doubt because it would break Derren’s ‘rules’) to electronic balls, laser etching, projection or (my theory) a hidden printing mechanism under the balls.

But how he did the actual trick isn’t really important. It was a perfectly performed illusion, and got a lot of people watching. Which is good, I think.

But the ‘revelation’ on Friday was problematic for me. I was fairly sure he wouldn’t go anywhere near the actual technique (because, frankly, magical techniques are clever, but ultimately mundane, compared to the effect they have). So how would he fill an hour while a) not talking about how he did it, and b) not outright lying.

I have a lot of respect for Derren. I think he’s one of the good guys. His book, Tricks of the Mind, was a fascinating look at mind, belief, memory and ended up almost as a fluffier version of Dawkins’ ‘The God Delusion’. And he’s never claimed to have (or believe in) psychic powers, even when presenting effects that seem to require them.

In ‘The System’ he appeared to be saying that it was possible to predict horse races, but the revelation was actually satisfying (topped off by a genuine magic trick). In one of his Tricks of the Mind he appeared to have hypnotised someone into being able to play piano like a virtuoso. I grew more and more uncomfortable with that show, as I knew it was impossible, but the revelation at the end actually moved me to tears.

I have an expectation that Derren will ‘play fair’ with the audience. Within the context of a magical performance, that is, where you expect the performer to declare that he’s doing something that appears impossible.

So I do get uncomfortable when he starts talking about the PEAR experiments. These were experiments performed (in part) to detect psychokinesis, the ability to affect the random behaviour of a machine using the mind. They initially said they were successful, but later analyses showed that their results weren’t as good as they suggested.

Derren then showed a nice trick with coin tossing that appeared to show an effect, but then explained it was a maths trick. Then, significantly, he said something like ‘and it turned out that the PEAR results didn’t really stand up’. Now, he said that casually, almost throwaway, so most of the audience probably didn’t really notice, so the strong suggestion that it’s possible to affect things with the mind remained, but he did that while still telling the truth about the experiments. That pleased me a lot.

Then came the main part of the programme, where he had a group of people harnessing ‘the wisdom of crowds’ to predict the lottery numbers. I’ve got an idea how this was done, but it’s enough to say this was another trick. But basically, this was just another piece of misdirection.

Then, just as you think he’s saying that’s how he did it, he did a very funny description of how he might have fixed the lottery machine.

And right at the end, with an almost straight face, he said ‘So I couldn’t possibly admit that I fixed the machine – which I didn’t – so now, when people ask me how I did it, I’ll just say “It was a trick”.’

Perfect. He managed a whole hour of fun and misdirection, and yet he genuinely did say how he did it.

And that’s why I love Derren Brown.