SAX-like Xml parsing

For those of you who don’t know or can’t remember, SAX (Simple API for XML) is a technology for reading Xml in an event based way. Instead of loading your Xml into a great big DOM and looping thru it or plucking out nodes via XPath or LINQ to XML, SAX allows the Xml parser to notify your application as new nodes were encountered. SAX (like XmlReader, is a forward-only Xml reader) and efficient for parsing large and streaming chunks of Xml.

Reactive extensions fits well with the SAX way of thinking because it is designed to “push” information to it’s consumer instead of making you “pull” information from it. At the same time, Reactive LINQ allows you to select on observable objects in a very natural feeling pull-like language. Therefore, it occurred to me: why not combine XmlReader and Reactive extensions to build a SAX-like Xml reader that you could use via Reactive LINQ!?

An observable XmlReader would allow you to subscribe to it and would iterate over your Xml document for you, notifying you when each node was read. The programmer using this could easily write reactive LINQ expressions to select on specific nodes in the Xml resulting in code that would look and feel much like LINQ to XML but with all the performance benefits of XmlReader.

For example, imagine you wanted to find all the values in nodes of a certain name. You could write something like this…

    1 XmlReader reader = XmlReader.Create(“TreeOfLife.xml”);

    2 IObservable<XmlReader> RxReader = reader.ToObservable();

    3 IObservable<string> NameFinder =

    4     from nodeReader in RxReader

    5     where nodeReader.NodeType == XmlNodeType.Element && nodeReader.Name == “NAME”

    6     select nodeReader.ReadElementContentAsString();

    7 NameFinder.Subscribe((item) => names.Add(item));

I’ll dissect:

  1. Create an XmlReader
  2. Use my newly created extension method to turn that XmlReader into an IObservable.
  3. Construct a new IObservable
  4. Select all the XmlReaders in the IObservable (one for each node)
  5. Filter for node type and element name
  6. Select their string values
  7. Actually initiate the XmlReader to iterate and notify you when a new name is available.

Now let’s look at the code in my extension method. It’s surprisingly simple!

public static IObservable<XmlReader> ToObservable(this XmlReader reader)



    Observable.CreateWithDisposable<XmlReader>(observer =>




            while (reader.Read())




        catch (Exception e)





        return reader;



All I am doing is looping on the XmlReader and passing the XmlReader itself (at it’s current state) to the observer. Violla!

Canceling the operation

Suppose you want to cancel the operation mid subscribe: Because I create the observer via Observable.CreateWithDisposable and return the XmlReader itself as my Disposable object. This allows me to cancel at any time by simply calling:

IDisposable processor = NameFinder.Subscribe((item) => names.Add(item));


More complex selections

Suppose you want to get only the child nodes within a parent node:

IObservable<string> NameFinder =

    from r1 in RxReader

    where r1.NodeType == XmlNodeType.Element && r1.GetAttribute(“ID”) == “76937”

    from r2 in r1.ReadSubtree().ToObservable()

    where r2.NodeType == XmlNodeType.Element && r2.Name == “NAME”

    select r2.ReadElementContentAsString();

I simply combine reactive LINQ statements and create a new reactive XmlReader to iterate a sub node using XmlReader.ReadSubtree().ToObservable().

Here’s a demo of the code above using the tree of life Xml for a Danaus butterfly genus.

Here’s the source code for the project.

In my last post I demonstrated how to use reactive extensions in Silverlight to easily build responsive UIs. In this post I am going to expand on that and demonstrate how to use reactive extensions (Rx) from within a view model by asynchronously loading an RSS feed into your model and populating the UI while the bytes are still coming in. This is about as fast and responsive as it gets and as you will see, by using Rx the code is concise and relatively easy on the eyes.

Note: All of this can be done without reactive extensions. Nothing here is new from the end users point of view. But as programmers, we should always be looking for ways to create more readable code in fewer lines to accomplish tasks even if we already know how to do them in other ways. Rx has the advantage of enabling you to easily write multi-threaded code without creating Thread objects and avoid using local variables or constructing user state objects to maintain state between events. Enough talk, time to make my case with code.

Note: If you want to get directly to the Rx stuff, skip down to the DataClient section.

First, let’s set up the foundation of a demonstration app that reads an RSS feed and displays the results to the user. Regardless of whether you’re going to use Rx or not, you’ll need to create the following:

1. The model. We clearly need a model to hold each RSS item. I’m going to use XmlSerializer to deserialize the objects from Xml, so I’ll add a bunch of XmlSerializer attributes to my class to help map the RSS Xml.


public class RssItem



    public string Title { get; set; }


    public string Link { get; set; }


    public string PublishDate { get; set; }


    public string Description { get; set; }


    public string PlainTextDescription


        get { return StripHtml(Description); }



Note: Because RSS item descriptions often contain HTML, I created a read-only property that strips out the html tags from the description. Thanks to John Papa for providing the StripHtml algorithm in his book.

2. A routine to turn a stream into RSS item objects. There are different ways to accomplish this (such as using LINQ to XML) but we need a method that allows us to read the bytes as they become available. Therefore, I’ll use a combination of XmlSerializer and XmlReader in order to support a stream based approach and avoid waiting for the entire Xml document to be delivered before we can start processing it.

public static IEnumerable<RssItem> GetRssItems(XmlReader reader)


    XmlSerializer rssItemSerializer = new XmlSerializer(typeof(RssItem));

    while (reader.GoToElement(“item”))

        yield return rssItemSerializer.Deserialize(reader) as RssItem;


Note: I’ve created an extension method (.GoToElement) for the XmlReader class in order to make using XmlReader easier. Download the source to see this method.

3. A routine to create and return a WebRequest object.

private static WebRequest GetWebRequest(Uri Uri) {

    var Result = (HttpWebRequest)WebRequest.Create(Uri);

    Result.AllowReadStreamBuffering = false;

    return Result;


Note: I also set AllowReadStreamBuffering to false in order to prevent the response from being buffered, thus allowing us to start using the data as it is being downloaded.

Also Note: I’m using a WebRequest object instead of a WebClient object for 3 reasons: 1) the response callback occurs on a background thread 2) Silverlight only allows us to process unbuffered data on a background thread 3) Rx has an extremely simple way to turn async patterned calls into observable objects (more on this below).

4. The view. We will create our view the exact same way regardless of whether we use Rx or not. This is important because it allows a designer to build the view without caring about how we go about getting our data. This is a typical and simple M-V-VM view that merely binds a property from the view model to a control on the view. The important thing to take away here is that using Rx in this example does not affect our view in any way, shape or form.

    <local:ViewModel />
<ScrollViewer VerticalScrollBarVisibility="Auto"> 
    <ItemsControl ItemsSource="{Binding RssItems}"> 
                    <HyperlinkButton Content="{Binding Title}" FontSize="16" NavigateUri="{Binding Link}" Margin="3" /> 
                    <StackPanel Orientation="Horizontal" Margin="3"> 
                        <TextBlock Text="Posted: " Foreground="Gray" /> 
                        <TextBlock Text="{Binding PublishDate}" Foreground="Gray" /> 
                    <TextBlock Text="{Binding PlainTextDescription}" TextWrapping="Wrap" Margin="3" /> 

The view simply shows our RSS items in a templated ItemsControl and wraps the whole thing in a ScrollViewer.

5. The ViewModel’s public API. The ViewModel needs to provide RssItem objects, so all we need is a property that can be bound to the view:

private ObservableCollection<RssItem> rssItems;

private ObservableCollection<RssItem> rssItems;

public IEnumerable<RssItem> RssItems


    get { return rssItems; }


So far everything above is probably identical to how you would have built the app regardless of whether or not you were going to use Rx! This is all standard stuff but I wanted to list everything involved in order to stress just how much of your code and coding practices do NOT need to change in order to take advantage of Rx. Now we have most of the major pieces of our demonstration app all nice and isolated and ready to be used with or without Rx.

The only things left are the DataClient (the thing that actually goes and gets the RSS Xml and populates your model) and the code in the ViewModel to call that DataClient.

The DataClient: Rx Magic time!

public static IObservable<RssItem> GetRssItems(Uri Uri)



        (from request in Observable.Return(GetWebRequest(Uri))

        from response in Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)()

        from item in Mapper.GetRssItems(XmlReader.Create(response.GetResponseStream())).ToObservable()

        select item).ObserveOnDispatcher();


That’s it! We just need one great big expression to return something that our ViewModel can use. No events, no lambda, no long routines.

The purpose of this function is super simple: to return an IObservable<RssItem> whose job is to “push” fully populated RSS item objects out to the consumer one at a time as soon as they are available. Later I’ll show you how to consume an IObservable object.

The basic mechanics of this function is to combine IObservable objects using a Reactive LINQ expression and return one super IObservable object that performs its duties on .Subscribe and pushes out results one at a time back to the consumer.

Let’s dissect:

First we have:


This calls GetWebRequest (described earlier) to get a standard WebRequest and puts it into an IObservable object that does one simple thing: it “pushs” that single WebRequest object to it’s consumer.

By using Reactive LINQ notation:

from request in Observable.Return(GetWebRequest(Uri))

we can chain together other operations that use that WebRequest to create their own IObservable objects.

This might be tough to get your head around but will become clearer as we keep going.

Next, we take that request and use it in our next expression:

Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)()

This feature of Rx is awesome! Here we call the FromAsyncPattern method and pass in references to 2 methods that already exist on the WebRequest object. FromAsyncPattern wraps this in an IObservable object that does a few things… It calls BeginGetResponse when someone subscribes to it, it handles the async callback, calls EndGetResponse, and finally returns the result via a “push” to the subscriber.

In a nutshell, FromAsyncPattern hides all the plumbing of using the async pattern and wraps it in a nice IObservable object. One thing to note: The call out to the web does NOT get initiated until someone subscribes to the resulting IObservable. This gives the consumer the ability to control the timing.

Quick recap on our giant expression: At this point, we now have  a new IObservable object that works like this…

When someone subscribes to the resulting IObservable, it goes and subscribes to the first IObservable in our Reactive LINQ statement, which immediately “pushes” notification out that tells us that we have a web request. That push notification is handled by the statement in the Reactive LINQ statement which uses that request object to initiate and handle the asynchronous call to the server. When it is done, it “pushes” the response on to the subscriber (the subscriber being the next thing in our big ‘ol Reactive LINQ chain). Which is…


The first thing you may notice is that there’s no Rx in this expression. All it is doing is creating an XmlReader from the response stream and passing it into the function that creates models from an XmlReader. At this point we just have an IEnumerable<RssItem> on which we call…


ToObservable is an extension method that extends IEnumerable and turns it into an IObservable. This allows a consumer to get notified when the next item in the collection is available instead of making us loop through the collection manually. We also need an IObservable because we’re chaining together IObservable expressions. You can’t just switch to IEnumerables in the middle of your LINQ expression. For example. A traditional LINQ expression with IEnumerable might look like:

from purchases in customers

from order in purchases

select order;

but you can’t start with an IObservable and switch to an IEnumerable or vice versa…

Finally, we want to select the item that ultimately will be pushed back to the consumer and wrap our IObservable in a new one that performs all “push” operations on the dispatcher. This is important because WebRequest returns all its data on a background thread and so without it, push notifications will occur on that same thread and throw an exception when we try to modify the UI.

select item).ObserveOnDispatcher();

Note: We could also have built the guts of this procedure using more traditional methods like handling events by creating our own class that implemented the IObservable interface. However, I think it’s better to re-use methods like FromAsyncPattern to do as much of the leg-work for us as possible.

Back to the ViewModel:

public ViewModel()


    rssItems = new ObservableCollection<RssItem>();

    IObservable<RssItem> client = DataClient.GetRssItems(new Uri(http://pheedo.msnbc.msn.com/id/3032091/device/rss/io&#8221;));

    client.Subscribe(item => rssItems.Add(item));


Done! All we had to do is get the IObservable object from the DataClient, subscribe to it and for each item returned, and add that item to the ObservableCollection bound to the view.

And remember, because this is running on a background thread and not buffering the response from the server, we can easily be spitting back model objects and showing them in the UI as more bytes are still being downloaded and processed.

More Rx magic!

OK, so we have an ultra responsive UI that shows data as soon as physically possible and we have a super slim DataClient that leverages Rx to avoid writing our own code to call and handle asynchronous webrequests. But what else can we do with Rx in the context of this app?

A: “a ton! “ but this post is already getting long so I’ll get you going with a couple quick examples and let your imagination take over.

Imagine you wanted to combine two different RSS feeds:

public ViewModel()


    rssItems = new ObservableCollection<RssItem>();

    var TopNewClient = DataClient.GetRssItems(new Uri(http://pheedo.msnbc.msn.com/id/3032091/device/rss/io&#8221;));

    var BusinessNewsClient = DataClient.GetRssItems(new Uri(http://pheedo.msnbc.msn.com/id/3032221/device/rss/&#8221;));

    var client = Observable.Merge(TopNewClient, BusinessNewsClient);

    client.Subscribe(item => rssItems.Add(item));


Or how about you wanted to expose an IsBusy state to the client:

< toolkit:BusyIndicator IsBusy=”{Binding IsBusy}” />

 public ViewModel()


    rssItems = new ObservableCollection<RssItem>();

    IObservable<RssItem> client = DataClient.GetRssItems(new Uri(http://pheedo.msnbc.msn.com/id/3032091/device/rss/io&#8221;));

    client = client.Finally(() => IsBusy = false);

    isBusy = true;

    client.Subscribe(item => rssItems.Add(item));



bool isBusy;

public bool IsBusy


    get { return isBusy; }

    private set


        isBusy = value;

        if (PropertyChanged != null)

            PropertyChanged(this, new PropertyChangedEventArgs(“IsBusy”));



Check out the vast library of Rx extension methods available to use. Getting an IObservable and pumping the results into an ObservableCollection is just the beginning of what you can do with a data client that returns an IObservable. Have fun and start using Rx!

See demo (Note: I threw in a very minor delay during deserialization of each item to exagerate the effect).

Download source

If you haven’t heard of Reactive extensions (Rx) for .NET, it’s time to get familar. Rx is extremely cool and once you understand it, it will change the way you write client-side code forever. Instead of providing an overview of Rx, I’m going to urge readers to check out Pencho Popadiyn’s blog post, where he does a much better job of explaining it that I probably could.

Instead, I’m going to demonstrate one practical use for Rx extensions here in my 2 part blog. Yes, 2 parts! That’s how cool I think Rx is. 🙂 And keep in mind that I’m only scratching the surface on the ways Rx can be used. Enough fanfair, let’s get started by building a super simple Silverlight app that updates a ListBox with and without Rx and you be the judge of which is better.

Let’s work backwards by looking at the end result first and then going over how to create it.

Click here to run

Download source code here

Now, here’s how it works…

Step 1: Download and install Rx for Silverlight (link about one page down on the right hand side).

Step 2: In your Silverlight 3 project, Add a reference to the 3 Rx assemblies: System.CoreEx, System.Observable, & System.Reactive.

Note: The 3 files only add ~70K to your .xap file.

Step 3: Create a function that returns a model. For this example, we’ll just have an IEnumerable<String> as our model and I’ll toss in a delay between each item so we can exagerate the difference between Rx and non-Rx.

public static IEnumerable<string> GetModel()
    for (int i = 0; i < 5; ++i)
        yield return "Item " + i;

Step 4: The standard way to put that model into our ListBox would be to assign it (the IEnumerable) to ListBox.ItemsSource. However, for the sake of an apples to apples comparison, I’ll manually loop thru my model and insert each item into an ObservableCollection that is bound to the ListBox.

//MyList.ItemsSource = GetModel();
var items = new ObservableCollection<string>();
MyList.ItemsSource = items;
foreach (string item in GetModel())

Step 5: Rx magic time! First, I’ll write similar code as in Step 4 but using Rx…

var items = new ObservableCollection<string>();
MyList.ItemsSource = items;
IObservable<string> observable = GetModel().ToObservable();
observable.Subscribe(item => items.Add(item));

Instead of iterating through the IEnumerable, we create an Observable object from our IEnumerable using the .ToObservable extension method. Then, we subscribe to that observer which tells it to iterate over the collection and run our lamba expression for each item. Bottom line: same result.

Step 6: More Rx magic. Let’s use the power of multi-threading and get our model to be created on a background thread, while we add our items to our observable collection (in order to avoid an invalid cross thread exception). We just have to change the last two lines a little bit..

IObservable<string> observable = GetModel()
observable.ObserveOnDispatcher().Subscribe(item => items.Add(item));

Passing in NewThread to .ToObservable() causes the GetModel function to run on a new thread and .ObserveOnDispatcher() causes our Subscription callbacks to run through the dispatcher (therefore allowing us to update the UI). The end result is a UI left totally responsive while the model is manufactured on it’s own thread and each new model item appears as soon as possible in the UI.

This is certainly possible to do by running GetModel() on a new thread and calling Dispatcher.BeginInvoke for each item. Afterall, this is what Rx is doing internally for us, but I personally think the Rx code is much more readable and writeable.

Next to come: Combining M-V-VM, Rx, and unbuffered REST webservices for clean, easy, and hyper responsive applications that need to communicate with the server!

Silverlight provides a variety of brushes that can be used to paint just about any area in your app: from text to shapes to borders. The most common brushes are for painting color and images: SolidColorBrush, LinearGradientBrush, RadialGradiantBrush, and ImageBrush.

However, today I paired the less common VideoBrush with an unusual visual element. Click below to see a demonstration of a fun and novel use of the VideoBrush in Silverlight:

Video Jigsaw Puzzle


Note: PuzzleTouch also now allows you to create your own video puzzles using .wmv or .mp4 files. All work is done 100% on the client! To create your own video puzzle, go to the Online Jigsaw Puzzles by PuzzleTouch homepage, choose “Custom Puzzle”, and have fun!

Here’s a new panel to add to your tool chest. It’s one I expect to use almost daily and save approximately 3.1 hours of typing over the next year. Hopefully you’ll find it useful as useful as I think it is.

What’s wrong with the built-in StackPanel:

You can’t get children to conform to the size of the panel. Imagine you want the following label and list but want the height of the Listbox to stretch or shrink according to the room available:

At first glance, a StackPanel would seem to be the natural choice for which panel to accomplish this. Afterall, you just want a linear list of two objects: a TextBlock and ListBox. However, unless you are willing to hardcode the size of the ListBox or resize it with code, with a StackPanel you’ll end up with:

Yuck! Clipping instead of a scrollbar. So how do you get the desired behavior?

Answer: Grid.

So what’s wrong with a Grid?

  1. Grids take more lines xaml to create. Compare the StackPanel Xaml to the Grid’s above and notice the 4 extra lines of Xaml. Ok, not a huge deal but if you’re doing this every day like me, you start to get sick of creating RowDefinition and ColumnDefinition objects.
  2. With a grid you have to explicitly define the order of the children. Adding the attached property Grid.Row is easy on your first pass but what happens if you want to insert a new row somewhere in the middle. You not only have to add a new RowDefinition, but you also have to remember to go increment the row number on all subsequent siblings. This is a pain and error prone because a sibling would potentially be defined in any order in the grid.

Wouldn’t it be great if you could get the best of both worlds?

What we really want here is a StackPanel that allows you to define the size of the children.

Welcome SuperStackPanel:

Just set the attached property StackPanel.Length to “*” to get a child to stretch.

In fact, SuperStackPanel lets you use all the same GridLength values you can use in a Grid (Auto, *, n*, and x):

Have I sold you yet? The nice part is that SuperStackPanel is completely compatible with a normal StackPanel. Just swap out your StackPanel for SuperStackPanel and everything will look the same because the default value of Length is “Auto”. Frankly, I’d love to see Microsoft expand the role of StackPanel to support this natively. Of course, until then, there’s SuperStackPanel.

SuperStackPanel is lightweight and simple to add to your project, just download the C# source code, add to your project, add the namespace to your xaml and away you’ll go. Enjoy!

I’m always looking for ways to take advantage of Silverlight to accomplish tasks that traditional web technologies can’t. Here’s one that will save you money, increase scalability, and improve your user’s experience

Allowing users to upload images is becoming common place for many websites and applications today. Equally common is the fact that most cameras and phones today produce very large and high quality images. On the other hand, very rarely do you actually want a high resolution / low compression image sitting on your server; nor does the average user know or care enough to manually reduce the size of their image before uploading it to your site.

Therefore, unless you’re lazy or in “get it done” mode, you are probably going to want to shrink the image and even increase the compression on that image before storing it on your server. Doing so will result in faster downloads of that image which means lower bandwidth costs and a better user experience.

The typical (and only option for standard Javascript+HTML based sites) is to do the work on the server. But wouldn’t it be great if you could do this work on the client BEFORE sending it up to your server!? Doing so would 1) decrease the time it takes to upload the image in the first place, 2) decrease the amount of work required by your server; thereby increasing scalability of your site, and 3) decrease the bandwidth used by both you and your user; thereby saving you money.

Silverlight has your answer! Here’s how:

Step 1) Use the OpenFileDialog to acquire the stream that contains the bytes of the image.

OpenFileDialog openDialog = new OpenFileDialog();

openDialog.Filter = “JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg”;

if (openDialog.ShowDialog().GetValueOrDefault(false))


    using (FileStream stream = openDialog.File.OpenRead())


        // now you have the filestream



Step 2) Create a WriteableBitmap from those bytes using a ScaleTransform to shrink the image.

public static WriteableBitmap GetImageSource(Stream stream, double maxWidth, double maxHeight)


    BitmapImage bmp = new BitmapImage();



    Image img = new Image();

    img.Effect = new DropShadowEffect() { ShadowDepth = 0, BlurRadius = 0 };

    img.Source = bmp;


    double scaleX = 1;

    double scaleY = 1;


    if (bmp.PixelHeight > maxHeight)

        scaleY = maxHeight / bmp.PixelHeight;

    if (bmp.PixelWidth > maxWidth)

        scaleX = maxWidth / bmp.PixelWidth;


    // maintain aspect ratio by picking the most severe scale

    double scale = Math.Min(scaleY, scaleX);


    return new WriteableBitmap(img, new ScaleTransform() { ScaleX = scale, ScaleY = scale });


Note: I’m still investigating the need for setting the Effect property on your image control. While this code does not actually affect the user’s image, it is necessary to get this to work. Maybe a bug in Silverlight 3?

Step 3) Encode the WriteableBitmap object back to a Jpeg using FJCore and set your compression quality.

Stream Source = Encode(wb, 20);

public static Stream Encode(WriteableBitmap bitmap, int quality)


    //Convert the Image to pass into FJCore

    int width = bitmap.PixelWidth;

    int height = bitmap.PixelHeight;

    int bands = 3;


    byte[][,] raster = new byte[bands][,];


    for (int i = 0; i < bands; i++)


        raster[i] = new byte[width, height];



    for (int row = 0; row < height; row++)


        for (int column = 0; column < width; column++)


            int pixel = bitmap.Pixels[width * row + column];

            raster[0][column, row] = (byte)(pixel >> 16);

            raster[1][column, row] = (byte)(pixel >> 8);

            raster[2][column, row] = (byte)pixel;




    ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };


    FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);


    //Encode the Image as a JPEG

    MemoryStream stream = new MemoryStream();

    JpegEncoder encoder = new JpegEncoder(img, quality, stream);




    //Move back to the start of the stream


    stream.Seek(0, SeekOrigin.Begin);

    return stream;


Step 4) Send the stream for the new, potentially MUCH smaller Jpeg up to your server!

byte[] buffer;

using (Stream Source = JpgEncoder.Encode(wb, 50))


    int bufferSize = Convert.ToInt32(Source.Length);

    buffer = new byte[bufferSize];

    Source.Read(buffer, 0, bufferSize);



Service1Client service = new Service1Client();


That’s it! Plug this code into your Silverlight app everywhere you upload images and improve your website!

Download the source code here.


Kudos to the folks that made FJCore for sharing all their hard work with those of us that would never consider trying to build it ourselves!

Kudos to nokola for finding a way to build a WriteableBitmap object from an image control without touching the VisualTree.

What is GWT?

In case you haven’t had a chance to explore, Google Web Toolkit (GWT) is a great new tool for building web applications. At its core, GWT allows developers to code in Java and essentially “compile” to Javascript. But it offers much more: GWT also provides a set of common controls (or widgets) to build UIs and even provides a plugin for Eclipse that allows developers to debug both client and server-side code in the same environment that they write their code. Cross browser compatibility is taken care of for you and if you stay within the confines of GWT, for all practical purposes you’ll think you were building a native Java client/server application.

What’s new in GWT 2.0?

Yesterday Google released Google Web Toolkit 2.0. GWT 2.0 provides a number of improvements but the most important one is the ability to define your UI using markup instead of code. You could always create good old fashion html with GWT, but if you wanted to use the native UI widgets, you’d have to do all the creational work in code. With 2.0 you are now able to use a feature called uiBinder to build your own native GWT widgets (the equivalent of UserControls) all in markup. The cool part is, you can mix html with your GWT markup if you want to.

The Good:

GWT helps developers build complex client/server applications with first class tools in a first class language and target any browser without the need for a plugin. The developer doesn’t have to know anything about Javascript, Html, or cross browser quirks and can use accepted design patterns for building complex web applications.

The Bad:

Before my time, assembly programmers must have argued with C programmers that they could never write code in C that would be as efficient as assembly. They must have argued that there would be certain advanced tasks that couldn’t be done easily in C, and that the compiled C would be bloated by comparison and nearly impossible to read if something went wrong and you needed to inspect your code. This is the same argument GWT faces today from the Javascript camp. Ultimately, a javascript app is still being created under the hood and because of it, GWT developers will never have the same level of control and flexibility as if it had built in Javascript from the beginning. All choices have tradeoffs and this is one of GWT’s.

The Ugly:

The product that GWT allows a developer to create will always only be as good as the browser running it and will be held back by the older browsers that it needs to support. In the near term, in order for the GWT feature set to progress, 2 things have to happen: 1) browsers have to natively start supporting new features (can anyone say HTML5?), and 2) certain features in your GWT app won’t support older browsers. While this is a reasonable way to compete with ASP.NET Webforms, jQuery, and Ruby on Rails, this is not a sustainable path to compete with Flash, Silverlight, or Java FX. Hence…

My opinion on GWT’s long term strategy:

Either GWT will ultimately be positioned as a technology suited for catering to lowest common denominator scenarios or…

Google will have to adopt something similar to the plugin approach. GWT developers will still build their app using GWT the way they do today but if they want access to all those extra goodies that Flash, Silverlight and Java FX have (the ones that are not supported in the current version of HTML or Javascript), GWT will need to build those features into Chrome and allow developers to build apps that require some variation of Chrome (Chrome browser, the Chrome OS, or the Chrome Frame plugin). Google may try to bake these feautres into whatever the next version of HTML is at the time but my guess is that they won’t always be willing to wait around for W3C to agree and will start adding them to Chrome as they need them. In the end, GWT apps that need the latest features will essentially be native Chrome apps built on (for all practical purposes) a Java powered plugin framework.

Personally, I say unless you need a plugin independent app, why wait? Silverlight, Flash, and Java FX give you today everything that GWT will provide tomorrow.

UPDATE: The results are in and PuzzleTouch won the grand prize! I had some tough competition so I am extra excited to have won.

The ComponentArt Silverlight Coding Contest results are in for the five finalists and I am super excited to annouce that my creation: PuzzleTouch Online Jigsaw Puzzles made the cut! Thanks to all who voted for me!

If you haven’t see PuzzleTouch yet, check it out. It’s as fun to play as it was to write and is a great testament to what Silverlight is capable of producing.

PuzzleTouch Free Online Jigsaw Puzzles

It’s the only online jigsaw puzzle on the web that supports 360 degree rotation, 100% mathamatically unique shapes, unlimited levels of difficulty, full multi-touch support (my favorite for those that have the hardware!), out of browser mode, the ability to save games, and the ability to run offline (great for planes, trains, and autos).

Silverlight apps are nothing more than big zip files and Amazon S3 is dirt cheap and hyper-scalable. Why would you ever host your Silverlight .xap files on your own server or ISP? … especially with Silverlight Streaming being dropped soon.

Here’s a quick guide to putting your Silverlight apps on Amazon S3 and depending on your app, never worry about scalability or bandwidth costs again…

1) Create your Amazon S3 account.

2) Install S3 Organizer FireFox plugin (this is the equivelent of an FTP client for Amazon S3).

3) Run S3 Organizer, log into your account and create your bucket.

Create a bucket in S3 Organizer via the toolbar

4) Upload your xap file to your bucket. BUT… you must add custom headers unless you are also going to host your .html file there too. Silverlight xaps need a MIME type specified when they are loaded from another domain. The good news is, this is easy with S3 as long as you do it at the time that you upload the file. There is probably a way to set it after the fact but not with S3 Organizer.

Upload your .xap file to Amazon S3 but don't forget to add custom headers

Set the content type for your xap file

Simply set the content type to ‘application/x-silverlight-app’ and send up your xap. Don’t forget to do this EVERY time you upload an update.

5) After uploading your .xap file, set permissions so everyone can read your xap file. Right click on your newly uploaded xap file and choose “Edit ACL…”. Then check Read access for Everyone and Authenticated Users. You do NOT need to do this every time as S3 remembers your ACL settings.

Edit ACL settings in S3 Organizer for your xap file

6) Add the enableHtmlAccess param to your object tag within your html file to enable access to the DOM bridge (assuming your Silverlight app needs access to the DOM bridge).

For example:

Set EnableHtmlAccess param in the object tag

7) Change your html page to load your xap file from S3 directly by setting the source param in your object tag.

For example:

Change the source of your xap file to load from S3

Note: ‘mybucket’ is the name of your bucket on S3.

8 ) Upload your html (or aspx) page to your web server. GoDaddy.com offers cheap hosting for only $5 per month.

That’s it! At this point, the only scalability concerns you should have are those of your web services (assuming you call web services from your Silverlight app).

And with S3, the costs depend on the usage — which will literally cost you just pennies per month until you have some descent traffic. Do the math and you’ll see that it would only cost 17 cents to have a  300K .xap get hit 3500 times. At that rate you’d pay ~$48 to have 1 million new users per month. (I say “new” users because unless you update your xap, users should be caching your xap file and won’t need to re-download it).

Happy cheap hosting and Silverlight coding!

Thanks to all who attended my presentation tonight at the Eugene .NET users group (EADNUG)! There were many great questions I had a fantastic time showing off all the cool things Silverlight can do.

Click here to get all the fun little projects covered (and a few we didn’t have time for).

See you again at the next meeting.