Uncategorized

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.

Advertisements

‘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:

http://ecn.t3.tiles.virtualearth.net/tiles/r031313112303.png?g=41&productSet=mmOS

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);
 }
 else
 {
 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());
 map.Children.Add(layer);

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"
 Height="500">
 <chart:Chart.Series>
 <chart:ColumnSeries ItemsSource="{Binding Results, Mode=OneWay}"
 IndependentValuePath="GenreTitle" />
 </chart:Chart.Series>
 </chart:Chart>

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.

Windows 7 Media Center on Acer Aspire Idea 500

We had a catastrophe recently. Our Windows Vista media centre developed a puzzling problem. It refused to boot up, complaining of no boot disc. But if I went into the BIOS and put the SATA boot drive back to the top of the boot drive order and reboot, it would boot up fine.

For a while.

Then, it started randomly hanging, then restarting, and giving the ‘No boot disk’ error again. Until it got to the point where it wouldn’t get through the boot sequence before rebooting.

Clearly, it was unhappy.

I’ve had hardware issues before.

The PSU has failed twice, in exactly the same way, in the last two years. Others have reported the same symptoms, so there’s definitely some problem, and a replacement PSU has solved it both times.

This is different, though. It looked like a faulty drive, although this drive was new this year.

Whatever the reason, we were without TV. We don’t watch live TV. All our TV viewing is through the Media Centre. Or iPlayer (mostly the kids use iPlayer on their netbooks when they don’t want to watch what’s on the big telly).

So I clearly had to do something.

I decided to put a new drive in. I had a spare 500G SATA drive with some archived TV, so I cleared all that off onto the 1.5TB external (which is now getting full itself) and put it into the Acer.

Then I booted up with the Win7 RC in the drive.

About 30 minutes later, Win7 was running. All was not rosy, though.

Windows 7 issues with Acer Aspire iDea 500

A default install was missing some drivers. I was using a TV as a monitor (easier to do where the machine lives) and the output was black and white and quite fuzzy – clearly NTSC rather than PAL. And there was no sound coming through the TV speakers, despite Win7 thinking a sound driver was working. And Device Manager was telling me that the TV Tuner card was unrecognised (not surprising – it’s an obscure OEM device from Yuan).

Luckily, I had two things on my side: Windows 7 uses the same driver model as Vista; and I’d gone through a complete install of Vista on this machine (it originally came with XP Media Center Edition) and I’d made sure I collected all the drivers I’d had to install to get things working. I’d even burned them onto DVD and remembered where I’d stored the DVD. Most unlike me, I have to admit.

So I grabbed the driver disk and installed away.

Graphics

The machine has an Intel 945GM integrated graphics chipset. I installed the drivers from my DVD, but it didn’t make much difference. The Intel drivers have a pig-ugly custom configuration control panel which allows you to set things like the TV mode, and I’d already set the mode to PAL_I, but I tried again, and this time, after a reboot, the colour image reappeared. I’ll come back to the graphics driver, but for now, that was OK.

Sound

No sound from the TV output (through a scart socket). I remembered having a similar issue with Vista, so I installed the Realtek drivers, and the sound was restored. (I had a plan B – a small USB speaker – but I’m glad I don’t have to use that plan.)

TV Tuner and Media Centre

I installed the Yuan drivers I’d used for Vista, and Device Manager showed that it believed they were correct, so to test it, it was time to start Media Centre for the first time.

Media Centre installation in Windows 7 was a little quicker than Vista. It seemed to ask fewer questions, and it recognised my tuner (it’s a dual digital/analogue tuner and both channels were recognised). I chose the default settings, and the only question it asked was my postcode, for the tuning and guide data.

After the requisite 15 minutes of searching for channels, it found around 91, which might even be more than I’d got before (the number of available channels tends to change, so that’s not perhaps surprising).

Then it started for real. I checked the guide, and started watching BBC One. After the usual tension-filled 5 seconds while it detects the signal, it started playing perfectly. Fantastic!

First Impressions

Media Centre strikes me as an unloved project. It could easily be a key selling point for Windows. other platforms’ alternatives are nowhere near as polished. And yet, it doesn’t seem, from the outside, that the project gets much development attention. Windows 7 MC still looks a lot like Vista. Some screens are almost identical. As such, the differences are often small, but telling.

Guide

The guide has been slightly redesigned. The grid is flatter in design, but doesn’t really show any more information. And some navigation features are missing. When you click on the channel name, it switches to the channel specific display, showing more upcoming shows. In Vista, Left and Right would cycle through the channels. In Win7 this doesn’t work. I used to use this all the time, so its absence is annoying.

Clicking on a specific programme in the channel listing brings up a very different Programme Info page. It still has the key options for recording the show, although the buttons are redesigned, and much smaller. This seems an odd choice, and on the tiny 14in screen I was using, it’s not that clear. However, I understand that they’re probably targeting much larger screens, so it’s probably unfair to complain.

One definite gripe, though is the behaviour when recording shows. I occasionally like to scroll through the channel listings and marking upcoming shows to record. In Vista, this was a couple of clicks. One click to bring up programme properties. Another click to record. and you’d be back where you were.

In Windows 7 it’s slightly different. When you click the Record button, you’re taken back to the channel listing, but the focus is on the button to the left of the listings, rather than on the show you were recording. This makes it a lot more difficult to just scroll through recording shows.

There is a shortcut, though, and I’m not sure if this worked in Vista. If you hit the Record button once, it will set the programme to record. Hit it again, and it sets it to record the series. Hit it a third time and it cancels the recording. This is nice, and if I remember it, it will be even quicker than before.

Live TV

There are two apparent improvements here (at least, to me). Firstly, I was surprised to see a ‘press the red button’ logo appearing. So I did, and I got the BBC’s interactive text service. I’ve never seen this on Vista, so I think it’s new in Windows 7. Nice to have, although it’s not a service I make use of myself. Sadly, they don’t record the stream, so the red button isn’t available on recordings. That might have been cool.

Another addition, which might only be new for the UK, is subtitles. These are available on the newly expanded ‘info’ menu which now opens a bar across the bottom of the screen and has several sections. I haven’t checked whether the subtitles are recorded – I presume they are. Old recordings from Vista MCE do not have subtitles.

Another tiny improvement: On Vista and XP, when recording BBC TV, there was always a recording glitch just as the programme was about to start. I’m not sure what that was, but it was ever-present. All my recordings have a slight glitch about 5 seconds after the channel ident starts. It’s probably something particular in the transport stream that the recording was choking on. But it’s gone in Windows 7 (well, on the programme I just checked).

Recorded TV

This is where we spend most of our time, and it’s never been a perfect environment in Vista.

I have some archived TV. Quite a lot of it.

Not sure how much, but over 5 terabytes of it, spread across lots of external drives.

Vista had… issues with this.

Vista has a nice feature – More TV folders – which allows the Recorded TV page to get files from more than one directory – something XP couldn’t do.

But Vista had performance issues. The more files and folders you added, the more time it would take to open Recorded TV. It got to be almost a minute before the screen would appear. I had to remove rarely used folders because it was so interminable. Every Time I’d go to the root Recorded TV page, it would spend >30s doing something before it would show us the page. It was quite bad. I’d almost have time to make tea while waiting.

Naturally, I was keen to see if Windows 7 had addressed this issue. I wasn’t hopeful, as I’ve never seen this issue mentioned as a problem with Media Centre. I plugged in two or three of my larger hard drives, and told Media Centre to monitor all the folders containing TV. Then I hit Recorded TV.

There was a pause. But not a long one. Recorded TV appeared. It didn’t yet have all the files, but it was up and showing me what it had.

I left it a while, indexing. Then I tried again. Again, there was a pause, a little longer, but still acceptable. Three seconds or so.

It’s also pretty-much instant going into groups of programmes when sort by title is on, and instant again going back up to recorded TV. Vista would have its long pause every time I went to the Recorded TV root. Windows 7 just seems to snap back.

I’m very happy with this improvement.

Playback

There’s one issue I haven’t sorted out. Playback of old recorded TV (recorded in Vista) judders. Every couple of seconds, the picture pauses then quickly catches up with itself. The sound is fine. At first, I thought it was a video driver issue, with the driver not being able to keep up with playback. But Live TV was smooth, and playback of a newly recorded progranne also looks smooth.

I know that they’ve moved to a new file format, so the old dvr-ms format is now a legacy format, but it’s all MPEG2 in the end, so I’m at a loss what the problem could be. Also, I know I’ve played back dvr-ms files on other Windows 7 machines, and not noticed such issues. I watched ‘Who Framed Roger Rabbit’ on a projector, played from a Samsung netbook, and it was fine, so it’s hard to know what the issue might be.

Conclusion

I’ve held off from going to Windows 7 on the media centre until now on the basis that it basically worked, and was in use every day. An upgrade or rebuild always takes time and might not even work, so I didn’t want to do it on a whim. So in a way, the machine’s problems were a good thing.

Windows 7 installation was quick and easy. My preparation of a driver disk paid off, and all the drivers I needed worked. I was worried about the tuner card, as I know that some very popular cards have had issues with Windows 7, but mine works fine.

The performance improvements in Recorded TV will make a huge difference.

And I hope I can get to the bottom of the skipping on old recorded programmes. It’s going to bug me otherwise.

I’ve yet to look at the extender features. I’d like to be able to access recordings across the network on any PC, but I haven’t set up a homegroup yet. I’ll also try once more to set up my XBox as an extender, something I was unable to get working on Vista.

To sum up. Windows 7 Media Centre is worth the upgrade, if your hardware works. It’s still the same Media Centre, just better.

Update: 29 August 2009

At the same time as the Vista media centre dies, our TV died. Sort of. The switch on the front broke, and would no longer lock on. It’s a 6 year old 32in CRT TV that’s frankly showing its age, so I’ve been expecting it to die at some point. It was a bit of a coincidence it broke the same day as the MC, but that switch has been dodgy for a while. It’s funny how these things happen together, though.

So I wasn’t too upset that we needed to buy a new TV. Which we did today. We bought a Samsung 40in LCD TV. Something like this one. I toyed with buying a 50in plasma, but it was an extra £220, and 40in is still significantly bigger than our current TV, and probably as big as we want. It fits in the space where the old TV was, in the corner of the room, and we’ll probably put it on the wall eventually.

But how does it get on with my fairly old Media Centre? I was worried that it wouldn’t drive the HD resolution screen fast enough, that it would be choppy or slow.

I needn’t have worried.

I rebooted the Media centre, plugged in the HDMI cable, selected the right input on the TV and waited.

I’ve never been so pleased to see the ‘Starting Windows’ screen.

It detected the TV’s resolution (1920×1080) and I had a perfectly working display.

Except there was no sound.

After much fiddling and swapping, I’ve concluded that the HDMI cable I bought doesn’t carry sound. Probably. I’d have to try it with another known, working TV/Device combination to be sure.

Luckily, the TV has an input that takes this possibility into account (for DVI, VGA or video-only HDMI inputs) and I ran an extra audio cable to the TV and finally got sound.

And because it’s now using a native widescreen mode (instead of the square mode I was forced to use with a standard def TV) it now switches from widescreen to 4:3 when necessary. No longer does Jon Stewart look tubby.

And the best result by a long way is that playback of old recordings are no longer stuttering. They’re as smooth as they used to be on Vista.

So my new conclusion: Windows 7 Media Centre, plus an HD TV is made of win. I’m very, very happy.