Silverlight Example Apps

Mon, May 12, 2008, 06:32 AM under Silverlight
I've seen introductory sessions where people jump straight into Visual Studio and/or Blend and start demonstrating how to build a Silverlight application. IMO, Silverlight is a relatively new technology and there are potentially people that have not seen examples of applications built with it. As such it is important to demonstrate its capabilities first by running some applications and clicking around. There are many samples to choose from the Showcase and from the Gallery, so take your pick.

In my sessions I show my favourites (i.e. the ones that appeal to me personally, for one reason or another).

1. Hard Rock Memorabilia (shows the DeepZoom feature in a public released site)
2. Silverlight Airlines (gets you thinking of great user experience for booking a flight)
3. Cameras (another example of great user experience for shopping online scenario)
4. Image Snipper (shows graphics and interaction you would only expect from a desktop app)
5. Video Puzzle (combination of a game with video elements)

...then before jumping into code, it is worth showing some of the controls that are available and also how they can be skinned (templated):
6. Control Demo (not all of them, but gives you an idea)
7. Corina's control skins Flat, Bubbly, Red, Rough.

...if you are looking for a sample that combines skinning, the OpenFileDialog, IsolatedStorage and also throws in a bit of extensibility, do check this out:
8. Calculator (get its story from the author's blog post)

Finally,
9. a great business application that is almost indistinguishable from a local client and has only recently been made available is the Healthcare Demo (built in the UK).

What publically available Silverlight application(s) float your boat?

Last Flash issue for me

Thu, May 8, 2008, 01:48 AM under Links
In last’s week Flash issue, I wrote 500 words About Silverlight 2.

I have enjoyed being the editor of the UK MSDN Flash newsletter. Ever since I took it over, it has topped Microsoft's (worldwide) newsletter growth stats compared to previous years in more areas than one. Additionally, its format inspired other newsletters from other Microsoft subsidiaries outside the UK. Hope you don't mind me blowing my own horn and since I can't publically back up these claims with numbers, you'll just have to take my word for it ;-). Exactly a year after the first issue I edited, the time has come for me to hand the newsletter back and I look forward to receiving it with a bit more anticipation as to what content I'll find inside!

Thanks to everyone that stayed tuned to that Flash feed, and I also hope you'll stay tuned to my blog feed.

LINQ to XML, namespaces and VB

Tue, May 6, 2008, 06:30 AM under dotNET | LINQ
Recently I was playing with some LINQ to XML for a demo I was preparing and was having trouble retrieving the expected values from what was a very straightforward query.

Have a look at the XML file that looks like this (the results of programmatically calling this Amazon service).

Each Item element represents a book and I wanted to retrieve the Title. How would you form that query with LINQ to XML?

I went for the obvious:
  var res =
from ia in XElement.Parse(e.Result).DescendantsAndSelf("ItemAttributes")
select ia.Element("Title").Value;
When that did not produce the expected results I scratched my "tired" head at the time and pinged MikeT who came up with the correct way of doing this (you still have time to work it out on your own).

The clue (and at the same time further "excuse") is that all my previous experiments with LINQ to XML involved using my own demo XML files that never had namespaces inside so I forgot all about them (haven't paid the tax in a while). I find quite ugly what you have to do to incorporate namespaces in a LINQ to XML query, but there seems to be no nicer alternative to the following (thanks Mike):
void SomeMethod()
{
var res =
from ia in XElement.Parse(e.Result).DescendantsAndSelf(n("ItemAttributes"))
select ia.Element(n("Title")).Value;

// TODO use res
}

static XName n(string name)
{
return XNamespace.Get("http://webservices.amazon.com/AWSECommerceService/2005-10-05") + name;
}
I still didn't like this solution for the simple demo I wanted to use it for. So, I recalled VB's superior support for XML and I converted the project to VB and used the following instead which needs no extra method and is all round more elegant:
  Dim res = _
From ia In XElement.Parse(e.Result)...<n:ItemAttributes> _
Select ia...<n:Title>.Value()
...and if you are wondering where the n comes from, that is at the top of the VB file:
Imports <xmlns:n="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
...another aspect of VB's beauty and another thing I had the opportunity to mention in my demo ;-)

Lenovo Fn key

Sat, May 3, 2008, 03:52 PM under UserInterfaceDesign
Very recently I received (from work) a new laptop: Lenovo T61p (to replace my aging Toshiba M5). There are quite a few gotchas with setting up this machine (e.g. I wasted an hour trying to get it to see a second internal drive), but I will spare you my setup/installation experience. Instead, you may be interested in Keith's helpful post here. Generally, I am happy with this machine from a performance perspective.


There is however the quite important issue of its keyboard: it's the laptop keyboard from hell. Why the "£$^&* don't we have a universal standard for laptop keyboards yet? The placement of keys on this laptop is weird (e.g. the ESC key is further up than the top row of keys instead of being aligned with the Function keys) and also keys I usually expect to be more easily accessible than other keys (e.g. up, down, left, right arrow keys) are actually... smaller and cramped close to the others!

However the biscuit goes to the Fn key placement in relation to the Ctrl key. I expected the Ctrl key to be firmly placed in the bottom left and for it to be larger than other keys. Instead, the Ctrl key is normal size and it is 2nd from the bottom left, its place taken by the rarely used Fn key! What is worst is that, apparently, there is no keymapping software that can fix this, since Lenovo in their wisdom have made it permanent in the firmware :-(

One of the worst examples of how this trips me up is copy/paste (Ctrl+C, Ctrl+V). I have some source window where I do a copy (but in reality I only did an Fn+C without realising it) and then close the window, switch to my target window and do a paste (in reality a Fn+V) and nothing happens. Then I realise my mistake but it's too late to do a Ctrl+V now since the copy was never actioned... Arghh!

If you think that I am overreacting, first try using a keyboard like that before passing judgement. If you own one and think I am overreacting, clearly you haven't tried pressing Ctrl+Shift+B (Build Solution in Visual Studio) or Ctrl+Shift+Esc (bring up Task Manager) with just one hand (impossible!). Anyway, it looks like I am not alone judging by the collections of complaints here, here, here and here amongst other places.

My partial solution: I removed the offending key completely (screenshot).

As an unrelated aside, the Mac Air suffers from the same bewildering choice of placement of the Fn and Ctrl keys. As a more related aside, if you see me struggling to type in my upcoming events, now you know why!

<end of rant/>

May Events

Mon, April 28, 2008, 01:28 PM under Events
Just came back from a much need holiday (in Madrid) and since I have no new technical content to post, I thought I'd follow my blog's tradition (Jan, Feb, Mar and Apr) and list the events that I am presenting at in May. Funny thing is that after a recent storm of flights, all of the below involve flights as well. Will I ever get sick of this?

+ 1st, Manchester, MSDN Roadshow 2008.
+ 10th, Glasgow, DDD Scotland.
+ 13th, Glasgow, MSDN Roadshow 2008.
+ 16th, Newcastle, MSDN Roadshow 2008.
+ 22-23, Amsterdam, DevDays 2008.

A week after I fly back from Amsterdam, I fly to Orlando for Tech Ed US (more on that nearer the time).

DevDays 2008 in Amsterdam

Mon, April 28, 2008, 01:04 PM under Events
Last year I presented for the first time in the Netherlands at DevDays. This year the organisers invited me back to present 3 talks (different to the 3 from last year) on 22 and 23 May. Register from here.

I will post on my blog resources for all 3 sessions once they are done, but for now, here are the session times, room and title info:

- Thu, 10:50-12:00, Auditorium, Introduction to Silverlight 2

- Thu, 16:30-17:40, Auditorium, Five Cool Things to Know and Use for Smart Client Development with VS2008 and the Fx 3.5

- Fri, 15:00-16:10, Zaal Forum, Parallel Extensions to the .NET Framework

For the abstracts of the sessions above or to view the full conference schedule, click here for the Thursday and here for the Friday. Hope to see you there!

Networking in Silverlight 2 Beta 1

Tue, April 22, 2008, 06:35 AM under Silverlight
For the actual real content of this post I'll defer to other links, but at least you'll have all those links collected in one place: here ;-)

In a nutshell, Silverlight 2 fully supports networking and calling services. It would be crazy if it didn't because by choosing the SL model you are choosing to run your application entirely on the client side (i.e. with no postbacks) so where will the real data come from (given that you are sandboxed in the browser and hence cannot access local data sources)? You have to connect somewhere to get it.

The High Level Statement
Broadly speaking there are 4 options (which you can combine of course) to satisfy the requirement:
1. Call self-describing services such as asmx, WCF, Java services or anything else conforming to SOAP. This is what is mostly used in the enterprise space and you can imagine behind the service a database so the service is a facade into that.
2. Call URL-based services (aka POX or REST) where you must construct the URL yourself by piecing information you read from the service's documentation and then parsing the results that come back which is typically a lamp of XML or JSON. Think e.g. services from amazon, ebay, flickr, youtube, digg etc
3. Consume RSS or ATOM feeds. Hopefully I don't have to give examples of syndication here ;)
4. Raw sockets where communication takes place over the TCP channel.

Links Covering the 4 Sub-Topics Above
- Quickstart on Building a WCF Web Service and Accessing It by Using a Proxy
- Quickstart on Sending and Receiving Plain XML Messages
- Quickstart on Accessing Syndication Feeds with Silverlight
- MSDN Documentation on Working with Sockets
- Karen's post on Silverlight's HTTP Networking Stack
- Wilco's post on HttpWebRequest in Silverlight
- Mahjayar's post on Rundown of webservices-related Functionality in Beta 1
- Mike's post on Silverlight 2 and Sockets
- Tim's post on Calling Web Services in Silverlight 2
- MSDN Documentation on Accessing Web Services in Silverlight (6 rich sub sections)

"I only have 1 hour and 5 minutes to look into this stuff, where should I go?"
You need to watch the session from MIX titled "Working with Data and Web Services in Microsoft Silverlight 2" delivered by Eugene. The direct link to the WMV file is here (save as).

Getting Started with IronPython

Sat, April 19, 2008, 05:45 AM under Links
My TODO list has had for a while to find some time to play with the Dynamic Language Runtime (DLR) and I may find an excuse to do that soon given that it is supported (and aligned to ship with) Silverlight 2. In the meantime, I needed a true expert to write a short related article for the MSDN Flash. All my research pointed to one guy and he happened to be based in the UK too: Michael Foord. Read his succinct 500 words on getting started with IronPython here (scroll down). Like I stated in my Flash intro... "exciting times!"

Silverlight 2 Essential Getting Started Facts and Guide

Thu, April 17, 2008, 01:20 AM under Silverlight
As someone pointed out to me, I jumped straight into this "Silverlight thing" without doing a "Hello World post". Part of the reason for that is that this is covered in many online places already, but anyway, here goes my take...

Holding Your Hand for Clicking in the Right Places
After you install the bits we released at MIX (the only must is the SL tools for VS2008), go "File->New Project" and select the Silvelight tab (screenshot). You have two options: creating an Application or a Library (a dll you can reference form other SL apps). Select an Application, type your project name (e.g. HelloWorld) and (tip: I also like checking the "Create directory for solution" checkbox) click OK and you'll be confronted with a new dialog (screenshot). Of the 3 options only the 2 top ones are enabled for this scenario and I'll say off the bat that the 2nd option is fairly useless, so let's stick with the first option which is more interesting and powerful. What this option suggests is that it will create 2 projects for you: the Silverlight application project (the results of which run client side in the browser) but also a vanilla web project (that will run server side) to host your Silverlight app. Unlike most people I prefer "Web Application Project" to "Web Site" so change the "Project Type" combobox and click OK. Your solution now has two projects: HelloWorld and HelloWorld_Web (screenshot). Build it now (Ctrl+Shift+B) and notice the addition of a ClientBin folder in your HelloWorld_Web tree.

The Web Project
Delete the Default.aspx, file it is useless. We are left with two files (HelloWorldTestPage.aspx and HelloWorldTestPage.html) of which we will use only one at any given time (switch between them by right clicking and "Set As Start Page"). Both serve the same purpose which is to host the Silverlight plugin in which our SL application will be loaded in (think of them as test harnesses at this stage). Do a "View Code" on each from the right click menu (or click on the two links above) and take your time to look inside. I do not intend to go through the markup (please follow all links in this paragraph for more). Both files accomplish the same thing. One using the object tag with application/x-silverlight and the other using the asp:Silverlight tag, they point the Source of those to ClientBin/HelloWorld.xap. That is how the plugin knows where to look for the Silverlight application. So, you can correctly infer from this that your Silverlight project compiles to a XAP file and the build process then copies that to the web project's ClientBin folder. For now, please hold the question "What is this XAP thing?".

Before we move on to examine the Silverlight project, right click on the solution node and select "Add->New Project" and again choose "Silverlight Application" and click OK (screenshot). Notice how now the 3rd option is enabled? This is how you could add a Silverlight project to existing solution (instead of starting from scratch like we did) - Cancel the dialog. Another way to add a Silverlight project to an existing Web Project is by right clicking on the HelloWorld_Web project treeview node and select "Add Silverlight Link" and using that dialog. Now that we are comfortable with the web site aspect of things, let's look at the Silverlight project.

The Silverlight Project
Expand the References node in the Silverlight project. Most of the names of those assemblies will be familiar to you but bear in mind that these are the Silverlight variants/versions that will generally be a subset of what you are familiar with in the full .NET Framework.

Right click on the App.xaml node and select "View Code" which will bring up App.xaml.cs. Two of the self-explanatory event handlers in there are for you to use as you see fit (Exit and UnhandledException) and the most important one has been pre-populated for you: Startup - this is the entry point to the Silverlight app. You could handle here parameters passed from the markup (e.InitParams). By default it sets the Application.RootVisual to point to the other class in this project: Page (Page.xaml + Page.cs).

Right click on the Page.xaml node and select Open or just double click on it (screenshot). If you have done any WPF development this will be familiar in the sense that it is all about the eXtensible Application Markup Language (XAML).
Both WPF and Silverlight use the same declarative, tool-friendly XAML-based UI development. The rough idea is that you drag and drop controls on the design surface at the top, set the properties of the controls via the properties window and potentially make some tweaks to the XAML that gets generated in the pane at the bottom. You can then hand this to a designer that will use another tool (currently Expression Blend 2.5) to really jazz it up, add their bling and then hand it back to you whilst the code behind in the Page.xaml.cs that you wrote (that contains the real business logic) remains intact. The reality at this stage of the Beta 1 is that the designer is read-only and the properties window doesn't work and Blend 2.5 also has some more work to be done to it. What this means is that currently in Beta 1, as a developer, you have to manually type all of the XAML for the GUI layout of your Silverlight application.

Within the existing Grid tag, type:
<TextBlock Text="Hello Silverlight World"/>

Build the solution. Using Windows Explorer navigate to the ClientBin (or just use Open Folder in Windows Explorer) and find the HelloWorld.xap file. Not to repeat myself here, please visit this post, read the first paragraph and then jump to point 4 and 5 and then come back here, we'll be waiting.

Run (F5)
Run the project (obviously the start up project for the solution is the Web project) and notice your browser coming up showing what you would expect. What has happened here is that the html or aspx page instantiated the SL plug-in, which then instantiated the Silverlight CLR, created an AppDomain and then downloaded the XAP file, opened it up and found the entry point at which stage it passes control over to your code.

When you right click anywhere on the page, you see the Silverlight menu option which just shows the "About" dialog with versioning info. You can tweak the size of the Silverlight plug-in in the host page (html or aspx) so it does not occupy the entire page. This is a way of creating an "island of richness" on an existing web page. I leave that as an exercise for home ;-).

For Further Info
- Truly Excellent Section on MSDN(read all of it following all the links)

OpenFileDialog and FileDialogFileInfo in Silverlight 2 Beta 1

Wed, April 16, 2008, 02:38 AM under Silverlight
From a Silverlight 2 app we can prompt the user with a safe OpenFileDialog (OFD) so they can choose a file from their file system that we can then use in our application. It is interesting to contrast it with the existing OFD types that we have in the full framework. We have one for Windows Forms (in System.Windows.Forms namespace in same named assembly) and one for WPF (in Microsoft.Win32 namespace in PresentationFramework.dll assembly):

In the diagram above, I have filtered out many methods and properties so if you are interested in those please visit the hyperlinks I embedded above. Also, on a totally separate note, you may be interested in the new features that the WinForms dialog was enhanced with in Fx 2.0 SP1.

The Silverlight variant does not have any of the rich features (e.g. setting the title, readonly configuration, advanced extension usage, checking for file/path existence, setting initial directory, validation, showing help etc). It also does not have any parent classes (other than Object), so all required methods are defined on the OpenFileDialog class itself (which resides in the System.Windows.Controls namespace in the System.Windows.dll assembly). Below is the complete list of its members PLUS a new type (FileDialogFileInfo) that is introduced specifically for Silverlight:

The Filter and FilterIndex properties work just like the desktop counterparts (as do the obvious ctor and Dispose method). EnableMultipleSelection is also obvious, but it is worth noting the departure from the name used in the other two variants: Multiselect. Also obvious is the ShowDialog method but without following the link can you tell what the return type is? Up to this point you couldn't really tell if the SL dev team borrowed the design from the WPF team or from the WinForms team. Note that the WPF variant of ShowDialog returns a nullable Boolean (an interesting choice). The WinForms variant of ShowDialog returns the same type that the Silverlight variant returns: a DialogResult enumeration!

OK, enough of the obvious, let's move on to the not so obvious and see where the new type FileDialogInfo comes into play. The answer comes when we examine the return type of the SelectedFile property and find that it returns a FileDialogFileInfo object (and correspondingly the SelectedFiles returns a collection of FileDialogFileInfo objects). So, for security reasons, we are not given a path to the file that the user selected, and instead we are given an object from which we can discover the Name of the file and can open it as a stream (OpenRead or OpenText). Sample code:
var ofd = new OpenFileDialog();
ofd.EnableMultipleSelection = false;
ofd.Filter = "Txt Files|*.txt|Silverlight Video Files|*.wmv";
ofd.FilterIndex = 2;
if (ofd.ShowDialog() != DialogResult.OK)
return;

FileDialogFileInfo fdi = ofd.SelectedFile;
lbl.Text = fdi.Name; // lbl is a TextBlock
if (ofd.FilterIndex == 1) //not robust but hey..
{
StreamReader sr = fdi.OpenText();
txt.Text = sr.ReadToEnd(); // txt is a TextBox
sr.Close();
}
else if (ofd.FilterIndex == 2) //not robust but hey..
{
wmv.SetSource(fdi.OpenRead()); // wmv is a MediaElement
}

See it running in action here (plus a bit more). Get the source via the usual decompiling method.