X technology is dead

Wed, September 15, 2010, 03:10 AM under Silverlight

Every so often, technology pundits (i.e. people not involved in the game, but who like commenting about it) throw out big controversial statements (typically to increase their readership), with a common one being that "Technology/platform X is dead".

My former colleague (who I guess is now my distant colleague) uses the same trick with his blog post: "iPhone 4 is dead". But, his motivation is to set the record straight (and I believe him) by sharing his opinion on recent commentary around Silverlight, WPF etc. I enjoyed his post and the comments, so I hope you do too :-)

Silverlight 2 Beta 1 Namespaces – Part 4 – the WPF subset

Wed, May 28, 2008, 12:00 PM under Silverlight
Following from Part 1, Part 2 and Part 3, in this last part of the exploration I'll focus on the UI layer and I'll have even more of a statistical hat on.

11. System.Windows.dll is yet another Silverlight assembly with no direct counterpart in the full framework, but with tons of stuff inside (as evidenced by its size on disc and by the 21 namespaces!) that makes it the 2nd largest assembly. You can think of it as the brick that gives Silverlight its WPF UI. Its namespaces come from various v2.0 and v3.0 desktop assemblies as listed below (and it is in my opinion a prime candidate for refactoring):

-System.Net namespace with WebClient plus 6 related classes comes from the desktop's System.dll (!)

- System.ComponentModel comes from System.dll (! again) and is basically the BackgroundWorker implementation.

- 5 of its namespaces (System.Windows.Controls.Primitives, System.Window.Data, System.Windows.Documents, System.Windows.Resources, System.Windows.Shapes) and the System.ComponentModel.DesignerProperties class map to the desktop's PresentationFramework.dll

- 3 of its namespaces (System.Collections.ObjectModel, System.Collections.Specialized, System.Threading) map to WindowsBase.dll.

- 2 of its namespaces (System.Windows.Ink, System.Windows.Media.Imaging) map to the desktop's PersentationCore.dll.

- System.Windows namespace has a total of 61 types, coming from homonymous namespaces in PresentationCore.dll (e.g. FontStyle, RoutedEventHandler) and PresentationFramework.dll (e.g. Application, FrameworkElement) and WindowsBase.dll (e.g. DependencyProperty, Point) and also introduces some new types (e.g. AssemblyPart, ErrorType).

- System.Windows.Markup namespace with 2 types from WindowsBase.dll, 2 from PresentationFramework.dll and 1 from PresentationCore.dll.

- System.Windows.Media namespace which maps to PresentationCore.dll except for Matrix class from WindowsBase.dll and 5 new Silverlight types (MediaElementState, TimelineMarkerCollection plus 2 relatives and VideoBrush).

- System.Windows.Input largely maps to PresentationCore.dll, except for 2 classes (Key and ModifierKeys) from WindowsBase.dll and 1 class (KeyboardNavigationMode) from PresentationFramework.dll. There is also one new class in there: StylusInfo.

- System.Windows.Controls namespace has 24 types that come from PresentationFramework.dll (same namespace name of course). It also has 2 types (MultiScaleImage, MultiScaleSubImage) that make up the DeepZoom feature. It also has 3 types (2 from System.Windows.Forms.dll plus 1 brand new) that make up the OpenFileDialog feature.

- System.IO.IsolatedStorage.ApplicationSettings class has no counterpart in the desktop world and was touched upon here (scroll to the bottom).

- System.Windows.Interop namespace with 3 classes (Content, Settings and SilverlightHost) that is all new in Silverlight framework (even though that namespace name exists in various other WPF assemblies).

12. and 13. System.Windows.Controls.dll and System.Windows.Controls.Extended.dll
The overwhelming majority of the Silverlight controls reside in the System.Windows.Controls.dll assembly. The Extended.dll adds the Calendar, DatePicker, Slider and WatermarkedTextBox.

14. System.Windows.Controls.Data.dll
This adds a control not available at present in WPF: the Silverlight DataGrid. For all things DataGrid-related visit Scott's blog.


Tue, May 27, 2008, 08:36 PM under dotNET | Silverlight
A cool class that was introduced in .NET Framework v2.0 is the BackgroundWorker. If you do any kind of UI development I encourage you to learn about this class (e.g. by following the links below), which makes it easy to execute long running operations on a separate thread, supporting cancellation, progress reporting and marshalling results back to the UI thread.

Back in 2004 I described what the class looks like (inc. links to MSDN) when I implemented it for the .NET Compact Framework v1.0/v2.0 (and for .NET Framework v1.1): BackgroundWorker. I also provided sample code to demonstrate the usage.

An added incentive to learn about it is that Silverlight 2 includes a fully interface-compatible version of BackgroundWorker. A good way to learn about it is by porting to Silverlight the desktop PI sample from my previous blog post and follow what the code does... have fun!

Silverlight 2 Beta 1 Assemblies – Part 3 – the v3.x subset

Tue, May 27, 2008, 05:03 AM under Silverlight
Following from Part 1 and Part 2, in this part of the exploration we look at assemblies in Silverlight that were introduced with the desktop framework's v3.0 and v3.5.

5. System.Runtime.Serialization.dll is an assembly with 3 namespaces introduced with .NET Framework v3.0 and it is also supported in Silverlight. System.Runtime.Serialization is present in the Silverlight implementation with most of the classes available. The System.Xml namespace in this assembly has support for the Dictionary but not for the MTOM, Binary or Text reader/writers.

6. System.ServiceModel.dll is a tiny subset of the full WCF v3.0 implementation. In a nutshell, 5 of the 15 namespaces are here and furthermore they are very thin with many classes missing and with existing classes missing members. Essentially, currently, Silverlight supports calling WCF services using the basicHttpBinding only.

7. System.ServiceModel.Web.dll is the assembly introduced in WCF v3.5 and, again, Silverlight only offers 1 namespace (out of the possible 10) and it only has the one self-explanatory type: System.Runtime.Serialization.Json.DataContractJsonSerializer.

8. System.Core.dll was also introduced in Fx v3.5 and I listed what it offers on item 9 here. The Silverlight variant offers the TimeZoneInfo class (but no custom timezone support), full LINQ to Objects support (System.Linq, System.Linq.Expressions and System.Runtime.CompilerServices) and just a drop from the System.Security.Cryptography namespace (Aes and AesManaged classes).

9. System.Xml.Linq.dll is an identical to its Fx 3.5 desktop counterpart. The only thing missing are the Save methods because in Silverlight we cannot arbitrarily save to the user's machine outside IS.

...and finally, not fitting with the title of this blog post, but included nonetheless...

10. System.Windows.Browser.dll is an assembly unique to Silverlight for now, and it offers the ability for managed code in a Silverlight app to interact with other browser elements. I described it fully at my HTML Bridge post.

Silverlight 2 Beta 1 Assemblies and Namespaces – Part 2 – the v2.0 subset

Mon, May 26, 2008, 07:29 PM under Silverlight
In a previous post I showed where we find the assemblies that make up the Silverlight 2 Beta 1 framework. Have a quick glance at the screenshots to remind yourself. Below, I follow up on the promise in my closing sentence of that blog entry.

1. mscorlib.dll includes almost 30(!) public namespaces, which means it is missing only about 20 namespaces compared to the desktop full version. Of course, even when the namespace exists in both versions of mscrolib, there are some types missing from the Silverlight version. In general terms the omissions are to do with: hosting, remoting, registry access, non-generic collections, serialization and some of the security types that are Windows-specific (e.g. System.Security.Principal/Policy/Permissions/AccessControl namespaces). We also find some types having members missing (e.g. the GC class does not have overloads of Collect that accept the generation to collect, no ThreadPriority etc) but nothing major. On the flip side, Silverlight adds some new sporadic members of its own e.g. a new NoOptimization value to the MethodImplOptions enum, and new attribute classes such as System.Security.SecuritySafeCriticalAttribute and System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute. Generally speaking, there are tons of stuff in this assembly, the largest of them all in the Silverlight framework, so please explore on your own the compatible subset.

2. System.dll has just 6 public namespaces so it is 30 short of its desktop brother (but we'll see later that some of those are available in other Silverlight assemblies). The things truly missing though make sense such as: CodeDom, the specialized and generic collections (except for Queue and Stack which are present), configuration classes for reading appsettings, performance counters, tracing (but a thinner Debug class is present), EventLogging and SerialPort support. Whilst support for regular expressions is there, you cannot CompileToAssembly.

3. System.Xml.dll is missing the entire Xsl and XPath namespaces and even the support it has for Schema and Serialization is minimal at best (a total of 1 concrete class, 1 interface and 1 enumeration!). The main namespace (System.Xml) is almost fully implemented though with some additions as well (e.g. XmlXapResolver class and DtdProcessing enum) and notable omissions the Text reading/writing and the DOM model (XmlDocument and relatives).

4. System.Net.dll is a bit weird. You see, on the full framework there was a System.Net.dll introduced with .NET Framework v3.5 that had all the P2P stuff. However, the assembly here in the Silverlight framework has absolutely nothing to do with any of that! Instead, this assembly is all about sockets. On the full framework the implementation of sockets has always lived in System.dll (which we saw further up), so not sure why the factored out the 2 namespaces (System.Net and System.Net.Sockets) into this one. Maybe it is because, not only there are many types and methods missing, but also there has been some "butchering" that renders many things incompatible with each other (such as changing concrete classes/methods to be abstract, changing the type returned from various methods and adding new members to various places). The principles are the same though and, in a nutshell, you can connect back to your server asynchronously via sockets (but you cannot listen/accept).

Next time we'll see the Silverlight assemblies that stem from v3.0/v3.5 desktop counterparts.

My Silverlight session

Thu, May 22, 2008, 10:19 AM under Silverlight
I am giving a 75-minute Silverlight 2 Beta 1 session at various places and this blog post summarises the session pointing to resources for those that attended (and maybe useful for those that haven't).

You can download the entire PowerPoint slidedeck (save as PPTX) – it follows the following steps.

Step 1: First I go through 2-3 slides ensuring everybody realises that Silverlight is a cross-browser, cross-platform web technology that utilises .NET in the browser.

Step 2: Demonstrate some apps to give an idea of the kind of rich apps we can build - a subset of these samples.

Step 3: After a slide on what needs to be installed I move to the AGENDA. My AGENDA slide has 5 items on it, which are the following 5 steps (4 to 8).

Step 4: Getting Started aka Hello World.

Step 5: Intro to XAML inc. developer-designer interaction using Blend.

Step 6: HTML Bridge.

Step 7: Networking.

Step 8: IsolatedStorage and OpenFileDialog (i.e. File System Access).

Step 9: Finally, a summary pointing to your one-stop URL for Silverlight: silverlight.net.

Thank you to those that attended (or plan to attend) this session.

XAML: Level 100

Mon, May 19, 2008, 03:29 PM under dotNET | Silverlight
Since you are reading my blog, chances are that you are a .NET developer. Do you realise that eXtensible Application Markup Language (XAML) is now part of .NET? Are you familiar with it? How would you describe XAML (pronounced "zammel") to someone that is not familiar with it if you only had 10-20 minutes? Below is my take.

XAML was introduced as part of Windows Presentation Foundation (WPF) which was released in November 2006 as part of .NET Framework v3.0. In addition, XAML is at the core of Silverlight, v2 of which will be released this year. Whilst XAML itself is independent of those two technologies, I am a practical person so I associate XAML with those two presentation technologies (WPF for the Windows desktop and Silverlight for the cross-platform browser) and have no qualms in intermixing those terms in this blog post. The XAML that Silverlight 2 will support is a subset of the XAML that WPF supports but the core principles and most capabilities are the same.

XAML is an XML language for describing a hierarchy of objects and their properties; in our concrete examples, it describes a hierarchy of visual objects that make up a Graphical User Interface (GUI).

Relationship to managed code
An important fact about the XAML elements (more precisely the WPF/Silverlight graphical system and controls) is that they are fully composable. For example, the following screenshot shows some crazy XAML that places a TextBox inside a button as its content (and in the bottom right corner the result):

It is important to note that anything you can do with XAML, you can also do in code (C#, VB etc). For the previous example, the alternative code required is a single statement in the ctor:

Regardless of that important fact, it is our preference to use XAML for the (naturally) declarative part of describing a GUI. We then use code, of course, to programmatically react to user interaction with the GUI elements that were declared in XAML, i.e. we use code to capture the behaviour.

The obvious question that arises is how we connect the XAML bits to our managed code. In brief, the technique of partial classes ensures that the XAML bits and the managed code bits end up making a single class. XAML properties assign names to controls so we can reference them in the code-behind and, finally, XAML properties connect events in XAML to event method handlers in code. The following screenshot shows a GUI where clicking on the button, updates the time in the textbox.

Take a look at the combination of XAML and C# to achieve this.

Tool Support and the Designer-Developer Workflow
Visual Studio 2008 has a designer tool that allows you to type XAML (with full intellisense) and instantly see the results. For WPF projects it allows you to also drag and drop controls onto the surface and have the XAML generated for you. Have a look at this VS2008 screenshot of Silverlight designer.

For Silverlight 2, the VS2008 is just a read-only designer so you have to type things in the XAML pane or use an external tool to generate the XAML such as Expression Blend.

Expression Blend allows your designer friends to work on the same project/solution and more importantly on the same XAML that you, the developers, are working on.

Have a look at the screenshot of the exact same project you saw just now, but this time in Blend.

That is one of the reasons XAML is an XML-based language: XML is very toolable. Because of that we have a nice workflow between designer people in Blend and developer folk in VS2008, where there is no exchange of bitmaps or binaries but they are both truly working on the same asset: XAML files. The designer-developer interaction for WPF with XAML is described in this paper.

In my relevant demo, I use Blend to style the Button, add a storyboard for animating it and changing the background color to the LayoutRoot to a gradient color. You can see glimpses of that in both of the above screenshots of VS2008 and Blend, so revisit them paying attention to the XAML parts.

Concepts Worthy of Further Exploration (MSDN links)
If you are a seasoned .NET developer, you'll find that XAML/WPF/Silverlight introduce some new concepts. Below I list MSDN links to the top 5 areas I recommend you investigate – just follow the hyperlinks.

- The Layout System. Note that from the list of layout panels, Silverlight 2 only supports Canvas, StackPanel and Grid. Explore all 3 by changing the LayoutRoot type and dragging various controls on it. This is a good time to grok Attached Properties.

- Dependency Properties. These are important to understand because they enable the following 3 equally important areas:

- Animations (in my session I make a button fly around a bit when clicked).

- Databinding (in my session I bind the results of a WCF call to a list).

- Control Styling/Templating (in my session I change a button to look like a happy face)

Conclusion – XAML levels of competency
If you have been ignoring XAML so far, I don't think you can afford to do so any longer. IMHO there are 4 levels of XAML competency:

Level 100 – truly understand all of the above.

Level 200 – confidently read XAML (e.g. as spat out by VS2008 or Blend).

Level 300 – be able to type XAML yourself with an aim to create a structure of a bland GUI (setting basic properties and hooking events etc).

Level 400 – create styles, templates, animations and set gradient colours by hand.

FAQ - What do I need to develop Silverlight 2 Beta 1 apps

Tue, May 13, 2008, 07:43 AM under Silverlight
Based on questions I receive, there seems to be some confusion as to what needs to be installed in order to develop Silverlight applications.
You only need ONE download: Silverlight 2 Beta 1 Tools for Visual Studio 2008 RTM (notice the file name is "chainer"). Note that this is not compatible with the recently released Orcas SP1.
Optionally, if you have designer friends or you are a graphically inclined developer, you can download the Expression Blend 2.5 CTP (build 2.1.1113.0 is the one that also works with .NET Framework v3.5 SP1). The truth is that if you aspire to create truly rich Silverlight applications, you will need to hire designer people and have them use Blend.

The confusion arises because we have other downloads, which are actually included with the chainer install at the top so no need to install separately:
1. Runtime - essential as this is the actual SL plugin (and also the only thing end users need to install – about 4MB taking about 4-10 seconds)
2. SDK - Includes the asp:Silverlight control that you place on aspx pages and also a whole bunch of Silverlight assemblies that you may wish to use (and deploy) with your Silverlight application.

If you are having trouble getting everything installed, read this highly referenced post and if you are still having problems post them to the dedicated forum.

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)

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?

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).

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)

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
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.

IsolatedStorage in Siverlight 2 Beta 1

Tue, April 15, 2008, 01:49 AM under Silverlight
Silverlight applications can store data (in files) onto the user's machine via the good old Isolated Storage mechanism. The API and restrictions of Isolated Storage are slightly tweaked in the Silverlight framework. Let's explore that.

Background Research
On both the full (aka desktop) framework and the Silverlight framework the implementation resides in mscorlib.dll and specifically the System.IO.IsolatedStorage namespace. On the desktop framework the classes in there are shown on the following class diagram (with the 2 most interesting classes collapsed for exploration later):

Note that in the Silverlight implementation there is no base abstract class IsolatedStorage as on the desktop or INormalizeForIsolatedStorage interface or IsolatedStorageScope enumeration. If you explore the desktop capabilities following the links above and relate them to Silverlight's restrictions you'll see why that is – I will not explore that in this post. Also note that the IsolatedStorageException class is available in Silverlight.

On the flip side, when looking in the namespace in the Silvelright version of mscorlib we additionally find the IsolatedStorageSecurityOptions enumeration that is only used by the other new type in the namespace: the IsolatedStorageSecurityState class which itself is not used or exposed publically by anything AFAICT! So basically, just ignore these two types for now as I can only presume that someone forgot to mark them as internal.

Using It
So back to looking at useful classes, and we are left with the 2 that exist in both variants (that are collapsed on the diagram further above): IsolatedStorageFile and IsolatedStorageFileStream. If you follow the links to the Silverlight documentation for those you'll find some differences compared to the desktop version and maybe the eagle-eyed among you can spot them in the following list of methods:

The IsolatedStorageFileStream class is the same as the desktop version but it omits 5 overloads of the constructor (the ones that have a bufferSize option and the ones that do not have the IsolatedStorageFile argument). The IsolatedStorageFile class has 12 static methods removed (the GetXXX methods except one) and also adds 10 members of its own (I have marked these with an asterisk * in the screenshot above).

OK, enough of API spelunking; how do you use this thing? That's the easiest part as you just follow the pattern of:

1. Obtaining an IsolatedStorageFile (e.g. via the static method GetUserStoreForApplication)
2. Creating an IsolatedStorageFileStream object passing it in the reference from step one
3. Creating a normal System.IO. StreamWriter or StreamReader passing it in the reference from step two
4. Using the Stream to read or write as per usual.

I have a basic SL app that uses iso storage here so have a play by entering some text/values and close/reopen the browser to see them remembered. To look at the code, follow the steps here. To browse on your local machine to the storage, paste this in your windows explorer (and drill in to find a moth file and a _LocalSettings):

Wait, There Is More
What other things must you know? There is a default disc quota that Silverlight apps have and your app can request an increase (IncreaseQuotaTo) from the user, but only from the UI thread. There is a good explanation of that and more here. You may also be thinking what type of data you should be storing in iso storage (e.g. things that the browser caches anyway are not good candidates) and Chris has some opinions here (even if some of his facts are outdated).

In addition to all of the above, Silverlight adds a unique class (no equivalent on the desktop yet) that makes it easy to store application settings in isolated store: System.IO.IsolatedStorage.ApplicationSettings in System.Windows.dll. There are examples of its usage here and here (and I also use it in my basic sample above). If you are the decompiling type, look through reflector at the class's Save method to see how it uses the lower level APIs discussed further above combined with a MemoryStream ;-)

Silverlight 2 Beta 1 Assemblies and Namespaces – Part 1

Mon, April 14, 2008, 01:03 AM under Silverlight
One of the big things about Silverlight 2 is that it is "just .NET", but in the (cross)browser and cross-platform world. "Just .NET" means that we can use the same programming language (e.g. C# 3.0 or VB9), the same tool (i.e. Visual Studio 2008) and we can expect the same services from a runtime (i.e. the CLR). It also means that the libraries available should have some parity (e.g. compatible subset) with the .NET Framework 3.5 libraries that we are already familiar with. So I thought I'd explore the managed assemblies in Silverlight 2 Beta 1 from a high level.

First we browse to %ProgramFiles%\Microsoft Silverlight\2.0.30226.2\ and there is the full list of what is part of the runtime package that is installed on users' machines when they install the plugin (note the size of each assembly that gives an indication of the number of members in there):

In addition to those assemblies above, currently there are some additional ones that you can choose to reference and deploy with your Silverlight application (i.e. in the XAP). You currently get these when you download the Silverlight SDK:

Notable in the list above are the 3 highlighted assemblies that include controls. I would expect that some of the assemblies currently in the SDK folder would become part of the main list further up. Also note the interesting System.Xml.Linq.dll and all the support for dynamic languages.

In future posts, I will write a paragraph for each one of the assemblies comparing them to their desktop counterparts as applicable.

Decompiling Silverlight 2 Apps – Enter the XAP

Sun, March 9, 2008, 10:40 AM under Silverlight
When you build a Silverlight 2 application, you compile your source files (inc. XAML and embedded resources) into assemblies (dlls). Those assemblies (plus any 3rd party ones plus MS assemblies that are not part of Silverlight) are then collected together along with a manifest into a packaged archive – or in other words, a ZIP file. Except, the extension is changed to be a .XAP (pronounced "ZAP"). The benefits of packaging everything into a XAP should be obvious but in case they are not, Pete has discussed that on his blog (inc. screenshots). Note that if your web server is on IIS (prior to version 7) you need to register that MIME type. As an aside, my web server happens to be Apache (shocking I know!) and I had to configure nothing – it just worked.

So, if I had given you a Winforms EXE file you wouldn't ask me for the source code, you would probably just pass it through your favourite decompiler and you've got it all. Same with Silverlight apps: if I point you to my web page that is running a Silverlight app (e.g. the one from this post) all you have to do is:

1. View HTML source, e.g. for this: http://www.danielmoth.com/SL/HtmlBridge/index.html

2. Locate the tag that points to a XAP file and copy the full path, e.g. ClientBin/DemoIntegration.xap

3. Use that path to "Save As" the xap file locally.

4. Rename the XAP file to ZIP and explode it to get the DLLs inside.

5. Party away by tossing the DLL(s) to the decompiler, e.g. Reflector.

Obviously authors of serious SL apps may not condone that behaviour, but feel free to do it with all of mine, for example the DeepZoom/MultiScaleImage that I have now updated to also use mouse wheel.

Silverlight Browser Integration aka HTML Bridge

Sat, March 8, 2008, 11:12 AM under Silverlight
Given that Silverlight applications sit in the browser via a plug in, it would be silly if you couldn't interact from managed SL code with other browser elements, such as html elements and script so that you could, for example, reuse existing assets. I have heard the browser-agnostic integration featured described as HTML Bridge and it is implemented in the System.Windows.Browser.dll assembly in a same named namespace. You can see the types from that namespace on the following image (click on it for the expanded version):

The important inheritance hierarchy to be aware of is that HtmlDocument and HtmlElement inherit from HtmlObject (that allows handling script events via AttachEvent) which inherits from ScriptObject (that allows you to execute scripts via its Invoke and InvokeSelf methods). HtmlPage is a great entry point because you can navigate across its Window property to an HtmlWindow (that allows e.g. to Navigate URLs) and across its Document property to an HtmlDocument (that offers e.g. access to Cookies and QueryString). Also note the 2 Attribute classes: ScriptableType and ScriptableMember. Those are used for exposing Silverlight managed classes to script in the browser combined with HtmlPage.RegisterScriptableObject and RegisterCreateableType methods. Open the expanded class diagram in a separate window and identify the aforementioned methods. Notice there how HtmlDocument allows you to create new elements and retrieve existing ones (CreateElement and GetElementById). Once you have references to those HtmlElements you can do things like SetAttribute, SetStyleAttribute and AppendChild to name a few. Script events are handled in your managed ScriptEventHandler method that accepts an HtmlEventArgs which you can find on the class diagram along with its relationships (e.g. MouseButtons). You should also checkout the HttpUtility class and its self-explanatory methods such as UrlEncode.

Phew! Take a moment to study the two class diagrams using the previous paragraph as a guide and also note that all links above are direct links to the API documentation (i.e. this blog post becomes my bookmark into MSDN ;)). You can also follow a quickstart (DOM access), two walkthroughs (calling managed from script and script from managed), and for those that want even more, follow this 2-hour lab (ZIP).

To see some of the browser integration in action, I have here the ugliest and most basic SL app that simply proves some of the concepts.

Class Diagram item template missing from SL projects

Fri, March 7, 2008, 10:13 AM under Silverlight
It is a well known fact that I love the Class Designer that was introduced in VS2005 and I had fed back a lot during its early stages (good and missing). This is the tool I use to explore any new library/framework that comes out before dropping to the code editor to really play with the API (btw, that answers this FAQ I get when people talk to me about this job).

So I did the same for Silverlight 2 Beta1 and noticed that the option to add a "Class Diagram" was not there! These are all the item templates a Silverlight project will offer:

Some overzealous filtering took place there IMO. I see no reason to omit it since the CD is reflection-based and can hence handle any .NET library. Anywho, all is not lost as you can right click on any code file in Solution Explorer and select "View Class Diagram" from there. Panic (and trivia) over.

MultiScaleImage with mouse support-ish

Thu, March 6, 2008, 07:13 AM under Silverlight
One of the demos that captures people's attention with some Silverlight 2 demos is the Seadragon-based technology that in Silverlight is called "DeepZoom". To see a good example of that in action look at the Hard Rock Memorabilia site or visit the Vertigo site (the guys that built the HR experience). The control behind all that is the MultiScaleImage control. You need to point the Source property of that to the output you get when you use the DeepZoomComposer tool. The tool basically takes an image and chops it up to more download-friendly bits that it distributes to folders.

My colleague MikeT had a play with it all and has a quickstart on his blog. One of the downsides of that approach is that it uses the keyboard for panning around and zooming. I thought I'd take that and try to offer navigation (left/up/right/down) via dragging the mouse and also zooming in by clicking the mouse. To zoom out, I had to keep with using the keyboard (Spacebar was my choice). Assuming that you have the Silverlight 2 runtime installed, the results are here. The source is work in progress but should anyone care about it too much I can share.

It was actually more work than I anticipated. Detecting mouse movement is easy, but making it scroll half-sensibly dependent on how zoomed in or out it is, and also to vary the drag speed dependent on how aggressively the mouse is moved was not as straightforward (to me). My example also doesn't really make as a good sample because I used an image that isn't sufficiently large or deep. To truly experience the beauty of the control, please visit the links at the top.

If you visit the links at the top you will also find that scrolling is much more natural because in addition to mouse clicking for zooming in, the mouse wheel is also used. Mouse wheel events are not directly supported in managed code and require javascript assistance. There is a sample that shows you how to do that on mharsh's blog (but it doesn't include the panning and zooming on click).

So if you aggregate all the sources of information I list above, you can come up with the complete sample ;-).