Silverlight 2 gotcha

I was going through an example from Microsoft’s Tim Sneath and hit the following error…
A first chance exception of type ‘System.Windows.Markup.XamlParseException’ occurred in System.Windows.dll
Additional information: AG_E_PARSER_BAD_PROPERTY_VALUE
 
I dread this sort of error in Silverlight, but it turns out that the answer in this case was fairly simple, if a little suprising. The example has 3 slider controls each sharing the same ValueChanged event handler. However, as the page is initialized the slider values are firing their ValueChanged events. Unfortunatley the shared event handler examines the value of all the controls but they are not yet available, hence the error. To avoid this I simply check for null in the event handler.
 
 

Silverlight 2.0 (beta)

I’d picked up Silverlight 1.1 pretty quickly and initially got stuck into to solving its pretty close to non-existent keyboard support. However, other time factors got involved and although my solution worked ok it was always going to be a poor substitution to the real deal. So it was with renewed enthusiasm that I downloaded the latest incarnation, VS2008 templates and all. Unfortunately it’s taken me most of the day to get my development environment installed (requiring a number on uninstalls of previous beta sdks) but so far the wait seems to have been worth it. The first thing that strikes you is the far more mature project templates in VS2008 with creation choices including hosting the project in a new web site or via a HTML page. The latter is interesting because it hides the page…although the former is the weapon of choice if you want to avoid all those annoying ‘enable javascript’ browser prompts. Next things is you get split designer view ala Expression Blend. Although my early experience with the design surface is pretty…well pointless. More of an instant preview than a UI surface, I’m sticking with the XAML for now. The next thing that stuck me is the lack of all the supporting files, e.g. javascript, manifests, etc. Well VS has kindly hidden those, or rather bundled them up in another one of the ever common zip-thats-not-a-zip-but-is-only-renamed files, much like the Office docs. Still that’s great for me, since I do have some idea what they are and probably won’t want to have to interact with them like I did before. Obviously the well publicised changes are there, all the lovely WPF like controls albeit without any glossy 3D. What did strike me as unusual is that coding the page is still a bit…odd. For example, the steps I went through to put a caption on a button (without RTM first) were…
1. Drag button onto UI surface – Nope nothing
2. Drag button onto XAML – yes
3. Properties of button – nothing
4. Click in button tag to bring up intellisense – yes
5. Look for something like text or caption – nothing
6. Enter text in the ‘innertext’ of the tag – not allowed
7. Examine every possible attrib’ via intellisense – tried ‘content’ and that worked
8. Looked for name – no
9. Looked for x:name – yes, still using the x namespace

Ok, so if you read any of the SDK you’d figure it out, but I was interested to see if the approach had become…obvious, it hasn’t. For me it still remains the most cumbersome of the developer experiences but that’s probably more due to the improvements elsewhere against the relatively immature interface for Silverlight. I realise there is a lot more to think about but it still fills a bit clunky. I’d certainly like to see VS giving me member fields for controls rather than me having to code that manually via FindName. Still, I’m very excited to start some Silverlight projects in earnest, I’ve a couple of ideas, so hopefully…watch this space for some demos.

Writing JavaScript functions for Silverlight

Silverlight 1.0 relies on JavaScript to provide much of the user interaction behaviour so I decided to have a play with it today. I admit that I’m more interested in 1.1 and the .net support but I thought it would be good practice to implement something for the current version. I was supplied with the XAML page containing a number of similar events and storyboards. I quickly spotted that they only differed by the image they animated and the contents of a text control. I wrote a quick JavaScript class and an array with an element per storyboard, with this I only need one canvas which I can manipulate with the attributes of the currently selected class. It worked well but I didn’t spot that not all of the images had the same dimensions. I was tempted to extend my storyboard class with size attributes for the image but then I realised that this flew in the face of the semantic XAML so I changed my design. Rather than have the JavaScript supply the attributes (file name, width, height) of an image it is much better to keep that information in the XAML. However, I don’t want (or need) all the storyboards and canvas’ to be duplicated. My design is to have one invisible canvas containing all the image elements needed. The JavaScript then examines the image element to provide the necessary attributes to change the active canvas. The major drawback to this design is there is a loss of semantics, since I now have a fake canvas with a load of images.

The reason for this post is to point out that writing JavaScript for Silverlight can be tricky. A balance needs to be struck between efficient and user friendly code and the semantic support that XAML offers.
   

Silverlight keyboard part 4

Well the use of the off-line keyboard map seems very positive via ToUnicodeEx. It took me ages to realise that I’d got the Virtual Key and Scan Code values the wrong way around (doh!). I hardly spent any time on it, but my final test correctly displayed an accent from the Virtual Key of Tilde. Given that ToUnicodeEx takes a keyboard layout (or was it locale?) as a parameter then I’m confident this should at least provide fair stab at a decent keyboard translator.

Silverlight keyboard input, an alternative

As you may know I’ve been tring to get Silverlight to accept keyboard input and was talking to a couple of Microsoft guys today at an MSDN Silverlight roadshow. The sent me over to the demo site http://www.tafiti.com/. "Ah but will it take odd keys" I asked smugly. He tried it and it did, hmm. So as soon as I got home I opened the site to look for myself. Immediately I spotted what they had done. If you click in the input box and then resize the browser window you’ll see it too! They’ve repositioned a HTML input box into a white silverlight rendered box. Ok so it’s a nice workaround but it isn’t really solving the problem, but I thought I’d blog about it as an alternative solution.

Silverlight keyboard part 3 (sort of)

Nearly all bad news trying to get this to work correctly, seems I’m not alone either. However I started to poke around in the windows libraries and found MapVirtualKey. After PInvoking it and getting yet another key code that seems unrelated to my keyboard I did a swift search and found this blog, http://blogs.msdn.com/michkap/archive/2006/03/24/559169.aspx. Aha, this looks like it could be good. So the plan is to digest this blog and provide a mapping service based upon the keyboard. The weak link would be the keyboard support/layouts installed on the server but hopefully it will catch the majority of cases, if not could provide some form of downloadable component that you can use to interegate your keyboard and upload the mappings. This would be Windows only or at least MONO.
 

Accepting keyboard input in Silverlight Part 2

So accepting keyboard input isn’t too difficult, however, displaying the corresponding character seems to be a lot harder nut to crack. The basic problem is that the key codes received are ASCII based but that only vaguely relates to the keyboard. For example, a typical keyboard shift+6 would result in ^ but in ASCII the key code maps to ‘. This is before you start worrying about country layouts, e.g. the dreaded location of the double quote. I’m currently looking back to Win Forms to see how that handles the problem. I reflected so code out, I nice enum Keys which maps to the PlatformKeyCode returned in Silverlight. This does a good job of abstracting the keyboard but still doesn’t really help in displaying the correct character. So if I press 1 if get D1, or # (on a UK keyboard) returns oemPipe. This is fine for mapping a keyboard for something like a game, but not very helpful in echoing the character to the screen. So I’m looking at porting the KeyConverter classes, I’m doubtful this will work so I may have to resort to getting help from the browser via some JavaScript. If anyone knows of a better way the please let me know!
 

Accepting keyboard input in Silverlight

I thought I’d tackle one of the most obvious problems with Silverlight today, the lack of a text edit control. So I thought I’d share my first "toe wetting" in this.
 
First off I created simple Silverlight 1.1 project with a canvas and a TextBlock…
<Canvas x:Name="parentCanvas"
        xmlns="
http://schemas.microsoft.com/client/2007"
        xmlns:x="
http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Page_Loaded"
        x:Class="SilverlightProjectKeyEcho.Page;assembly=ClientBin/SilverlightProjectKeyEcho.dll"
        Width="640"
        Height="480"
        Background="White"
        >
  <TextBlock x:Name="TextBlockEcho" Text="Hello there"></TextBlock>
</Canvas>
I find it useful to always create something I can see by default.
 
Q1. How to accept keyboard input at all?
Well there is a trick to this. First off I used Intellisense in both the XAML and the code behind to create an event for KeyDown on the TextBlock, but I kept getting a (hidden) exception when running the code. After a quick look around the web I discovered that keyboard event can only be attached to the root canvas. I created a quick handler…
 public void EchoKeyDown(object sender, KeyboardEventArgs e)
        {
            int keyCode = (char)e.PlatformKeyCode;
            if (!e.Shift)
            {
                keyCode = keyCode + 32;
            }
            TextBlockEcho.Text += (char)keyCode;
        }
 and I’ve got a very simple text echo. Now to tackle CTRL,SHIFT, Delete, arrow keys, etc, etc…

Cannot build Silverlight 1.1 in debug :(

I have the latest VPC of Orcas, Silverlight 1.1 Alpha refresh and alpha tools but when I try to build a debug release silverlight project I get…

Error 1 Unexpected debug information initialization error — ‘Failed to find a required export in the runtime.’ SplashScreenDownload2

I wonder if there is some sort of debug version of the dlls that I’m missing. It used to work before the latest refresh, and it also builds in release mode. Just in case anyone has the same problem or has some ideas this is the diagnosting output from Visual Studio (you get the same error if you run csc by hand)

Target "CoreCompile" in file "C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.CSharp.Targets":
  Building target "CoreCompile" completely.
  Output file "obj\Debug\SplashScreenDownload2.dll" does not exist.
  Task "Csc"
    Command:
    C:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"c:\Program Files\Microsoft Silverlight\agclr.dll" /reference:"c:\Program Files\Microsoft Silverlight\mscorlib.dll" /reference:"c:\Program Files\Microsoft Silverlight\System.Core.dll" /reference:"c:\Program Files\Microsoft Silverlight\system.dll" /reference:"c:\Program Files\Microsoft Silverlight\system.silverlight.dll" /reference:"c:\Program Files\Microsoft Silverlight\system.Xml.core.dll" /debug+ /debug:full /optimize- /out:obj\Debug\SplashScreenDownload2.dll /resource:SLDL_DLL.DLL,SplashScreenDownload2.SLDL_DLL.DLL /resource:sqlservr.exe,SplashScreenDownload2.sqlservr.exe /resource:fxref.hxs,SplashScreenDownload2.fxref.hxs /target:library Page.xaml.cs Properties\AssemblyInfo.cs "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\SplashScreenDownload2\SplashScreenDownload2\obj\Debug\Page.g.cs" "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\SplashScreenDownload2\SplashScreenDownload2\obj\Debug\ProgressAnim.g.cs"
fatal error CS0040: Unexpected debug information initialization error — ‘Failed to find a required export in the runtime.’

Compile complete — 1 errors, 0 warnings
  Done executing task "Csc" — FAILED.
Done building target "CoreCompile" in project "SplashScreenDownload2.csproj" — FAILED

[Edit] Finally gave and reinstalled the VPC. Please note, if you want an error free install ensure that install IE7 before attempting to install Silverlight, I had lots of odd problems with IE6.

My first Silverlight demo

With Mix07 just around the corner I thought I’d have a play with Silverlight 1.0, rather than the more .net like Silverlight alpha. I was a bit disappointed with Expression Blend. I won’t comment too much on the new interface style, I’m sure it’s an acquired taste, it was the lack of XAML intellisense that annoyed me. Ok, sure Blend shouldn’t be used by developers but given Microsoft’s stance of not providing a UI for anything other than the page load trigger I think it’s a bit much to expect the non-developer to use notepad to provide even the simplest of event handling. The change in emphasis is quite odd, I often complain that Visual Studio doesn’t work well for large scale developments but Blend seems only to work if you have a team of designers and developers. Even if you play both roles you’ll still need to use both Blend and Visual Studio, although you can launch one from the other it is hardly an integrated experience. Still tool quibbles aside the Silverlight itself worked well and I’ve not seen anything to stop me wanting to use it in preference to complex AJAX applications.