Tag Archives: Silverlight and Beyond (SLaB)

Quickly building a trial mode for a Windows Phone application

Wow – long time no blog!  Over the last few months, I took a bit of a break from blogging, but fear not – I’ve been a busy bee.  Since I last blogged, a lot has changed for me.  In particular, I decided to return to my home state of California.  While I’m still with Microsoft (in the Bay Area), I’m no longer with the Silverlight team.  I’m not done with Silverlight yet, though!  I’ve continued working on various additions to my SLaB library, expanding its scope from utilities for Silverlight on the desktop to Silverlight for Windows Phone.  I did most of this work in the course of building a variety of apps for Windows Phone for fun, curiosity, and utility.  If you’re interested, head over to the Applications section of my website.  There, you’ll see what I’ve been working on: apps for singers, barbershoppers, and everyone else!

Early on, I started porting various tools from SLaB over to Windows Phone, including many of my utility classes and my XamlSerializer.  I also ported the BusyIndicator (formerly the Activity control, now in the desktop toolkit), making use of Jeff Wilcox’s PerformanceProgressBar.  There are a bunch of other goodies in there too, one of which I’ll discuss in this post.

Trials and Tribulations

As I began building my first Windows Phone applications (Pitch Perfect and Tag Master), I decided early on that I wanted to include a free trial that would give people a taste of my apps while showing them “just how sweet life could be” if they were to make the purchase.  Doing a little research on the topic quickly led me to the LicenseInformation.IsTrial() API.  Best practices around this API, however, suggest that it shouldn’t be called too frequently, as “a typical call takes approximately 60 milliseconds or more,” and that the license state should be cached if you plan to call it frequently.  Well, I honestly didn’t know how frequently I would be calling the API, and it didn’t seem like caching a Boolean value would be a costly or difficult task to accomplish, so I went ahead and abstracted it out with a utility class (which you can find in SLaB if you’re interested).

public static class PhoneUtilities
{
    private static bool? _IsTrial;

    public static bool IsTrial
    {
        get
        {
            if (_IsTrial.HasValue)
                return _IsTrial.Value;
            var license = new LicenseInformation();
            _IsTrial = license.IsTrial();
            return _IsTrial.Value;
        }
    }
}

The next problem I encountered was around testing any trial-only code in my application.  There’s not a simple, built-in way to do this using the LicenseInformation API, so I went ahead and added a SimulateTrialMode static property that causes the IsTrial property to return true when it’s set.  Using this API to test your trial mode is pretty straightforward.  I found it most convenient to add a build configuration to my projects which I called “Release Trial” (and also a “Debug Trial” that was modeled after the Debug build configuration) that #defined TRIAL.  This way, by adding the following code to my Application constructor, I could toggle between building the trial and full versions of my applications easily:

public App()
{
#if TRIAL
    PhoneUtilities.SimulateTrialMode = true;
#endif
    // ... boiler-plate initialization code
}

Look, but don’t touch!

With these APIs in place, I felt confident that I could work on producing a good user experience around my trial modes.  The question, however, was what it should look like.  Fundamentally, I wanted to show users what they were missing by not purchasing the app, and give them quick access should they wish to make a purchase decision.  Thus, the concept I chose to develop was to obscure (with a semi-opaque overlay) the part of the UI that is not enabled during a trial and provide a link to the marketplace page for the apps in its place.

As I envisioned it, an app that looked like this when purchased:

ByKeySignaturePitchPipeMode

Might look like this in trial mode:

ByKeySignatureTrialPitchPipeModeTrial

Well, if you read my blog, you know I’m not satisfied if it’s not easy to do this in XAML, so you won’t be surprised to find out that I went about creating a control that I could use precisely for this purpose.  My first instinct was to take the same approach as I originally took with the BusyIndicator control – after all, this is just a control that, based on some condition, displays an overlay and some specialized UI over its content!  Instead of using a property that could be bound to a value, however, this control would simply read IsTrial to determine its behavior.

The result: a TrialBlocker control in which you can wrap your controls for instant trial functionality!

Using the control is just like using the BusyIndicator – it’s a ContentControl, and under normal circumstances (i.e. non-trial mode), it does nothing.  To produce the blocked-out radio button as I did in the images above, your XAML might look like this:

<slabControls:TrialBlocker>
    <RadioButton GroupName="PitchRange"
                 Content="From F to F"
                 IsChecked="{Binding IsFromFToF, Mode=TwoWay}" />
</slabControls:TrialBlocker>

You can also replace the visuals used when the application is in trial mode by setting the TrialContent and TrialContentTemplate properties.  If your TrialContent is text and you use the default TrialContentTemplate, the TrialBlocker will display the text as a hyperlink back to your application’s details in the marketplace.  You can customize the content further (as I did at the bottom of the bottom-right image to produce the “Trial” link that only shows up in Trial mode) by replacing the template or using a UI element as the TrialContent. Within the content or template, a hyperlink with a Uri of “marketplace:///” will automatically link to your app’s marketplace details (using the same INavigate magic I described long ago in this post).

Thus, XAML like this:

<slabControls:TrialBlocker HorizontalAlignment="Center"
                            TrialContentTemplate="{x:Null}">
    <slabControls:TrialBlocker.TrialContent>
        <StackPanel Orientation="Horizontal">
            <HyperlinkButton Content="Trial"
                                Margin="-12,0"
                                FontSize="{StaticResource PhoneFontSizeSmall}"
                                NavigateUri="marketplace:///" />
            <TextBlock Text=" " />
        </StackPanel>
    </slabControls:TrialBlocker.TrialContent>
</slabControls:TrialBlocker>

Can be used to produce a “Trial” link like this:

PitchPipeModeTrial

And that’s it!  It’s a straightforward mechanism, but it does the job of producing the UI I had imagined without too much difficulty.  If you think it would be useful to you, by all means, feel free to use it in your applications, too!

How about the bits?

True to form, I would never leave you without some code – you can grab it on my Downloads and Samples page.  I recently uploaded SLaB v0.11 (yes, that’s zero-point-eleven – got a problem with that? ;)  My releases go to eleven!), which is full of a bunch of goodies for mobile that I’ll try to blog about soon.  As always, I make no promises about quality or support for the libraries – they’re just there as an example/tool for you to use if you’re so inclined!  In the meantime, here’s a summary of what’s new since I last blogged:

  • SLaB v0.11 (includes source and binaries I’ve accumulated by blogging)
    • For the latest version, please check out SLaB on my Downloads and Samples page
    • The v0.10 version of SLaB contained the following changes:
      • Ported various components (e.g. XamlSerializer, etc.) to work on Windows Phone 7
      • Added BusyIndicator for Windows Phone 7
      • Added ContinuousButton for Windows Phone 7, allowing a bound value to be true while the button is being held down by the user
      • Added the DelayCreateContentControl for Windows Phone 7, which delays creation of its content until it has been loaded
      • Added the DelayLoadItemsControl for Windows Phone 7, which fires an event when scrolling nears the end of the vertical space so that more content can be loaded
      • Added the DetailsLayout for Windows Phone 7, which makes creating a 2-column table of headers and content easier
      • Added the MarketplaceNavigator for Windows Phone 7, which makes it easy to create HyperlinkButtons that point to marketplace content
      • Added the TrialBlocker control and PhoneUtilities static methods for Windows Phone 7, which make blocking functionality for trial applications easy and testable
      • Improved progress indication for network downloads
      • Other minor bugfixes
    • The v0.11 version of SLaB contained the following changes:
      • Added the Tombstoner utilty class and a variety of helpers for Windows Phone 7, which make tombstoning of UI state simple and XAML-friendly
      • Added the SequenceGrid panel for Windows Phone 7, which lays out its children in a grid (with a fixed number of columns) in the order they are added
      • Other minor bugfixes

A quick note about barbershop (pun intended :))

In case you were wondering what my “Tag Master” app is all about, I’ll share with you a tidbit from my personal life.  I’m a barbershopper – it’s a style of a cappella singing I grew up hearing my father perform, and fell in love with after attending my first rehearsal with a chorus in the Seattle area when I first joined Microsoft full-time.  If you’ve never heard of it, do a quick search (web and Youtube) for “Barbershop quartet” or “Barbershop chorus” – I think you’ll be pleasantly surprised!  It’s an amazing hobby.  If you’re curious, do yourself a favor and find a local chapter!

To XAML, with love (an experiment with XAML Serialization in Silverlight)

I’m a big fan of XAML.  It provides a nice, declarative, toolable way of defining UI, encourages separation of UI logic and application logic, and is flexible enough to allow an impressive amount of expressiveness.  In addition to being a way to describe a user interface, XAML can be used as a serialization format for arbitrary CLR objects.  A little over a month ago, as I was building out a prototype of an idea I had for a blog post for another time, I found myself looking for a way to quickly and easily serialize some data out into Isolated Storage.  I looked at a few options, such as the XML and JSON serializers in the Silverlight SDK.  Both of these work well for serialization of data, but as I was looking at them, I noticed something that failed to meet my requirements for the task at hand: these libraries are both quite large and would need to be packaged into my XAPs.  System.Xml.Serialization.dll is 314 kb, and System.Runtime.Serialization.Json.dll is 138 kb (uncompressed).  Under many circumstances in large applications, taking such dependencies might be fine, but I was looking for something small that would be acceptable to package into a quick-to-load bootstrapping application.

As a result, I thought I’d spend some time looking for another option.  It occurred to me that in WPF, I might’ve used the XamlWriter for precisely this purpose: to serialize my objects out into text.  As I thought about my options for serialization, taking assembly size into account, I found myself wondering if XAML was a good choice.  After all, Silverlight has a reader (XamlReader) built into the runtime, so I wouldn’t have to build one myself.  Perhaps that would save me the size I was looking for.  Furthermore, in Silverlight 4, the XAML parser got a major overhaul that helped ensure more consistent support of the XAML language, so I felt confident that I could produce a flexible XAML serializer.

With that in mind, I started writing.  At first, I was just hoping to build out some basic serialization into XAML – enough to suit my needs for what I was working on.  But unfortunately, once I start trying to solve a problem, I can’t leave it half-complete!  Just like that, I was hooked on the challenge of seeing how complete of a XAML serializer I could build (which helps explain my blogging absence for the last month :)).

Honestly, I expected to find a large number of issues – limitations of Silverlight that would keep me from collecting enough information to serialize to XAML properly.  The reality, however, was that I could actually get really close to full fidelity.

In the process, I learned a lot about XAML, Silverlight, and myself (a journey of self-discovery, so to speak :)).  In this post, I’ll share my results (happily included for your consumption and experimentation in my latest build of SLaB) as well as some of what I learned.  As usual, I make no promises around support or correctness in all cases.  This is sample code for your edification.  That said, if you do find an issue, please let me know, and I’ll see if I can figure out what’s going on!

POCO, oh, POCO, wherefore art thou?

I started out just trying to serialize POCOs (Plain ol’ CLR Objects).  On the surface, this is pretty straightforward – walk the object graph being serialized, writing objects and property values out using the XmlWriter.  Simple, right?  Well, there’s actually a lot going on here:

  • Walk the object graph using reflection
  • Decide whether properties are serializable (i.e. is the property read-only?  If so, is it a collection type?)
  • Retrieve TypeConverters from both properties and property types (based on the TypeConverterAttribute)
  • Determine whether to set properties as attributes (<Foo Bar=”Baz” />) or elements (<Foo><Foo.Bar><Baz /></Foo.Bar></Foo>)
  • Retrieve and honor ContentPropertyAttributes (So that if “Bar” is the ContentProperty of Foo, the example above is serialized as <Foo><Baz /></Foo>)
  • Determine whether properties should/should not be serialized based on the “ShouldSerializeXXXXX” method and the DefaultValueAttribute
  • Discover attached properties and repeat all of the above
  • Manage xml namespace definitions (e.g. xmlns:foo=”clr-namespace:MyAssembly.Foo;assembly=MyAssembly”) and scope
  • Discover/respect XmlnsDefintion and XmlnsPrefix attributes
  • Understand serialization of built-in types (e.g. Uri, string, double, int, bool, enums etc.)
  • Serialize null values (using “{x:Null}”)
  • Serialize collections
  • Serialize dictionaries (and make use of “x:Key”)
  • Properly escape strings (e.g. “{Hello, world!}” needs to get serialized as “{}{Hello World!}”)
  • Properly handle string whitespace (turning on xml:space=”preserve” at the appropriate times)
  • Avoid cycles in the object graph (I simply ignore the property if it would cause a cycle – sorry, I’m not a miracle worker!)
  • Be performant!

Nothing to it, right?  Phew, I’m tired just writing all those down!  Who knew there was so much to that XAML stuff? (answer: Rob Relyea)

Anyhow, here’s the end result of this labor of love:

POCO Serialization demo

Try changing some of the bound values (against a couple of simple test POCOs I wrote).  You’ll notice that the XAML gets printed without an issue.  XamlReader.Load() works just fine on this text, and could be used to clone objects or otherwise save them.

For posterity, here’s a quick sample of the XAML produced in the sample above:

<util:NestedObject xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                   BoolValue="True"
                   DoubleValue="1.23450005054474"
                   IntValue="12345"
                   StringValue="Hello, world!"
                   UriValue="http://www.davidpoll.com/"
                   util:AttachedProps.AttachedObject="Cool, huh?"
                   xmlns:util="clr-namespace:UtilitiesContent;assembly=UtilitiesContent">
    <util:NestedObject.DictValue>
        <System_mscorlib:String x:Key="Hello"
                                xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">Bonjour</System_mscorlib:String>
        <System_mscorlib:String x:Key="Goodbye"
                                xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">Au Revoir</System_mscorlib:String>
    </util:NestedObject.DictValue>
    <util:NestedObject.ListValue>
        <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">1</System_mscorlib:Int32>
        <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">2</System_mscorlib:Int32>
        <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">3</System_mscorlib:Int32>
        <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">4</System_mscorlib:Int32>
    </util:NestedObject.ListValue>
    <util:NestedObject.OtherObject>
        <util:Person Age="22"
                     FirstName="David"
                     LastName="Poll" />
    </util:NestedObject.OtherObject>
</util:NestedObject>

Nifty, right?  I thought so too.

And here’s the code it took to produce that XAML from my objects:

XamlSerializer xs = new XamlSerializer();
xs.DiscoverAttachedProperties(typeof(AttachedProps));
string text = xs.Serialize(this.nestedObject);

It’s pretty simple: create a XamlSerializer, discover relevant attached properties (you can do this per-property by handing it MethodInfo for the getter/setter, per-type, or per-assembly.  Note: the more of these you have, the more expensive it will be to serialize each object, since the serializer has to test each object for a value from each attached property that could possibly apply to it), and then serialize!

Turning this back into an object is as simple as:

XamlReader.Load(text);

The grand total for the size of this assembly: 36 kb uncompressed.  Bigger than I had originally hoped, but still small enough (16 KB compressed) to work for the scenario I had in mind, I think.  Regardless, it’s a far cry from the two serialization assemblies – both >100 KB uncompressed (which, incidentally, is not to knock them – they are probably much more rigorous than I am in ensuring correctness, performance, and supporting more than what XAML directly supports).

Did you hit any Silverlight roadblocks?

Nope.  For POCO serialization, I didn’t really hit any significant limitations or bugs in Silverlight.  The biggest  potential limiting factor is the lack of internal reflection, but since XAML only supports the public interfaces on objects, this didn’t up being an issue for what I was hoping to do.

UI must make a pact… we must bring salvation back…

Well, I couldn’t stop with just being able to serialize POCOs.  My first instinct after getting the XamlSerializer (basically) working was to try it on a Button and see what happens.  This is useful for serializing out user content (e.g. drawn paths, rich text, etc.), so it’s a nice functionality to have around.  I crossed my fingers, fixed some bugs, and gave it a shot… and failed.  Turns out it’s not so simple.  First of all, the UI stack in Silverlight has a number of controls with complex properties that on any other control would use a custom TypeConverter (and their WPF equivalents do indeed have these TypeConverters).  In Silverlight, however, many of these controls are native to the runtime, and are thus missing public managed TypeConverters that the XamlSerializer could look for when serializing.  Second, there are literally a million (ok, ok, not literally, that would be crazy – but it’s still a lot, alright?!) properties on every Silverlight control, and they probably shouldn’t all be serialized out.  I ought to be looking for DependencyProperties and checking to see if they’re set.  Finally, there are some types that just have to be treated specially: bindings, styles, and templates come to mind immediately.  With this in mind, I set about deriving from my XamlSerializer and creating a “UiXamlSerializer” that augments its functionality and handles these UI nuances.  Here’s what it does:

  • Understand the concept of DependencyProperties (attached and regular), and check to see if their values are set before serializing
  • Discover the built-in attached properties (e.g. Grid.Row and Grid.Column, which should “just work” with this serializer).
  • Handle TypeConversion for properties/types that have native TypeConverters
    • A few in particular are a bit sticky: TargetType on ControlTemplate and Style both need awareness of xml namespaces, as do Style Setters (for setting attached properties and finding the names of the DependencyProperties they target)
  • Reconstitute templates: ControlTemplate, DataTemplate, and ItemsPanelTemplate
  • Opportunistically detect references to items in Resources, and reference them using the “{StaticResource}” markup extension
  • Reconstitute bindings (use ReadLocalValue() on a DependencyProperty to get the BindingExpression, then serialize the binding instead of the value) – this is a behavior you can disable if you don’t want it
  • Recognize content inside of Blocks (i.e. rich text), and avoid rich XML formatting (this is mixed content – elements and direct content – and mustn’t have extra line-breaks or spaces in the XML when serialized)
  • Avoid a few built-in pitfalls (for example, some controls have properties where one or the other should be serialized, e.g. ListBox.SelectedItem, ListBox.SelectedItems, and ListBox.SelectedIndex)

Again, this is a fair amount of work, and it definitely goes a little farther than XamlWriter in WPF did (e.g. trying to serialize Bindings and StaticResources), but I wanted to see how close to full-fidelity I could get here.  Really, the only big item I couldn’t find a way to serialize were TemplateBindings.  Unfortunately, while you can get a TemplateBindingExpression from a property that’s been TemplateBound, I could find no way to get back to the name of the property to which it’s actually bound.  However, “{Binding RelativeSource={RelativeSource TemplatedParent}}” serializes just fine :).

The result of all of this is something that comes pretty close to doing what you want, serializing custom SDK, Toolkit, and custom controls just as happily as it serializes built-in controls.  Take a look at a simple demo:

UI Xaml Serialization Demo

Try selecting different items in the TreeView or ListBox, checking/unchecking the box, etc., and note how the serialized XAML keeps up with the changes you’ve made to the UI through your interactions.

The XAML used to produce the UI on the left-hand side of the screen is as follows:

<Grid x:Name="gridToSerialize"
        Grid.Column="0">
    <sdk:TreeView x:Name="treeView1"
                    Margin="4">
        <sdk:TreeViewItem Header="Level 0 - Item 0 (TreeView items)"
                            IsExpanded="True">
            <sdk:TreeViewItem Header="Level 1 - Item 0"
                                IsExpanded="True">
                <sdk:TreeViewItem Header="Level 2 - Item 0"></sdk:TreeViewItem>
                <sdk:TreeViewItem Header="Level 2 - Item 1"></sdk:TreeViewItem>
                <sdk:TreeViewItem Header="Level 2 - Item 2"></sdk:TreeViewItem>
            </sdk:TreeViewItem>
            <sdk:TreeViewItem Header="Level 1 - Item 1"></sdk:TreeViewItem>
            <sdk:TreeViewItem Header="Level 1 - Item 2"></sdk:TreeViewItem>
        </sdk:TreeViewItem>
        <sdk:TreeViewItem Header="Level 0 - Item 1 (Basic Controls)"
                            IsExpanded="True">
            <Button MinWidth="75"
                    MinHeight="23">Click!</Button>
            <CheckBox IsChecked="True">Check this out!</CheckBox>
            <ComboBox SelectedIndex="0">
                <ComboBoxItem>Combo box item 0</ComboBoxItem>
                <ComboBoxItem>Combo box item 1</ComboBoxItem>
                <ComboBoxItem>Combo box item 2</ComboBoxItem>
                <ComboBoxItem>Combo box item 3</ComboBoxItem>
            </ComboBox>
            <ProgressBar IsIndeterminate="True"
                            MinWidth="100"
                            MinHeight="23" />
            <sdk:DatePicker Height="23"
                            HorizontalAlignment="Left"
                            x:Name="datePicker1"
                            SelectedDate="7/23/2010"
                            Width="120" />
        </sdk:TreeViewItem>
        <sdk:TreeViewItem Header="Level 0 - Item 2 (Layout, Binding, Templates, &amp; Attached Properties)"
                            IsExpanded="True">
            <Grid xmlns:sys="clr-namespace:System;assembly=mscorlib">
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <ListBox Grid.Row="0">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding StringFormat='Value = {0}'}" />
                                <Slider MinWidth="100"
                                        IsEnabled="False"
                                        Value="{Binding}"
                                        Maximum="50"
                                        Minimum="0" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel />
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <sys:Int32>10</sys:Int32>
                    <sys:Int32>20</sys:Int32>
                    <sys:Int32>30</sys:Int32>
                    <sys:Int32>40</sys:Int32>
                    <sys:Int32>50</sys:Int32>
                </ListBox>
                <toolkit:BusyIndicator Grid.Row="1"
                                        IsBusy="True" />
            </Grid>
        </sdk:TreeViewItem>
        <sdk:TreeViewItem Header="Level 0 - Item 3"></sdk:TreeViewItem>
    </sdk:TreeView>
</Grid>

Serializing this out using the UiXamlSerializer produces the following XAML:

<Grid xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="gridToSerialize"
        Grid.Column="0">
    <sdk:TreeView x:Name="treeView1"
                    Margin="4,4,4,4"
                    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
        <sdk:TreeViewItem Header="Level 0 - Item 0 (TreeView items)"
                            IsExpanded="True">
            <sdk:TreeViewItem Header="Level 1 - Item 0"
                                IsExpanded="True">
                <sdk:TreeViewItem Header="Level 2 - Item 0" />
                <sdk:TreeViewItem Header="Level 2 - Item 1" />
                <sdk:TreeViewItem Header="Level 2 - Item 2" />
            </sdk:TreeViewItem>
            <sdk:TreeViewItem Header="Level 1 - Item 1" />
            <sdk:TreeViewItem Header="Level 1 - Item 2" />
        </sdk:TreeViewItem>
        <sdk:TreeViewItem Header="Level 0 - Item 1 (Basic Controls)"
                            IsExpanded="True">
            <Button Content="Click!"
                    MinHeight="23"
                    MinWidth="75" />
            <CheckBox Content="Check this out!">
                <CheckBox.IsChecked>
                    <System_mscorlib:Boolean xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">True</System_mscorlib:Boolean>
                </CheckBox.IsChecked>
            </CheckBox>
            <ComboBox IsDropDownOpen="False"
                        SelectedIndex="0">
                <ComboBoxItem Content="Combo box item 0"
                                IsSelected="True" />
                <ComboBoxItem Content="Combo box item 1" />
                <ComboBoxItem Content="Combo box item 2" />
                <ComboBoxItem Content="Combo box item 3" />
            </ComboBox>
            <ProgressBar IsIndeterminate="True"
                            MinHeight="23"
                            MinWidth="100" />
            <sdk:DatePicker x:Name="datePicker1"
                            DisplayDate="7/25/2010"
                            FirstDayOfWeek="Sunday"
                            Height="23"
                            HorizontalAlignment="Left"
                            SelectedDate="7/23/2010"
                            Text="7/23/2010"
                            Width="120" />
        </sdk:TreeViewItem>
        <sdk:TreeViewItem Header="Level 0 - Item 2 (Layout, Binding, Templates, &amp; Attached Properties)"
                            IsExpanded="True">
            <Grid>
                <ListBox Grid.Row="0">
                    <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">10</System_mscorlib:Int32>
                    <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">20</System_mscorlib:Int32>
                    <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">30</System_mscorlib:Int32>
                    <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">40</System_mscorlib:Int32>
                    <System_mscorlib:Int32 xmlns:System_mscorlib="clr-namespace:System;assembly=mscorlib">50</System_mscorlib:Int32>
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel CanHorizontallyScroll="False"
                                                    CanVerticallyScroll="False"
                                                    ScrollOwner="{x:Null}" />
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock FontSource="{x:Null}">
                                    <TextBlock.Text>
                                        <Binding Path=""
                                                 StringFormat="Value = {0}" />
                                    </TextBlock.Text>
                                </TextBlock>
                                <Slider IsEnabled="False"
                                        Maximum="50"
                                        Minimum="0"
                                        MinWidth="100">
                                    <Slider.Value>
                                        <Binding Path="" />
                                    </Slider.Value>
                                </Slider>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
                <toolkit:BusyIndicator IsBusy="True"
                                        Grid.Row="1"
                                        xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit" />
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
            </Grid>
        </sdk:TreeViewItem>
        <sdk:TreeViewItem Header="Level 0 - Item 3" />
    </sdk:TreeView>
</Grid>

There are a few things to notice here:

  • The DataTemplate for ListBox.ItemTemplate was serialized out and includes bindings for each of the items
  • Bindings are not serialized using the curly brace syntax (e.g. “{Binding Foo}”).  This is because they may (rarely) have properties attached to them, which requires that they be in object-element form
  • CheckBox.IsChecked got serialized the “long way” (object-element syntax).  Why?  Well, CheckBox.IsChecked isn’t of type bool, it’s a Nullable<bool>.  Because of this, it’s not a built-in type, and I serialize it out just like any other object (since I can’t determine the TypeConverter for it on a property level).  There is a built-in NullableBoolConverter TypeConverter, but it doesn’t support ConvertTo (to turn the bool back into a string) and wasn’t necessary to make this scenario work, so I decided to avoid bloating my code with a special case for this.
  • Path geometries do serialize using the UiXamlSerializer.  In Silverlight 4, we made the PathGeometry’s ToString() return the path mini-language, so making this work was actually fairly straightforward.

Once again, doing this serialization is quite straightforward.  Here’s the code:

UiXamlSerializer uxs = new UiXamlSerializer();
string text = uxs.Serialize(this.gridToSerialize);

Cool, right?

In order to keep the POCO XAML serialization assembly small, I chose to put this serializer in its own assembly, deriving from XamlSerializer and overriding a large set of virtuals in order to add understanding of these concepts to the serializer.  Getting UI XAML serialization adds a 26 kb assembly (uncompressed) on top of the 36 kb assembly for the base type.

Lucy in the sky…

Ok, so having a UiXamlSerializer is pretty cool, but what can it do?  Well, the first scenario that comes to mind for me is the serialization of rich text.  Silverlight 4 added the RichTextBox as a core control.  This control is great – it allows editing of rich text with a large variety of inline content, formatting, etc.  It also allows you to insert InlineUIContainers that support arbitrary content.  This is the only way to get images into your rich text.  RichTextBox does have a “Xaml” property, but this property is strictly limited to serializing out Paragraphs, Runs, LineBreaks, Spans, Bolds, Hyperlinks, Underlines, and Italics.  As a result, using this to serialize your rich text loses any images your users might have added to their rich text.  In order to save this data, you had to serialize this manually from the RichTextBox.Blocks property.

With the UiXamlSerializer, doing this is much simpler.  I’ve got a quick demo of this that gets a little “trippy”.  It’s a RichTextBox in which you can format text, add images, and even add other RichTextBoxes (visual recursion?  scary thought :)).  Clicking the button on the page will serialize the content out into XAML using the UiXamlSerializer, read it using XamlReader.Load(), then copy those freshly-cloned elements into the RichTextEditor on the right side of the screen.  Give it a shot!

Rich Text Serialization Demo

The code to do this is slightly more complex, simply because the RichTextBox.Blocks property can’t be serialized directly (its type has no public constructor).  Instead, I copy the elements to my own collection type that is XAML-friendly (remember, generic types aren’t supported in XAML in Silverlight), then copy them back after deserializing.  Otherwise, it’s pretty straightforward:

UiXamlSerializer uxs = new UiXamlSerializer();
ObservableObjectCollection ooc = new ObservableObjectCollection();
foreach (Block b in rteLeft.RichTextBox.Blocks)
    ooc.Add(b);
string xaml = uxs.Serialize(ooc);
this.xamlTb.Text = xaml;
ObservableObjectCollection bc = (ObservableObjectCollection)XamlReader.Load(xaml);
rteRight.RichTextBox.Blocks.Clear();
foreach (Block b in bc)
    rteRight.RichTextBox.Blocks.Add(b);

Et voila!  Simple RichTextBox content serialization!

Any Silverlight roadblocks this time?

Actually, there were only a few (fewer than I expected) painful things to overcome in Silverlight to make UI XAML serialization work:

  • Templates… Unfortunately, the only way to get the Template content in Silverlight is to expand the templates out.  As a result, I have to handle each type of template specially.  DataTemplates are easy: LoadContent() and then serialize the content into the DataTemplate element.  ControlTemplates are reasonably simple as well: create an instance of the control, apply the template, and serialize the visual child of the control.  ItemsPanelTemplates are a little more difficult: create an ItemsControl, apply the template, put the ItemsControl in a popup to force its template to expand, search its visual children for the ItemsPresenter, and serialize the ItemsPresenter’s visual child.  Confusing, but doable.  Unfortunately, all of these require actually expanding the template, creating all of objects in its visual tree.  It’s not ideal, but it works.
  • TypeConverters… I hope I got all of these, but I’m sure there are some that I’ve missed.  I think the primary scenarios all work, though.  Let me know if you encounter an issue and I’ll see if there’s anything I can do to fix it.
  • ShouldSerialize… In WPF, there are a number of ShouldSerializeProperty methods hidden from intellisense and the object browser.  These tell the XamlWriter whether a particular property should be serialized (e.g. should I serialize SelectedItem, SelectedItems, or SelectedIndex on a ListBox?)  I’ve tried to hit the worst offenders here, but again, I’m sure I’ve missed some.

The following issues were insurmountable, but I made a best effort:

  • TemplateBindings… they just can’t be reconstituted once they’ve been created.  There’s no way to get the property that is the Source of the TemplateBinding back after it’s been created.
  • DependencyProperties… Since you can’t get their names, I have to rely on the reflected field name of the DependencyProperty.  I make the (usually safe) assumption that this field will be public, static, and named <PropertyName>Property in both the regular and attached property cases.  If I don’t find these fields, I treat the property as a CLR property rather than a DependencyProperty.
  • Bindings…  Everything’s good when trying to rebuild these except that the PropertyPath doesn’t expose enough information to safely rebuild the Binding’s path.  In particular, if the Binding has an attached property within its path, it uses the “(ns:Foo.Bar)” syntax.  Since I don’t know what “ns:” means after the binding was originally parsed, I can’t be 100% sure what the attached property really is.  In this case, the UiXamlSerializer searches its known attached properties for a class named “Foo” with an attached property called “Bar”.  If it finds multiple attached properties that match this, the result is indeterminate.  In other words, please don’t create a class called “Grid” with an attached property called “Row” and bind to that property – you’re asking for trouble.  If you call it “MyGrid”, though, you’re golden :)
  • Weirdness… I can probably work around these, but now and then you’ll encounter some little quirks or bugs in Silverlight’s XAML parsing.  It’s much less unpredictable in Silverlight 4 than Silverlight 3, but there are still one or two issues.  For example, if you explicitly set a control’s Cursor property to null in code, all is well.  Unfortunately, doing the same explicitly in XAML throws.  Luckily, it’s rare to set this property’s value to null in code, since its default value is null anyway (and if the DependencyProperty remains unset, the serializer won’t write it out, and everybody’s happy).  I haven’t special-cased this for now, but you get the picture :).

Zippity Doo Dah…

One place where I learned a lot from this experience was in dealing with performance in Silverlight.  It can be a sticky area, and I definitely had my fair share of performance problems when I made my first pass on implementing this.

Honestly, I had never actually profiled a Silverlight application before trying this.  It had rarely been an issue for me with the things I was writing.  But then I wrote the UiXamlSerializer, and when I tried to Serialize about 60 lines of XAML it took about 1.2 seconds.  Simple profiling revealed a poor coding choice I had made that increased the complexity of my serialization by a factor of O(n^2) – oops!  Now, serializing the same content (after warming up the serializer, which now does some aggressive caching) takes about 120 milliseconds – just a little longer than WPF’s XamlWriter takes for the same content: 80 milliseconds (also after warmup).  That said, my “warmup” takes about 1/3 of the time of XamlWriter’s (I suspect I’m doing less – I think XamlWriter actually searches all loaded assemblies for attached properties – I do it explicitly for desired attached properties).  Not too shabby, right?  With more effort, I could probably improve on that some more, but I was pretty happy with the improvement :).

The best resource I found for learning to profile a Silverlight application was Maxim Goldin’s blog.  He lays it out quite clearly.  Thanks, Maxim!

Here are some of the big things I learned from profiling and implementing performance improvements:

  • Reflection is expensive.  I knew this going in, but I didn’t realize how much of an impact it would have.  I cut my run-times nearly in half just by caching any attributes, PropertyInfos, and MethodInfos I happened to find along the way.  It’s a fairly easy step to take for a big win.  GetCustomAttributes() was the biggest offender for me.  These can’t change at runtime anyway, so they’re safe to cache.  I just kept dictionaries associating them with Types, PropertyInfos, and MethodInfos whenever I could.
  • LCG (Lightweight Code Generation) is awesome.  I managed to shave off a good 30-40% of my time by turning PropertyInfo.GetValue() and MethodInfo.Invoke() calls into pure IL which I could invoke directly.  Granted, this project is very heavy on reflection, so I probably got more of a benefit here than most apps would, but I was really surprised by just how much of a difference it makes.  It’s important to cache the generated IL here, since the initial generation is actually more costly than reflection, but if you’re repeatedly checking the same property’s value over and over on different objects (e.g. “Background” on any control), this makes a big difference in aggregate.  Furthermore, subsequent serializations (e.g. calling Serialize() 50 times on 50 different objects of the same type) are significantly faster.
  • LINQ expressions make LCG easy!  Wow — I was stunned by just how simple it was to do my lightweight code generation.  Here’s an example of the code it took to generate a delegate (Func<object, object> in this case) for an attached property getter (this.Getter is the MethodInfo for the attached property, and this.GetterFunc is the cached generated delegate):
var param = Expression.Parameter(typeof(object));
var cast = Expression.Convert(param, this.TargetType);
var call = Expression.Call(null, this.Getter, cast);
var finalCast = Expression.Convert(call, typeof(object));
var lambda = Expression.Lambda<Func<object, object>>(finalCast, param);
this.GetterFunc = lambda.Compile();
  • Cache often.  It probably goes without saying, but assuming you’ve already got algorithmic complexity down, look for places to cache things rather than performing new calculations.  Something to watch out for: expensive lookups.  I found that my aggressive caching in Dictionaries led to a new potential performance issue – the Dictionary lookups.  A few times, I needed to go through and optimize the Equals() and GetHashCode() implementations for my dictionary keys.  For Types, this was no problem for me, but PropertyInfos are more complex (they don’t have an Equals() implementation, so I had to write one myself).
  • Caching has an impact on assembly size.  The IL metadata from additional fields and code for caching added at least 4-5 KB to my assemblies.  It had a significant impact on performance, though.  It’s a trade-off one must consider when making these types of improvements.  In my case, the gains were so great that it was really a no-brainer.  As I was looking at smaller optimizations, however, I began to consider this issue carefully.
  • Watch out for Exceptions.  First chance exceptions make this serializer run fairly slowly when the debugger is attached, and they’re happening constantly because some attached properties target any DependencyObject, but throw for all but a few types.  As a result, almost every UIElement being serialized hits a first chance exception.  I spent some time clearing them out of my own code, and it definitely improved performance both with and without the debugger attached.  It’s an unavoidable issue sometimes (in this case because I’m running someone else’s code blindly for property getters), but minimize using exceptions for control flow whenever possible.
  • Finally, LINQ to Objects is really cool and makes for some very clean code.  Watch out for its performance pitfalls, though.  One example: once you create a query, iterating over the resulting IEnumerable re-runs the query each time.  If you’re doing any more complex calls within those queries (e.g. selecting the value of a property via reflection, performing string comparisons, or determining if the property can be written to XAML), watch out for this.  “let” and ToArray() are your friends in this case.

I heard it through the grapevine…

Before I conclude this post, I just want to take a moment to acknowledge some folks who tried this long before I ever got my hands on it.  Having a XamlWriter equivalent in Silverlight is a request I’ve seen over and over, and others have tried it before me.  My hope was to overcome some of their drawbacks and really have something general-purpose.  I think, for the most part, I’ve accomplished that.  Regardless, check out these – they may do the trick even better than I do!

All of these folks have done great work and deserve recognition for it.  I may have missed some – these were just from a preliminary search.

I got plenty o’ plenty…

You know I would never leave you without code and links to the live sample!  Last night, I updated SLaB to v0.9 (uh oh, I’m running out of numbers, but I’m not sure I want to have a “v1.0”… any suggestions?) and updated the live sample to include XamlSerializer demos.

I’ve also updated my SLaB sample to be installable!  Yup, it uses Transparent Platform Extensions and can run out of browser.  How?  That’s my RemoteControl (which uses my XapLoader) at work.  I’ll eventually blog about it specifically, but there’s more work I’d like to do there :).

With that said, here’s a summary of the links and access to the source!

  • Live Sample (source — found in the SLaB v0.9 source under “UtilitiesContent”)
  • SLaB v0.9 (includes source, a sample app, some tests, and binaries)
    • For the latest version, please check out SLaB on my Downloads and Samples page.
    • The v0.9 download of SLaB includes the following changes:
      • Added XamlSerializer and UiXamlSerializer for producing Xaml from POCOs or UI/DependencyObjects
      • Updated MEFContentLoader to include Glenn Block’s changes from his talk, supporting MEF’s Xap loading (sorry for the long delay on this – didn’t realize those changes had been made until someone brought it up to me!)
      • Fixed a bug with PackUriParser that caused navigations between pages within the same assembly (using full pack Uris) not to update the browser’s address bar as users moved from page to page.
      • Other minor bugfixes

As always, I love hearing what you have to say.  This is something I primarily do in my “copious” amounts of free time (yes, the quotes indicate my sarcasm) because I really enjoy working on/with Silverlight and seeing how far I can push it/myself.  I also like keeping my developer side alive and well by spending some quality time coding (have to break that Program Manager stereotype :)).  I’m always surprised by how 6 PM suddenly turns into 4 AM when I’m working on something like this.  Anyhow, if there’s something you’d like to see or have a question about, speak up!  I’ll try to get back to you when I can, but I reserve the right to work on things I’m intrigued by! ;)

Common Navigation UI and Authorization-driven Sitemaps

Navigation-driven Silverlight applications tend to share some common pieces of UI.  Traditionally, this has required sprinkling HyperlinkButtons throughout the application’s XAML.  For ASP.NET a number of controls intended to drive navigation exist.  These controls are driven by a sitemap, integrate well with authorization and roles (through sitemap trimming), and provide common user experiences around hierarchical application structures such as a TreeView-based list of hyperlinks and Breadcrumbs or navigation paths.  These controls provide the user with context as to where in the application/site they currently are as well as where within the application they can go.

In this post, I’ll introduce a few controls that attempt to mimic this behavior in a Navigation-driven Silverlight application.  I have added these controls to SLaB, and you’re welcome to use and modify them – or use them as examples for your own development – as you see fit.  The controls are:

  • TreeViewNavigator – a control which represents a sitemap as a TreeView

A TreeView Sitemap.

  • BreadCrumbNavigator – a control which represents your current location within the sitemap’s link hierarchy and allows navigation back up the hierarchy as well as to siblings of any node within the hierarchy

A BreadCrumb sitemap.

If you’ve been following the evolution of my sample projects, you may have noticed some navigation UI that’s not built into the default navigation application template and has controls that look like the ones I’ve described above.  Surprise, surprise! :)  You can see this in action here.

How does this type of UI work?

At its core, these controls have the same common set of functionality:

  • Rendering UI based on a sitemap
  • Keeping UI synchronized with the current page within the application
  • Trimming the sitemap based upon the roles the current user belongs to and the metadata in the sitemap

The goal of these controls is to allow the navigation structure of an application to be exposed to a user in a declarative fashion, much as one can do using ASP.NET sitemaps.  The API for the controls above uses Sitemaps that can be specified in XAML, but follow the same general structure as in ASP.NET.

For example, the sitemaps displayed above are produced by the following XAML:

    <SLaB:Sitemap x:Key="Sitemap"
                  Title="DavidPoll.com"
                  Description="My homepage.  Check it out and see what it's all about!">
        <SLaB:SitemapNode TargetName="ContentFrame"
                          Title="Home"
                          Description="The home page."
                          Uri="/Views/Home.xaml" />
        <SLaB:SitemapNode Title="SLaB Features"
                          Description="Demonstrations of Silverlight and Beyond features.">
            <SLaB:SitemapNode Title="Navigation">
                <SLaB:SitemapNode Title="Local Pages">
                    <SLaB:SitemapNode TargetName="ContentFrame"
                                      Title="About"
                                      Description="The about page."
                                      Roles="Foo"
                                      Uri="/Views/About.xaml" />
                    <SLaB:SitemapNode TargetName="ContentFrame"
                                      Title="A broken link"
                                      Uri="/Views/NonExistent.xaml" />
                </SLaB:SitemapNode>
                <SLaB:SitemapNode Title="On-Demand Xaps"
                                  Description="Pages in Xaps that will be loaded on-demand."
                                  TargetName="ContentFrame"
                                  Uri="/Views/SitemapPage.xaml?sitemapname=OnDemandSitemap">
                    <SLaB:SitemapNode Title="This Domain">
                        <SLaB:SitemapNode TargetName="ContentFrame"
                                          Title="Page in a big xap"
                                          Uri="pack://siteoforigin:,,SecondaryXap.xap/SecondaryXap;component/Page1.xaml" />
                        <SLaB:SitemapNode TargetName="ContentFrame"
                                          Title="Awesome Page"
                                          Uri="pack://siteoforigin:,,TernaryXap.xap/TernaryXap;component/AwesomePage.xaml" />
                        <SLaB:SitemapNode TargetName="ContentFrame"
                                          Title="Penguins (mapped Uri + metadata)"
                                          Uri="/remote/TernaryXap/AwesomePage.xaml?Site=http://www.davidpoll.com&amp;First Name=David&amp;Last Name=Poll&amp;Title=Penguins!&amp;Please rate..." />
                    </SLaB:SitemapNode>
                    <SLaB:SitemapNode Title="Cross-Domain">
                        <SLaB:SitemapNode TargetName="ContentFrame"
                                          Title="http://open.depoll.com Page"
                                          Uri="pack://http:,,open.depoll.com,SimpleApplication,SimpleApplication.xap/SimpleApplication;component/Depoll.xaml?Source=http://open.depoll.com&amp;File=wildlife.wmv" />
                    </SLaB:SitemapNode>
                </SLaB:SitemapNode>
                <SLaB:SitemapNode Title="Printing"
                                  Description="Pages that demonstrate printing utilities that simplify pagination of data and printing of complex data sets."
                                  TargetName="ContentFrame"
                                  Uri="/Views/SitemapPage.xaml?sitemapname=PrintingSitemap">
                    <SLaB:SitemapNode Title="Collection Printing (DataGrid)"
                                      Uri="pack://siteoforigin:,,ScratchPrintingProject.xap/ScratchPrintingProject;component/PrintingPage.xaml"
                                      TargetName="ContentFrame" />
                    <SLaB:SitemapNode Title="Collection Printing (Template-based)"
                                      Uri="pack://siteoforigin:,,ScratchPrintingProject.xap/ScratchPrintingProject;component/ItemTemplatePrinting.xaml"
                                      TargetName="ContentFrame" />
                    <SLaB:SitemapNode Title="Pre-defined page printing (Template-based)"
                                      Uri="pack://siteoforigin:,,ScratchPrintingProject.xap/ScratchPrintingProject;component/PredefinedPages.xaml"
                                      TargetName="ContentFrame" />
                </SLaB:SitemapNode>
                <SLaB:SitemapNode Title="Useful XAML Tools">
                    <SLaB:SitemapNode TargetName="ContentFrame"
                                      Title="Demo (simple QueryString)"
                                      Uri="/Views/ObservableDictionaryDemo.xaml?a=b&amp;c=d&amp;e=f&amp;g=h" />
                    <SLaB:SitemapNode TargetName="ContentFrame"
                                      Title="Demo (more complex QueryString)"
                                      Uri="/Views/ObservableDictionaryDemo.xaml?a=b&amp;Name=David Eitan Poll&amp;Url=http://www.davidpoll.com&amp;No Value&amp;Order=Dictionary" />
                </SLaB:SitemapNode>
            </SLaB:SitemapNode>
            <SLaB:SitemapNode Title="DavidPoll.com">
                <SLaB:SitemapNode TargetName="_blank"
                                  Title="Home Page"
                                  Uri="http://www.davidpoll.com" />
                <SLaB:SitemapNode TargetName="_blank"
                                  Title="Navigation Posts"
                                  Uri="http://www.davidpoll.com/tag/navigation/" />
                <SLaB:SitemapNode TargetName="_blank"
                                  Title="SLaB Posts"
                                  Uri="http://www.davidpoll.com/tag/silverlight-and-beyond-slab/" />
                <SLaB:SitemapNode TargetName="_blank"
                                  Title="SLaB Download Page"
                                  Uri="http://www.davidpoll.com/downloads-and-samples/#SLaB" />
            </SLaB:SitemapNode>
        </SLaB:SitemapNode>
    </SLaB:Sitemap>

You’ll note that the “About” link in the Sitemap above (bold/italic above) is missing from the TreeView.  This is because the sitemaps do principal-based trimming of the sitemaps, ensuring that users only see the links they’re authorized to see. 

In addition, the controls above stay in sync with the current page the user is viewing.

To get all of this functionality, there are three primary properties to set on the navigation controls (which derive from the Navigator abstract base class for this common functionality):

  • Sitemap – usually, this is set to a Sitemap that is defined in resources somewhere, and may be shared across multiple navigation controls.
  • CurrentSource – if the navigation control needs to stay in sync with the user’s current location (which is not always the case – e.g. on Error/404-ish pages), bind it to the CurrentSource of the Frame that it will be navigating
  • Principal – if the navigation control should trim the sitemap based upon the User’s authorization, bind the Principal to be that of the current user.  In the case of RIA Services, this can be done through the WebContext

Ultimately, using these controls just requires some simple XAML.  For the TreeViewNavigator:

<SLaB:TreeViewNavigator CurrentSource="{Binding ElementName=ContentFrame, Path=CurrentSource}"
                        Principal="{Binding User, Source={StaticResource WebContext}}"
                        Sitemap="{StaticResource Sitemap}" />

And for the BreadCrumbNavigator:

<SLaB:BreadCrumbNavigator CurrentSource="{Binding CurrentSource, ElementName=ContentFrame}"
                          Principal="{Binding User, Source={StaticResource WebContext}}"
                          Sitemap="{StaticResource Sitemap}" />

What can I customize?

These controls are made to work with any ISitemap, which is, at its core, a container for a collection of ISitemapNodes.  You can provide custom implementations of these, customizing your sitemaps to your heart’s content!  For example, you might make sitemaps and sitemap nodes which:

  • Retrieve their data from an ASP.NET xml-based sitemap file
  • Authorize users for access to nodes based upon more than just roles
  • Check authorization based on metadata on the page type itself, or by using a NavigationAuthorizer from the AuthContentLoader library
  • Import one sitemap into another (I’ve actually provided an implementation of this in SLaB so that sitemaps and sub-sitemaps can be used)

Furthermore, the controls themselves are look-less, and you should be able to completely re-template them, customizing how hyperlinks are displayed, how much of the tree is expanded, and so on.  If there’s something I’m missing, let me know!

So, can I see it in action?

Of course!  You know I never leave you without a demo!  In fact, today I’ve got two for you!

First, the SLaB demo application itself uses these controls.  Click around and see how things behave.  You’ll notice the controls are the centerpiece of the navigation UI, but also make appearances throughout the application, such as on “category pages” that list only the links within a particular section of the site, and on error pages within the application, making it easier for users to get back to useful locations within the application.

The second demo application is meant to show role-driven sitemap trimming.  It uses WCF RIA Services to drive authentication and authorization, and shows and hides parts of the sitemap based upon the roles the user belongs to.  You can log in using the following credentials:

User: Test

Password: _Testing

Experiment with the application and what happens to the navigation controls as you log in and log out.  This also uses the AuthContentLoader from SLaB to perform additional authorization before actually loading any page.

Authorization-driven navigation controls 

The XAML for the sitemap in the application above shows how access can be restricted and how trimming takes effect:

<SLaB:Sitemap x:Key="Sitemap"
                Title="Scratch Business Application"
                Description="A sample RIA Services Business application that uses SLaB to represent its navigation and do authorization.">
    <SLaB:SitemapNode Title="Home"
                        Description="The home page for the application"
                        Uri="/Views/Home.xaml" />
    <SLaB:SitemapNode Title="Broken Link"
                        Description="A broken link"
                        Uri="/Views/NonExistentPage.xaml" />
    <SLaB:SitemapNode Title="Protected Pages (Non-Trimmed)"
                        Description="Pages protected by authorization">
        <SLaB:SitemapNode Title="About"
                            Description="The About page for the application"
                            Uri="/Views/About.xaml" />
        <SLaB:SitemapNode Title="Page for registered users"
                            Description="A page that can only be visited by registered users"
                            Uri="/Views/RegisteredUsersPage.xaml" />
    </SLaB:SitemapNode>
    <SLaB:SitemapNode Title="Protected Pages (Trimmed)"
                        Roles="Registered Users"
                        Description="Pages protected by authorization">
        <SLaB:SitemapNode Title="About"
                            Description="The About page for the application"
                            Uri="/Views/About.xaml?trimmed" />
        <SLaB:SitemapNode Title="Page for registered users"
                            Description="A page that can only be visited by registered users"
                            Uri="/Views/RegisteredUsersPage.xaml?trimmed" />
    </SLaB:SitemapNode>
    <SLaB:SitemapNode Title="Protected Pages (Leaf nodes trimmed)"
                        Description="Pages protected by authorization">
        <SLaB:SitemapNode Title="About"
                            Roles="Registered Users"
                            Description="The About page for the application"
                            Uri="/Views/About.xaml?leaftrimmed" />
        <SLaB:SitemapNode Title="Page for registered users"
                            Roles="Registered Users"
                            Description="A page that can only be visited by registered users"
                            Uri="/Views/RegisteredUsersPage.xaml?leaftrimmed" />
    </SLaB:SitemapNode>
    <SLaB:SitemapNode Title="DavidPoll.com"
                        Description="David Poll's homepage"
                        Uri="http://www.davidpoll.com"
                        TargetName="_blank" />
</SLaB:Sitemap>

Cool… but where are the bits?

Well, the good news is that you can get all of these controls in my Silverlight and Beyond (SLaB) libraries!  Give them a shot and let me know what you think.  What’s missing from these controls?  What other pieces of user experience are you looking for?  Are the behaviors of the TreeViewNavigator and BreadCrumbNavigator correct for your scenarios and desired UX?

With that said, here’s a summary of the links and access to the source!

  • Live Sample (source — found in the SLaB v0.7 source under "ScratchApplication")
  • Live Sample using RIA Services for AuthN/AuthX (source

    SLaB v0.7 (includes source, a sample app, some tests, and binaries)

    • For the latest version, please check out SLaB on my Downloads and Samples page.
    • The v0.7 download of SLaB includes the following changes:
      • Added TryImportResourceDictionary that allows XAML resource dictionaries to be imported but fail quietly (so that if not all dependencies for a control are met, other controls in the library (that share the same generic.xaml) can still be used.
      • Added XamlDependencyAttribute, which ensures that Xaml-only assembly dependencies can be declared and appear as dependencies in the assembly metadata.
      • Other minor bugfixes
    • In the interim (since my last post with SLaB), I also produced the v0.6 version, which had the following changes:
      • Made CollectionPrinter work for controls like DataGrid when they auto-generate columns for generic collections (based on the type in IEnumerable<T>)
      • Added a utility method that allows you to get the MethodInfo for an arbitrary method, including private ones (from anywhere that the method is accessible)
      • Other minor bugfixes

    As always, I’d love to know what you think!

  • A “refreshing” Authentication/Authorization experience with Silverlight 4

    At the beginning of the year, as part of a series of posts about the INavigationContentLoader extensibility point in Silverlight 4, I described a way to use a content loader to do authorization before allowing a user to navigate to a page.  With the content loader, you can either throw an exception when an unauthorized user tries to reach a protected Page, redirect your users to another Page, or return a different page (e.g. a Login page) in its stead.  This makes for a fairly nice experience for your users, wherein they are taken directly to a login page (or at least a page with more information about why they cannot access the given page) when they lack the credentials to reach the page they are requesting.

    The trouble with this, however, was that once your application reached the login page and your user attempted to log in, there was no clear/easy/universal way to get the user back to the location he/she was originally requesting.  Ideally, an application would keep its context (i.e. the Uri wouldn’t change) when it sends a user to a login page, and take the user to the restricted content once the right credentials are acquired.

    When I wrote my original post, I was aware of this limitation, and didn’t have a great solution for it.  Attempting to re-navigate to the requested page was unhelpful because navigating twice to the same Uri is a no-op.  Starting with the Silverlight 4 RC (and continuing into the RTW release, of course), however, such a solution exists!  We quietly added an API to Frame and NavigationService: Refresh().

    How does refreshing help?

    Calling Frame.Refresh() or NavigationService.Refresh() causes the entire page to be reloaded, meaning that a custom content loader will be called, providing an opportunity to return a different page (or redirect elsewhere).  Without having to make any changes to SLaB and the AuthContentLoader or ErrorPageLoader, we can now produce the desired experience!

    Now, our ContentLoader XAML looks like this:

    <navigation:Frame x:Name="ContentFrame"
                        Style="{StaticResource ContentFrameStyle}"
                        Source="/Home">
        <navigation:Frame.UriMapper>
            <uriMapper:UriMapper>
                <uriMapper:UriMapping Uri=""
                                        MappedUri="/Views/Home.xaml" />
                <uriMapper:UriMapping Uri="/{pageName}"
                                        MappedUri="/Views/{pageName}.xaml" />
            </uriMapper:UriMapper>
        </navigation:Frame.UriMapper>
        <navigation:Frame.ContentLoader>
            <SLaB:ErrorPageLoader>
                <SLaB:ErrorPage ExceptionType="UnauthorizedAccessException"
                                ErrorPageUri="/Views/LoginPage.xaml" />
                <SLaB:ErrorPage ErrorPageUri="/Views/ErrorPage.xaml" />
                <SLaB:ErrorPageLoader.ContentLoader>
                    <SLaB:AuthContentLoader Principal="{Binding User, Source={StaticResource WebContext}}">
                        <SLaB:NavigationAuthorizer>
                            <SLaB:NavigationAuthRule UriPattern="^/Views/About\.xaml\??.*$">
                                <SLaB:Deny Users="?" />
                                <SLaB:Allow Users="*" />
                            </SLaB:NavigationAuthRule>
                            <SLaB:NavigationAuthRule UriPattern="^/Views/RegisteredUsersPage\.xaml\??.*$">
                                <SLaB:Allow Roles="Registered Users" />
                            </SLaB:NavigationAuthRule>
                        </SLaB:NavigationAuthorizer>
                    </SLaB:AuthContentLoader>
                </SLaB:ErrorPageLoader.ContentLoader>
            </SLaB:ErrorPageLoader>
        </navigation:Frame.ContentLoader>
    </navigation:Frame>
    

    The primary difference between the XAML above and the original XAML I had posted was to remove the ErrorRedirector (which caused redirection to the login page rather than loading the login page in place of the requested page).  Because this was removed, we no longer need nested ErrorPageLoaders (which existed in order to redirect only in the login case, and load the error page without changing the Uri for other errors).  You’ll note that for the About page and the RegisteredUsers page, access is restricted.  When an UnauthorizedAccessException occurs, users will see the LoginPage.

    In the login page, all we need to do now is call NavigationService.Refresh() when the user logs in.  My example uses WCF RIA Service’s WebContext find out this information, but you could just as easily attempt to refresh after a ChildWindow is closed or a Login button is clicked.

    My LoginPage code looks like this:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        WebContext.Current.Authentication.LoggedIn += Authentication_LoggedIn;
    }
    
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        WebContext.Current.Authentication.LoggedIn -= Authentication_LoggedIn;
    }
    
    void Authentication_LoggedIn(object sender, AuthenticationEventArgs e)
    {
        NavigationService.Refresh();
    }

    Yep, that’s all it takes!  Now, when a user logs in (either by clicking the login button on the page or logging in through some other dialog in the application), the Frame’s content is refreshed, and the AuthContentLoader attempts to verify the user’s credentials once again.

    Cool!  Can I see it in action?

    You know I would never leave you without a sample!  Click the image below to see the sample application (based on my original example, just updated for SL4).  First try navigating to the protected pages without logging in, then try logging in and note how the page automatically is refreshed based upon your new credentials.

    Login information: Log in with User = “Test”, Password = “_Testing”

    A WCF RIA Services application with the AuthContentLoader

     

    You can find the source for this application here.

    Anything else I should know about Refresh()?

    Without a doubt, Refresh()’s usefulness is not restricted to this scenario.  With custom content loaders, it’s particularly useful to be able to refresh the page, since the page returned as a result of that navigation may change from one attempt to the next.  Even without a custom content loader, Refresh() allows you to create a new instance of a page, making re-initializing the page you’ve navigated to clean and simple.  The behavior is identical to navigating to a new page – the only difference is that the old and new Uris are identical, and the NavigationMode of the operation is “Refresh”.

    Please note: Refresh() will still respect the NavigationCacheMode of the Page and the CacheSize of the Frame.  If a Page is being cached, calling Refresh() will not create a new instance (but will still cause the Navigating/Navigated events and the corresponding overrides on Page to be raised/called).  To prevent this from happening, set the NavigationCacheMode of the page being refreshed to Disabled before the new page would be loaded (i.e. before Refresh() is called or while handling the Navigating event).

    Is that it?

    Yep, that’s it! :)  Let me know what you think!  What else would you like to see?

    Making printing easier in Silverlight 4

    Well, what an exciting week!  First Visual Studio 2010 is released, followed by Silverlight 4 yesterday!  Consequently, I was inspired to post about something new!  I’ve been spending some time looking at the new printing feature in Silverlight 4, and while on the surface it looks like a pretty simple and lower-level set of APIs, it’s possible to build rich frameworks on top of them for accomplishing common printing tasks.  In this post, I’ll take a look at an attempt I made (and added to SLaB) at building such a higher-level API over printing that makes printing collections of data easier.

    Specifically, I’ve been building a CollectionPrinter control – a control that paginates, previews, and prints collections in a template-driven, designer-friendly way.  With this control, printing a collection can be entirely XAML-based and code-free!

    For example, the image below shows some sample data (courtesy of the Blend 4 RC) within a DataGrid being printed across multiple pages.

    A printed collection.

    And you can see it in action by clicking here.

    Of course, this is just an example of how one might want to build such a library, but it hopefully inspires some ideas you all might have around printing!  I’d love to know what you think!

    So, how does printing work?

    The printing APIs in Silverlight 4 center around the PrintDocument class.  SilverlightShow has a great article on the basics of using this class.  Basically, the workflow for printing in Silverlight 4 is the following:

    1. Create a new PrintDocument
    2. Attach a handler to the PrintDocument.PrintPage event, which will be called for each page you choose to print
    3. Call PrintDocument.Print(), passing in a document name (which will appear in the print spooler, for example)
    4. The user is prompted to print
    5. In each PrintPage call:
      1. If you have content ready to print:
        1. Choose some UI to print to the page and set the PageVisual in the PrintPageEventArgs
        2. If there are more pages to print, set HasMorePages on PrintPageEventPargs to true
      2. If you’re not ready to print yet:
        1. Set PageVisual to null
        2. Set HasMorePages to true (you will be called back after a short delay for the content – up to 8 attempts will be made to print a page before printing fails)

    And that’s it!  For each page, Silverlight will render a bitmap of the visuals you provided in PageVisual (just like with WriteableBitmap), then send this bitmap to the printer.

    That all seems pretty straightforward… why do I need anything more?

    Well, it is pretty straightforward.  However, there’s a fair amount of work that you would have to do in order to create a coherently printed document:

    • Pagination – in order to figure out which items to print on each page, you will need to add items to the page, searching for the item that would flow beyond the end of the page.  This involves measuring/arranging pages and expanding templates, keeping track of the items you’ve printed so far, handling cases where items are too big for the page, and so on.
    • Page layout – it’s very common to want headers/footers on your pages, which further complicates the pagination process.
    • Page context – when printing a particular page, you often want some additional context, such as which items are on the page, the page number, the total number of pages (so that you can print “Page 1 / 10”, whether this is the first or last page, etc.  This context must be calculated and tracked, and is difficult when the printing process is progressive as with the above API (e.g. how can I print the first page without first having rendered all of the pages, so that I know what the total page count will be?)
    • Dealing with content not in the visual tree – often, you want to print UI directly from the visual tree, which is much easier.  But when printing controls that are NOT in the visual tree, life gets much more complicated.  As with WriteableBitmap, controls used as the PageVisual don’t get a full visual tree pass, meaning that events like FrameworkElement.Loaded don’t get raised.  Some controls use such events to do initialization, such as the charting controls in the Silverlight Toolkit.  In order to properly print arbitrary controls, it’s often helpful to actually place the control in the visual tree.
    • Handling animations – many controls (again, such as the charting controls in the Silverlight Toolkit) have animations and transitions by default.  For the charting controls, the data points being charted fade in by default.  If you try to print this when the control is created, you’ll get a blank chart!  One way to deal with this (if it’s the desired behavior) is to walk the visual tree, causing any running storyboard to SkipToFill.
    • Print preview – while it’s not really possible to give a full preview of what a printed document will look like (because you can’t find out what the size/margins of the page will be before printing has started), one can approximate it and at least provide a hint as to what to expect when printing begins.
    • Designability – Working with pages to print in Blend or Visual Studio’s designer can be somewhat difficult, especially if you need to write the code to handle the above cases.

    As you can see, there are a number of complicating factors when doing sophisticated printing, but these can be abstracted away if the domain you’re given is specific enough.  In this case, we’re printing a collection, and we can use the items in the collection as the units between which we can break up pages.

    OK, cool, I think I get it.  So, how does it work?

    You can use the CollectionPrinter much like an ItemsControl.  It’s fundamentally DataTemplate-driven.  It has an ItemsSource and an ItemTemplate, but instead, you can specify a BodyTemplate (which, by default, is an ItemsControl :)).  For headers, footers, and such, you can specify additional DataTemplates.

    All of the DataTemplates are bound to a “CollectionPrintContext” which contains the following pieces of information:

    • CurrentItems – the set of items being printed on this page (this collection will be built up dynamically during printing/previewing)
    • CurrentPage/CurrentPageIndex – the page number (1- or 0-based) being printed
    • First/Last items (so that you can print “Items 1-10” or “Aa – Aardvark” on each page):
      • FirstItem/FirstItemIndex/FirstItemValue – the first item being printed on the page (1-based index, 0-based index, or actual value, respectively)
      • LastItem/LastItemIndex/LastItemValue – the last item being printed on the page (1-based index, 0-based index, or actual value, respectively)
    • PageCount – the total number of pages to print (note: this is a nullable int value and may not be provided if there isn’t time to finish pre-rendering all pages before the PrintPage callback limit is reached)
    • PageMargins – the margins of the page being printed
    • PrintableArea – the size of the space in which the page can be printed

    The hope is that with these pieces of information to bind to, you can print rich pages for your users.  The rest is just creative use of bindings :)

    To kick off printing, either call the Print() method on the CollectionPrinter or bind a button to the PrintCommand property on the CollectionPrinter for completely code-free printing!

    The CollectionPrinter will attempt to address all of the issues above, spawning invisible popups to ensure that the UI actually has a moment to be in the visual tree, walking the visual tree to skip animations to fill, and most importantly paginating all of the items in the ItemsSource.

    Let’s see it in action!

    Using an ItemTemplate

    The most basic case for printing with the CollectionPrinter is to use an ItemTemplate, just as you would with an ItemsControl.  The CollectionPrinter will happily handle cases where items are irregularly sized, so be as rich as you’d like!

    For example:

    ItemTemplate-based Printing

    The XAML style for this CollectionPrinter is as follows:

    <Style x:Key="PrintStyle"
            TargetType="SLaB:CollectionPrinter">
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border BorderThickness="1"
                            BorderBrush="Gray">
                        <Grid>
                            <Grid.Resources>
                                <Style TargetType="TextBlock">
                                    <Setter Property="FontSize"
                                            Value="12" />
                                </Style>
                            </Grid.Resources>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <StackPanel Grid.Column="0"
                                        Margin="10">
                                <Image Source="{Binding Photo}"
                                       Height="{Binding Age}"
                                       Width="{Binding Age}"
                                       HorizontalAlignment="Left" />
                                <TextBlock Text="{Binding Name, StringFormat='Name: {0}'}" />
                                <TextBlock Text="{Binding Age, StringFormat='Age: {0}'}" />
                                <TextBlock Text="{Binding Address, StringFormat='Address: {0}'}"
                                           TextWrapping="Wrap" />
                            </StackPanel>
                            <toolkit:Chart Grid.Column="1"
                                           Title="{Binding Name}">
                                <toolkit:ScatterSeries DependentValuePath="X"
                                                       IndependentValuePath="Y"
                                                       Title="Values"
                                                       ItemsSource="{Binding Values}" />
                            </toolkit:Chart>
                        </Grid>
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate> ... </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="FooterTemplate">
            <Setter.Value>
                <DataTemplate> ... </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <SLaB:CollectionPrinter x:Name="printer"
                            Style="{StaticResource PrintStyle}" />
    

    All it takes to print based on this style is setting the ItemsSource (in this case to some Blend sample data) and binding a button to the PrintCommand on the control.  In my header and footer templates, I have controls that are bound to the CollectionPrintContext, and whose visibilities are determined by binding to things like IsFirstPage (see the source included in the SLaB download for more details).

    Changing the BodyTemplate (and printing a DataGrid)

    Now, that’s all wonderful if all I want to do is print something that looks like an ItemsControl.  But what can we do if we want to print a DataGrid (with column headers, etc.)?  Well, the CollectionPrinter doesn’t depend on being given an ItemsControl at any point.  Instead, it determines pagination based upon the DesiredSize of its content after measuring/arranging.  As a result, anything that grows as its bound content is changed will work with the CollectionPrinter.  You can easily print a DataGrid in this way, as I’ve done below:

    DataGrid-based PrintingAnd the XAML barely changes from what you see above.  In this case, instead of using an ItemTemplate, I set a BodyTemplate, which is a DataGrid (with vertical scrolling disabled) with a variety of columns.  In this case, I’ll specify the DataTemplates inline:

    <SLaB:CollectionPrinter xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
                            xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:SLaB="http://www.davidpoll.com/SLaB">
        <SLaB:CollectionPrinter.HeaderTemplate>
            <DataTemplate> ... </DataTemplate>
        </SLaB:CollectionPrinter.HeaderTemplate>
        <SLaB:CollectionPrinter.FooterTemplate>
            <DataTemplate> ... </DataTemplate>
        </SLaB:CollectionPrinter.FooterTemplate>
        <SLaB:CollectionPrinter.BodyTemplate>
            <DataTemplate>
                <sdk:DataGrid ItemsSource="{Binding CurrentItems}"
                              AutoGenerateColumns="False"
                              VerticalScrollBarVisibility="Disabled">
                    <sdk:DataGrid.Columns>
                        <sdk:DataGridTextColumn Binding="{Binding Name}"
                                                Header="Name" />
                        <sdk:DataGridTextColumn Binding="{Binding Address}"
                                                Header="Address" />
                        <sdk:DataGridTextColumn Binding="{Binding Age}"
                                                Header="Age" />
                        <sdk:DataGridTemplateColumn Header="Image"
                                                    IsReadOnly="True">
                            <sdk:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Image Source="{Binding Photo}"
                                           Height="50"
                                           Width="50" />
                                </DataTemplate>
                            </sdk:DataGridTemplateColumn.CellTemplate>
                        </sdk:DataGridTemplateColumn>
                        <sdk:DataGridTemplateColumn Header="Values"
                                                    Width="*"
                                                    IsReadOnly="True">
                            <sdk:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <chartingToolkit:Chart Title="{Binding Name}">
                                        <chartingToolkit:ScatterSeries DependentValuePath="X"
                                                                       IndependentValuePath="Y"
                                                                       Title="Values"
                                                                       ItemsSource="{Binding Values}" />
                                    </chartingToolkit:Chart>
                                </DataTemplate>
                            </sdk:DataGridTemplateColumn.CellTemplate>
                        </sdk:DataGridTemplateColumn>
                    </sdk:DataGrid.Columns>
                </sdk:DataGrid>
            </DataTemplate>
        </SLaB:CollectionPrinter.BodyTemplate>
    </SLaB:CollectionPrinter>
    
    

    Explicitly providing individual pages

    You can also use the CollectionPrinter for printing multiple pages explicitly (automatically dealing with all of the PrintPage callbacks, running animations, etc.) by providing a series of DataTemplates (one for each page) as the ItemsSource, changing the BodyTemplate to a ContentControl, and setting the maximum number of items to print per page to 1.  For example:

    Individual Pages

    And, of course, the corresponding XAML:

    <SLaB:ObservableObjectCollection x:Key="Pages">
        <DataTemplate>
            <StackPanel>
                <TextBlock FontWeight="Bold"
                            FontSize="20">Lorem Ipsum</TextBlock>
                <TextBlock TextWrapping="Wrap"
                            Margin="10"
                            xml:space="preserve">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ultrices cursus tortor ac egestas. Pellentesque semper lobortis enim, vel imperdiet dolor vehicula ac. Suspendisse auctor tempus molestie. Cras pulvinar sagittis libero, vel pretium ipsum consectetur sit amet. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum feugiat nunc eget ante euismod ac facilisis velit aliquet. Vestibulum eget nulla magna, eget scelerisque ligula. Cras nec nisi faucibus leo fermentum euismod eu vel lacus. Etiam lacus massa, pulvinar id tempor eget, varius at lorem. Praesent venenatis nisi ac ipsum facilisis at suscipit magna sollicitudin. Phasellus placerat imperdiet hendrerit. Nulla ac risus velit. Sed orci lorem, imperdiet vel ultrices et, viverra ut leo. Mauris feugiat, diam eget mollis tempus, est leo pellentesque risus, vitae lacinia ante felis hendrerit elit. 
    
    Suspendisse potenti. Donec dui justo, ultrices quis condimentum vel, bibendum vel nisi. Pellentesque suscipit fermentum dui vel sodales. Nulla vitae tortor vel orci posuere vestibulum. Curabitur non lacus quam. Nulla sit amet tempor libero. Integer dictum lectus ut sem adipiscing vitae fringilla felis accumsan. Mauris ut risus felis, ut pulvinar quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Integer fermentum, turpis sit amet tincidunt fermentum, metus mauris bibendum nisi, nec tincidunt purus enim nec nisi. Sed faucibus congue ultricies. Maecenas sed lorem id sem ornare imperdiet ut vitae libero. Curabitur mi diam, ornare sit amet dignissim eu, imperdiet sed nibh. Donec ultrices libero sed ipsum sollicitudin in dapibus elit rutrum. Nulla egestas tempus est, nec semper lacus sodales vel. Quisque consectetur turpis nunc, eu pretium felis. Etiam non adipiscing elit. 
    
    Cras sit amet volutpat metus. Nunc eu augue eu urna placerat adipiscing in vel lacus. Etiam auctor orci nec dui adipiscing non viverra nisl gravida. In lacinia venenatis lobortis. Vestibulum dignissim, dolor ut feugiat ultricies, eros odio adipiscing augue, quis congue turpis augue quis mauris. Aliquam at ligula sem. Aenean eget arcu ac odio eleifend convallis. Aenean eu tellus ac eros placerat aliquam. Nam consectetur neque sed massa accumsan mollis. Pellentesque in mi erat, eget tristique elit. Praesent mattis magna sed est placerat bibendum venenatis nulla facilisis. Duis nec mollis nisi. Vestibulum et eros vitae felis vestibulum scelerisque. Donec venenatis, nulla vel rutrum tempus, purus nulla feugiat felis, eu semper diam nibh tincidunt metus. 
    
    Praesent venenatis aliquet vulputate. In suscipit, nulla ut pulvinar ullamcorper, diam ligula sagittis enim, fermentum tempus nunc neque sed nisi. Vivamus aliquam rutrum scelerisque. Phasellus suscipit, quam sed suscipit pretium, massa nunc elementum lectus, et adipiscing arcu turpis sed dolor. Suspendisse potenti. Proin nisl mauris, sodales tincidunt ultricies sed, placerat quis enim. Nulla elementum nunc vel sapien venenatis venenatis vel eu ligula. Sed vitae erat ante. Etiam nec sapien nec sapien sagittis hendrerit. Duis at odio dolor. Sed condimentum euismod felis, ut congue dolor luctus quis. Duis non tellus enim. Quisque quis odio erat. Nulla nulla mi, dapibus ut euismod ut, adipiscing nec lacus. Aliquam faucibus dui at est accumsan ut laoreet erat pellentesque. Nullam id malesuada tellus. Donec et ligula tincidunt metus rutrum pretium. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; 
    
    Sed lacinia dignissim scelerisque. Duis pharetra elit et nisl euismod viverra. Nam semper, purus ut luctus tincidunt, eros nisi aliquam nunc, non semper lorem enim sit amet augue. Vestibulum adipiscing tortor a magna tristique fringilla. Etiam porta volutpat odio, eu posuere velit mollis non. Mauris ut arcu quis lectus dapibus condimentum. Pellentesque non bibendum nisi. In hac habitasse platea dictumst. Maecenas laoreet lorem ut sem pellentesque id facilisis nibh pulvinar. Vivamus tempus erat placerat diam condimentum ac bibendum felis egestas. Quisque mollis hendrerit risus, ac euismod metus dapibus nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus quis ipsum euismod dolor pharetra viverra eget a augue. Morbi lorem enim, porta ut congue quis, pretium et enim.
                </TextBlock>
            </StackPanel>
        </DataTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <TextBlock FontWeight="Bold"
                            FontSize="20">Lorem Ipsum</TextBlock>
                <Image Grid.Row="1"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Source="/ScratchPrintingProject;component/SLaB Logo.png" />
            </Grid>
        </DataTemplate>
    </SLaB:ObservableObjectCollection>
    <Style x:Key="PrintStyle"
            TargetType="SLaB:CollectionPrinter">
        <Setter Property="MaximumItemsPerPage"
                Value="1" />
        <Setter Property="BodyTemplate">
            <Setter.Value>
                <DataTemplate>
                    <ContentControl ContentTemplate="{Binding CurrentItems[0]}"
                                    HorizontalContentAlignment="Stretch"
                                    VerticalContentAlignment="Stretch" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate> ... </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <SLaB:CollectionPrinter x:Name="printer"
                            ItemsSource="{StaticResource Pages}"
                            Style="{StaticResource PrintStyle}" />
    

    Above, I have two pages: one with a bunch of text, and one with a large image on it.  I still get all of the context for my headers/footers, and can use this as a way to get the benefits of using the CollectionPrinter without being locked into an ItemsControl-like behavior.

    Headers and Footers

    Creating Headers and Footers for each page is also really easy with the CollectionPrinter – just specify a HeaderTemplate or a FooterTemplate.  These DataTemplates are bound to the CollectionPrintContext, which you can use to generate your header and footer info.  I use some ValueConverters (in one of the SLaB libraries, if you’d like to reuse them) to conditionalize Visibility of a title for a document to the first page, and to change colors/text for the other pages.  I also use the FirstItemValue/LastItemValue to provide a “Aa – Aardvark” (like you’d find in a dictionary) footer on each page.

    For example, the sample pages above use the following XAML for their header/footers:

    <SLaB:CollectionPrinter.HeaderTemplate>
        <DataTemplate>
            <StackPanel HorizontalAlignment="Stretch">
                <StackPanel.Resources>
                    <SLaB:BoolConverter x:Key="BoolConverter" />
                </StackPanel.Resources>
                <StackPanel HorizontalAlignment="Right"
                            Orientation="Horizontal">
                    <TextBlock Text="{Binding CurrentPage, StringFormat='{}Page {0} '}" />
                    <TextBlock Text="{Binding PageCount, StringFormat='{}/ {0}'}" />
                </StackPanel>
                <TextBlock HorizontalAlignment="Center"
                            Visibility="{Binding IsFirstPage, Converter={StaticResource BoolConverter}}"
                            FontSize="32">This is a test document!</TextBlock>
                <TextBlock HorizontalAlignment="Center"
                            Visibility="{Binding IsLastPage, Converter={StaticResource BoolConverter}}"
                            FontSize="16">This is the last page!</TextBlock>
                <TextBlock HorizontalAlignment="Center"
                            FontSize="14">
                    <TextBlock.Foreground>
                        <Binding Path="CurrentPage">
                            <Binding.Converter>
                                <SLaB:EvenOddConverter>
                                    <SLaB:EvenOddConverter.Even>
                                        <SolidColorBrush Color="Blue" />
                                    </SLaB:EvenOddConverter.Even>
                                    <SLaB:EvenOddConverter.Odd>
                                        <SolidColorBrush Color="Red" />
                                    </SLaB:EvenOddConverter.Odd>
                                </SLaB:EvenOddConverter>
                            </Binding.Converter>
                        </Binding>
                    </TextBlock.Foreground>
                    <TextBlock.Text>
                        <Binding Path="CurrentPage"
                                    StringFormat="This page is {0}">
                            <Binding.Converter>
                                <SLaB:EvenOddConverter>
                                    <SLaB:EvenOddConverter.Even>
                                        Even
                                    </SLaB:EvenOddConverter.Even>
                                    <SLaB:EvenOddConverter.Odd>
                                        Odd
                                    </SLaB:EvenOddConverter.Odd>
                                </SLaB:EvenOddConverter>
                            </Binding.Converter>
                        </Binding>
                    </TextBlock.Text>
                </TextBlock>
            </StackPanel>
        </DataTemplate>
    </SLaB:CollectionPrinter.HeaderTemplate>
    <SLaB:CollectionPrinter.FooterTemplate>
        <DataTemplate>
            <StackPanel HorizontalAlignment="Center"
                        Orientation="Horizontal">
                <TextBlock Text="{Binding FirstItemValue.Name}" />
                <TextBlock Text=" - " />
                <TextBlock Text="{Binding LastItemValue.Name}" />
            </StackPanel>
        </DataTemplate>
    </SLaB:CollectionPrinter.FooterTemplate>
    

    Nifty, isn’t it? :)

    That’s a lot of XAML!  Do I have to write all of that by hand?

    Of course not!  In fact, with the CollectionPrinter, Blend gives you a nice little print preview (especially if you use it as the root of a XAML file) and lets you modify the various templates directly in Blend, inline with the rest of the page!  You can adjust the “CurrentPageIndex” property to preview your CollectionPrinter configuration in the designer.

    Editing templates within Blend

    To accomplish this in Blend:

    • Select a CollectionPrinter on the designer (either making it the root of a XAML document or selecting it in your existing XAML)
    • Right-click the CollectionPrinter in the Objects and Timeline Window
    • Choose “Edit Additional Templates”
    • Choose a template to edit, and either edit a copy, edit the current template, or create an empty template.
    • Edit away!  Drag/drop your printed content!

    So, what’s it all add up to?

    It’s very common for business applications to want to print the data they’ve collected, and it’s not hard to see how that might be a chore.  Silverlight 4 introduced the printing feature, which allows printing at a very low level, but it also allows a huge amount of freedom in determining exactly what gets rendered to the page.  This freedom can make simple printing tasks a chore.  My hope is that the CollectionPrinter helps demonstrate how one might build a general-purpose (but more constrained than the built-in API) printing API.  I’d love to know what you think.  For me, it was primarily an experiment to see how close I could come to making printing large data sets easy and designable.  Does this come close to what you’d hope for?  What would your ideal be?

    Sweet!  Can I try it?!

    I’m glad you’re so enthused!  I’m tempted to say no, but wouldn’t torture you like that :).  You can give it a shot using my latest build of Silverlight and Beyond.

    You can see the live demos here (Requires Silverlight 4):

    Printing samples

    If you’d like to save time printing (yeah, it takes a while – it renders some pretty large bitmaps!), you can see some sample output files below.  Notice that the “Long” documents don’t have the total page count displayed, since it took longer to pre-render all of the pages than the PrintPage retry limit would permit:

    • ItemTemplate-based Document – Short (PDF 7.5 MB), Long (PDF 37.7 MB)
    • DataGrid-based Document – Short (PDF 7.9 MB), Long (PDF 37.0 MB)
    • Individual page-based Document – Download (PDF 5.8 MB)

    Finally, some source code for you:

  • Live Sample (source — found in the SLaB v0.5 source under "ScratchPrintingProject")
  • SLaB v0.5 (includes source, a sample app, some tests, and binaries)

    • For the latest version, please check out SLaB on my Downloads and Samples page.
    • The v0.5 download of SLaB includes the following changes:
      • Updated for SL4 RTW
      • Added CollectionPrinter for printing collections of items
      • Fixed a bug with Sitemap-based controls that caused some pack Uris to be evaluated as "equivalent" (and thus highlighted) even when they were not
      • Added EvenOddConverter that allows you to select an arbitrary value based on whether the input value was even or odd
      • Other minor bugfixes

    Enjoy, and let me know if you have any questions, thoughts, or ideas!

    Remember, SLaB is just a collection of the samples and experimental components I’ve been putting together so that they’re all in one place.  I can’t make any guarantees about maintaining them, fixing bugs, not making breaking changes, etc., but you’re more than welcome to try them out, use them, and let them inspire your development (or show you what not to do if you really dislike something I’m doing!) :).

    P.S. Do you know you talk to yourself in these blog posts?

    Yes, yes I do, Mr. “Person behind the headers of the sections in my blog posts who is actually me.” 

     

    UPDATE 4/25/2010: Thanks for the feedback in the comments on this post.  I have updated the CollectionPrinter to help with the DataGrid AutoGenerateColumns issue reported by “mb”.  It may still have problems if the ItemsSource is not an IEnumerable<T> (but rather just a plain IEnumerable), but I think this should cover the 90% case.

    You can download the newest bits here.  I also added a nice little utility method to SLaB that helps get a MethodInfo using a compiled Expression (using the LINQ expression libraries).  Please let me know if you encounter other issues!

    New in the Silverlight 4 RC: XAML Features

    Today, the Silverlight 4 RC was announced and made available to the masses.  But you may be asking yourself: what’s new since the beta?  Well, I’d like to dive into one of the areas where a bunch of new work was done to improve the development experience – the XAML Parser.  With Silverlight 4, we’ve done a significant overhaul of the XAML Parser, allowing us to add new features and improve consistency within the platform and with WPF’s XAML support.

    So, let’s take a quick walk through some of the new things you can do with Silverlight XAML as of the RC!  This is by no means an exhaustive list, but it’s definitely some of the bigger items.

    Direct Content

    This is one of those small inconsistencies with WPF that people hit almost immediately when they try to write Silverlight XAML after moving over from the WPF world.  Specifically, things like this now work in Silverlight:

    <Button>Click me!</Button>
    

    I know, I know – exciting, right!?  In Silverlight 3, you had to use attribute syntax or explicitly surround “Click Me!” in a string, like this:

    <Button Content="Click me!" />
    

    or…

    <Button xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <sys:String>Click me!</sys:String>
    </Button>
    

    I know when I first made the move from WPF to Silverlight, this was among the most irksome and frustrating things about its XAML parser.  With Silverlight 4, that frustration is gone, and I can enjoy direct content in my controls once again!

    See the image below for more examples:

    A quick demo of direct content support in Silverlight 4 XAML.

    xml:space=”preserve”

    In previous versions of Silverlight, the XAML parser was rather liberal about how it applied whitespace.  In general, it didn’t discard extra whitespace as most XML parsers will.

    For example, the following XAML:

    <TextBlock>
        <TextBlock.Text>This
    Text
    Is
    On
    Separate
    Lines
        </TextBlock.Text>
    </TextBlock>
    

    Looked like this:

    Whitespace preservation in prior versions of Silverlight.

    The XAML parser in Silverlight 4 has finally corrected this behavior, and has also added support for xml:space=”preserve”.

    When you recompile your application with the Silverlight 4 RC, the same XAML will produce the following:

    image 

    To get back the old behavior, add xml:space=”preserve” to your XAML:

    <TextBlock xml:space="preserve">
        <TextBlock.Text>This
    Text
    Is
    On
    Separate
    Lines
        </TextBlock.Text>
    </TextBlock>
    

    Finally, you have control over your whitespace back!  The results are much more predictable, and you can now be explicit about what you want the text content to be.

    Please note: when you upgrade your application to Silverlight 4 (i.e. recompile for Silverlight 4), you’ll need to watch out for this change!

    ISupportInitialize

    If you were a fan of the ISupportInitialize interface in the full framework, it’s finally made its way into Silverlight!  The XAML parser in Silverlight will now call ISupportInitialize.BeginInit() and ISupportInitialize.EndInit() on your classes (if you implement the interface) before and after setting properties defined in XAML.  This allows you to wait to do work until after all of your properties have been set, allowing you to handle properties that would otherwise be order-dependent and add some validation that combinations of properties are valid.

    It’s a convenient and welcome functionality to have around, especially for those of us that like declarative programming and are happy to use XAML as our format for doing so!

    XmlnsDefinition attribute

    In Silverlight 3 and earlier, how many times did you find yourself in a situation like this?

    <UserControl x:Class="SilverlightApplication1.MainPage"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
                 xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
                 xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input"
                 xmlns:navigationMappings="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"
                 xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
                 xmlns:ohmygoshtherearetoomanyofthese="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
                 mc:Ignorable="d"
                 d:DesignHeight="300"
                 d:DesignWidth="400">...
    

    And that’s just with some of the SDK assemblies!  Declaring xmlns’s in your XAML was a chore, and it was extremely easy to end up with a huge mess of them, as they require one definition per namespace/assembly.  Add in the toolkit controls and any custom libraries, and you’re easily looking at 20 lines of these definitions.  This is more than just a problem of convenience – it makes XAML intellisense a big problem as well.  Visual Studio starts its intellisense experience by waiting for an xmlns to be entered, such as “input:”.  Within that namespace, it will filter your options to valid tags for your context within the XAML.

    But, if you’re like me and like to break your libraries up into small pieces, this is not very helpful – I have to remember exactly which xmlns has which set of things that derives from the type I’m trying to create in XAML, and if I got it wrong, there’s not much there to help me.

    Silverlight 4 adds support for the XmlnsDefinitionAttribute in custom assemblies, and the SDK has been updated to take advantage of this.  Now, you can replace all of the code above with this:

    <UserControl x:Class="SilverlightApplication1.MainPage"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
                 mc:Ignorable="d"
                 d:DesignHeight="300"
                 d:DesignWidth="400">...
    

    Likewise, with the next update of the Silverlight Toolkit, you will likely see a similar change, allowing you access to all referenced toolkit controls from one xmlns!  Phew!  What a relief!

    With that in mind, I’ve also updated SLaB to use XmlnsDefinitionAttribute, which really helps clean up the use of those libraries with Silverlight 4.

    This is one of my favorite features, if only because it makes working with XAML so much simpler in Visual Studio, and now it’s available for you and other control/XAML-centric developers to use in your libraries as well!

    Xmlns flexibility

    Silverlight 3 required that your default namespace always be the following:

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    

    This was sometimes irritating when you wanted to use XAML as a serialization format for something other than UI, since you had to preface every element with some other xmlns.  In Silverlight 4, you can now change the default xmlns namespace at will, which you can use to clean up your XAML and customize your serialization format as you wish.

    Custom IDictionary support

    In XAML, it’s supposed to be possible to add items to a dictionary just as you would a list by using the “x:Key” attribute.  In prior versions of Silverlight, the only case where this was allowed was when used inside of a ResourceDictionary.

    With Silverlight 4, anything that implements IDictionary can be used in XAML.  To this end, I’ve provided a simple BindableDictionary in my SLaB libraries that you can now use like so (although you could just as easily use a Dictionary<object, SomeType> or a custom implementation of IDictionary):

    <SLaB:BindableDictionary x:Key="ValueBag"
                                    xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <sys:Double x:Key="Value Between Zero and 100">37.9184273</sys:Double>
        <sys:Boolean x:Key="A boolean">True</sys:Boolean>
    </SLaB:BindableDictionary>
    

    This is extremely useful for more complex XAML scenarios where you want a Dictionary rather than a List to be declared in XAML.  One example I’ve been wanting to play with: an INavigationContentLoader (it’s an obsession – I’m sick, I know :)) that maps a protocol (e.g. http:// or pack://) to another INavigationContentLoader, allowing protocol-specific content loading within a single application.

    Non-DependencyProperty Attached Properties

    Although you’re probably used to seeing them as such, attached properties are actually completely separate from DependencyProperties (just as properties are distinct from DependencyProperties).  In order to style or bind to them, they must be DependencyProperties.  Otherwise, it’s just an API convention:

    using System.Collections.Generic;
    using System.Windows.Controls;
    
    namespace SilverlightApplication1
    {
        public class ClassWithAttachedProperty
        {
            private static Dictionary<Grid, int> values = new Dictionary<Grid, int>();
            public static int GetGridMetadata(Grid g)
            {
                return values[g];
            }
            public static void SetGridMetadata(Grid g, int someValue)
            {
                values[g] = someValue;
            }
        }
    }

    Which can then be used in XAML like so:

    <UserControl x:Class="SilverlightApplication1.MainPage"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:my="clr-namespace:SilverlightApplication1">
        <Grid x:Name="LayoutRoot" my:ClassWithAttachedProperty.GridMetadata="150">
        </Grid>
    </UserControl>
    

    Note: I don’t recommend keeping a dictionary of Grid—>int around :).  That’s a giant memory leak waiting to happen!  It’s just convenient for demonstrative purposes.

    Better error messages

    One of the biggest complaints about XAML in Silverlight has been its poor reporting of errors when you’ve done something wrong.  This should have significantly improved in Silverlight 4.  In general, you’ll get more context and much clearer error messages at runtime when you make a mistake in XAML.  In general, that feeling of “what the heck just happened?” should be lifting when it comes to working with XAML.  It’s still not perfect, but things have improved significantly.

    Wow, that’s a lot of stuff!

    Yep, there’s been plenty of change with the parser, and the improvements should lead to a better experience when doing declarative development using XAML in Silverlight!  Please let me know what you think!  What’s your favorite feature or biggest peeve?

    What about SLaB?

    I’ve updated SLaB for the Silverlight 4 RC.  There’s a bunch of new stuff in there that I hope to blog about soon.  In the meantime, here’s a snippet from the changelog:

    • For the latest version, please check out SLaB on my Downloads and Samples page.
    • The v0.4 download of SLaB includes the following changes:
      • Added ZipUtilities so that the contents of a zip file can be discovered
      • Updated XapLoader to use ZipUtilities, allowing all TPEs to work rather than being limited to single-file TPEs where the file is named the same as the zip
      • Added Sitemap-based controls: BreadCrumbNavigator and TreeViewNavigator
      • Added ChangeLinq libraries for working with INotifyCollectionChanged collections and LINQ
      • Added ObservableDictionary and BindableDictionary, which raise INotifyCollectionChanged and INotifyPropertyChanged events as the dictionary changes, making it more usable with Binding
      • Added a basic MEFContentLoader
      • Updated to use XmlnsDefinitionAttribute wherever possible
      • Added XmlnsDefinition attributes to all libraries and updated ScratchApplication to use them
      • Other minor bugfixes

    Enjoy, and let me know if you have any questions, thoughts, or ideas!

    Remember, SLaB is just a collection of the samples and experimental components I’ve been putting together so that they’re all in one place.  I can’t make any guarantees about maintaining them, fixing bugs, not making breaking changes, etc., but you’re more than welcome to try them out, use them, and let them inspire your development (or show you what not to do if you really dislike something I’m doing!) :) .

    On-demand loading of assemblies with Silverlight Navigation – Revisited for Silverlight 4 Beta

    Way back in July, shortly after Silverlight 3 was released, I posted a technique that allowed you to use the Navigation framework in the SDK to load pages in dlls that would be downloaded as part of the navigation process.  The solution relied on two things: a workaround to the navigation framework’s inability to navigate to Pages in dynamically-loaded assemblies, and a derived version of the Frame class that hid many methods in order to orchestrate downloads of dlls and their dependencies.

    With Silverlight 4’s INavigationContentLoader extensibility point, we can address this scenario much more effectively, and are no longer locked into the workarounds and strict constraints that Silverlight 3’s navigation feature placed on us.  In this post, I’ll walk through the use of another ContentLoader I’ve been working on and look at how it simplifies building multi-xap applications.

    Getting a jump-start

    If you’d like to get started quickly and see the magic of multi-xap applications, follow these steps (note: Requires the Silverlight 4 Beta and an active internet connection) or download the source for the steps below here (you may need to fix up the references after downloading SLaB):

    1. Download and extract SLaB
    2. Open Visual Studio 2010 and create a new Silverlight 4 project using the Silverlight Navigation Application template.  When prompted to create a corresponding ASP.NET web application, just click “OK” and let Visual Studio create a web project for you.
    3. Add a reference to SLaB.Navigation.ContentLoaders.Xap.dll from the extracted Binaries folder.
    4. Add the following line of code to App.xaml.cs: PackUriParser.Initialize();
    5. Replace the Frame in MainPage.xaml with the following code (new code is bold/italic– the rest is identical to the default project xaml except for formatting):
    <navigation:Frame x:Name="ContentFrame"
                      Style="{StaticResource ContentFrameStyle}"
                      Source="/Home"
                      Navigated="ContentFrame_Navigated"
                      NavigationFailed="ContentFrame_NavigationFailed">
        <navigation:Frame.UriMapper>
            <uriMapper:UriMapper>
                <uriMapper:UriMapping Uri=""
                                      MappedUri="/Views/Home.xaml" />
                <uriMapper:UriMapping Uri="/{pageName}"
                                      MappedUri="/Views/{pageName}.xaml" />
            </uriMapper:UriMapper>
        </navigation:Frame.UriMapper>
        <navigation:Frame.ContentLoader>
            <SLaB:XapContentLoader xmlns:SLaB="clr-namespace:SLaB.Navigation.ContentLoaders.Xap;assembly=SLaB.Navigation.ContentLoaders.Xap"
                                   EnableCrossDomain="True" />
        </navigation:Frame.ContentLoader>
    </navigation:Frame>
    

    1. Run the application.
    2. Replace “#/Home” in your browser’s address bar with “#pack://http:,,open.depoll.com,SimpleApplication,SimpleApplication.xap/SimpleApplication;component/Depoll.xaml?Source=http://open.depoll.com&File=wildlife.wmv”
    3. Wait for a moment, and then enjoy the (admittedly underwhelming) show!

    Whoa, what just happened?!

    You just created an application that loaded a page in another xap!  It took only two actions to make this happen: registering the “PackUriParser” and setting the Frame’s ContentLoader to a XapContentLoader with cross-domain access enabled.  When you added the “pack://…” to the browser’s address bar, you told the content loader to downlaod a xap at http://open.depoll.com/SimpleApplication/SimpleApplication.xap (which is on my personal site, and has a very permissive cross-domain policy) and load the page “Depoll.xaml”.

    The XapContentLoader makes loading pages in other xaps (and reducing your download sizes) as easy as coming up with a URI that points to the page.  Read on to learn more about how to use the XapContentLoader and some of the problems associated with multi-xap applications.

    Why load pages in external xaps?

    This has always been a particularly interesting scenario to me.  The size of your application’s xap file can have a big impact on your users’ experience with your Silverlight application.  Since the entire xap and its dependencies (e.g. cached assemblies) must download before users can interact with your application, keeping the xap’s size small means users can start using your application sooner and are less likely to give up and click away.

    Partitioning your application into smaller-sized chunks that download only when users attempt to access that piece of functionality can also save bandwidth (since users need not download parts of the application they won’t use).

    The folks behind both MEF (Package catalogs) and Prism (Modules) have great libraries that help you accomplish this partitioning.  To me, navigation is a natural delineator of application functionality – Pages represent pieces of functionality your users can access, so triggering loading of other assemblies/xaps as part of navigation means that users will get the pieces of the application when they want to use them.

    In this post, I will be outlining a XapContentLoader, which makes loading pages in other Xaps a 2-lines-of-code problem to solve.  I’ve added this ContentLoader and some related utilities to SLaB, so you can use it yourself or play with the code if you like!

    XapLoader

    The first component I needed to make this scenario work was a way to download and load xap files.  As such, I wrote a XapLoader utility.  The strategy I used for loading xaps was the following:

    1. Download the xap
    2. Read the AppManifest.xaml within the xap to locate the assemblies therein
    3. Load all assemblies within the xap
    4. Download zip files for the “ExtensionParts” within the AppManifest (used for the “cached assemblies” feature)
    5. Load the assembly associated with each zip file

    Why worry about ExtensionParts?  My hope is to use this feature to solve the shared dependency problem.  For example, the System.Windows.Controls.Data.dll file in the SDK (containing the DataGrid control) is a fairly large assembly (446 kb uncompressed).  I’d like to avoid having users download this assembly when the app first loads, so I partition my application into four xaps: Main.xap, Foo.xap, Bar.xap, and Baz.xap.  Foo.xap and Bar.xap both use the DataGrid control.  Since I have no guarantees about the order in which my users will access the application, I need to make sure both of those xaps have access to that assembly, so I partition my application as follows:

    Multiple xaps have a shared dependencyThis is a bit painful, since now when I download both Foo.xap and Bar.xap, I’m forced to download System.Windows.Controls.Data.dll twice!  Instead, if I turn on the assembly caching feature introduced in Silverlight 3, I can get both Foo.xap and Bar.xap to point to the same System.Windows.Controls.Data.dll.  By taking it out of the actual xaps and making it a separate download, I need only download it once (in fact, the browser’s cache will take care of it for me!).  Now, my application is partitioned in this way:

    Xaps with a cached assembly dependency

    And now I’ve effectively partitioned the application without keeping redundant libraries around that would increase the overall download size of the application.

    My implementation allows you to do this (using the same mechanism as “assembly caching”), but has the following limitations:

    • Cached assembly .zip files must contain only one assembly per zip.
    • The name of the .zip file must be the same as the assembly name (replacing “.dll” with “.zip”)

    This loader returns a “Xap” object, which has all of the loaded assemblies related with the xap, a “Manifest”, which contains the same data as the Deployment defined in AppManifest.xaml within the xap, and a means to get the original streams from which each assembly was loaded (for use in keeping local copies, if that’s what you’d like to do).  The XapContentLoader, described below, uses this loader to find and load xaps that would contain additional pages.

    XapContentLoader

    The XapContentLoader is an implementation of INavigationContentLoader that will download an external xap and load a page in one of its assemblies.  This content loader uses a slightly modified version of the pack uri scheme (which I’m probably abusing a bit here, but oh well :)).  Technically, it only takes two lines of code/XAML to use the XapContentLoader:

    First, add the following line to your Application’s startup code (usually in App.xaml.cs), which registers the pack uri scheme with the built-in Uri class, so that you can create pack Uris in code and XAML without having exceptions be thrown:

    PackUriParser.Initialize();

    Then, in XAML:

    <navigation:Frame x:Name="ContentFrame"
                      Source="/Views/Home.xaml">
        <navigation:Frame.ContentLoader>
            <xapLoader:XapContentLoader />
        </navigation:Frame.ContentLoader>
    </navigation:Frame>
    

    And that’s it!  Alright, that’s all.  See you later…

    Ok, ok, I won’t leave you hanging like that!  Let’s look at how you would now use this content loader to load a page in another xap.  First, a quick review of the pack uri scheme as I understand it:

    pack://<authority>/<path>

    There are three parts to this Uri:

    • “pack://” – this is the scheme name of the Uri.  All absolute pack Uris begin with this.
    • “<authority>” – this is actually another Uri (just replace “/” with “,” and escape any other necessary characters).  For the XapContentLoader, this is a path to some xap.  For example, I might use the following authority: “http:,,www.davidpoll.com,xaps,MyApplication.xap”.  This indicates that I’ll be loading a page within the xap at that location.  I also support two other “special” authorities: “application:///” and “siteoforigin://”.  “application:///” cannot have an additional path attached to it, since I translate this as the location of the initial xap from which the application was loaded.  It’s basically equivalent to Application.Current.Host.Source.  “siteoforigin://” is replaced with the directory from which the application’s xap was loaded.  As such, any of the following authorities would be valid:
      • http:,,www.davidpoll.com,xaps,MyApplication.xap
      • https:,,www.davidpoll.com,securexaps,MySecureApplication.xap
      • application:,,,
      • siteoforigin:,,MyApplication.xap (equivalent to the first item in this list if MyApplication.xap was the entry point xap)
    • “<path>” – this is the path within the xap.  Usually, this looks like: “/SomeLibrary;component/Views/Page1.xaml”.  If no assembly name is provided, I assume they are referring to the “EntryPointAssembly” referred to in the AppManifest.xaml file of the xap.

    Some examples of valid Uris to navigate to (all equivalent assuming MyApplication.xap was the initial xap):

    • /Views/Page1.xaml
    • pack://application:,,,/Views/Page1.xaml
    • pack://application:,,,/MyApplication;component/Views/Page1.xaml
    • pack://http:,,www.davidpoll.com,xaps,MyApplication.xap/Views/Page1.xaml
    • pack://http:,,www.davidpoll.com,xaps,MyApplication.xap/MyApplication;component/Views/Page1.xaml
    • pack://siteoforigin:,,MyApplication.xap/Views/Page1.xaml
    • pack://siteoforigin:,,MyApplication.xap/MyApplication;component/Views/Page1.xaml

    Unfortunately, coming up with these Uris can be a bit of a pain, so I’ve provided a custom type of UriMapping that works on a per-xap basis to make this simpler:

    <navigation:Frame.UriMapper>
        <navUtils:UriMapper>
            <xapLoader:PackUriMapping XapLocation="siteoforigin://TernaryXap.xap"
                                      Uri="/remote/{assemblyname}/{path}"
                                      MappedPath="/{path}" />
        </navUtils:UriMapper>
    </navigation:Frame.UriMapper>
    

    Now, I needn’t ever actually write a pack uri myself.  Instead, I can have hyperlinks like “/remote/TernaryXap/Views/Page1.xaml”, and these mappings will generate the appropriate pack uris for you.  They work just like the UriMapping built into the SDK in terms of replacing values in the MappedPath.  “{assemblyname}” is a special token (that you could omit if you set the PackUriMapping.AssemblyName property) that allows you to make the assembly name part of your path.

    Enhancing the experience

    Great, so now we’ve got navigation integrated with on-demand xap loading.  It takes very few lines of code, and is quick to set up.  Note that my xaps have no concrete knowledge of one another (even the hyperlinks are just text, and users could manually enter other hyperlinks).  But web requests are slow, and could fail.  How can we improve the experience around this type of navigation?

    Well, I’ve got two ideas for you that you might recognize: BusyIndicator and ErrorPageLoader.

    Since web requests can fail (lost connectivity, bad links, servers being down, or other random problems), we should make sure users don’t see exceptions under those circumstances.  For this, we’ll whip out the ErrorPageLoader from our trusty utility belt and use it to load a local error page if something goes wrong:

    <loaders:ErrorPageLoader>
        <loaders:ErrorPageLoader.ContentLoader>
            <xapLoader:XapContentLoader />
        </loaders:ErrorPageLoader.ContentLoader>
        <loaders:ErrorPageLoader.ErrorContentLoader>
            <navigationLoader:PageResourceContentLoader />
        </loaders:ErrorPageLoader.ErrorContentLoader>
        <loaders:ErrorPage ErrorPageUri="/Views/ErrorPage.xaml" />
    </loaders:ErrorPageLoader>
    

    You’ll notice that I’ve used the built-in (SDK) PageResourceContentLoader as my ErrorContentLoader.  I did this because, presumably, something bad has happened with the XapContentLoader, so I want to use a ContentLoader with low likelihood of failure in order to display an error page.

    Next, users shouldn’t be left hanging while they wait for a link to load.  We can use the BusyIndicator control in the toolkit in order to let the user know that something is going on.  The XapContentLoader has an “IsBusy” property as well as a “Progress” property.  We can make the BusyIndicator’s progress bar display progress and appear by binding it to these properties on the XapContentLoader.  The following handy XAML accomplishes this:

    <toolkit:BusyIndicator IsBusy="{Binding ContentLoader.ContentLoader.IsBusy, ElementName=ContentFrame}"
                           DisplayAfter="0:0:0.1">
        <toolkit:BusyIndicator.BusyContent>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <TextBlock Text="Loading page..." Margin="0,0,0,4" />
                <ProgressBar Grid.Row="1"
                             Minimum="0"
                             Maximum="1"
                             Height="25"
                             Value="{Binding ContentLoader.ContentLoader.Progress, ElementName=ContentFrame}" />
            </Grid>
        </toolkit:BusyIndicator.BusyContent>
        <toolkit:BusyIndicator.ProgressBarStyle>
            <Style TargetType="ProgressBar">
                <Setter Property="Visibility" Value="Collapsed" />
            </Style>
        </toolkit:BusyIndicator.ProgressBarStyle>
        <navigation:Frame x:Name="ContentFrame"
                          Source="/Views/Home.xaml">
            <navigation:Frame.ContentLoader>
                <loaders:ErrorPageLoader>
                    <loaders:ErrorPageLoader.ContentLoader>
                        <xapLoader:XapContentLoader />
                    </loaders:ErrorPageLoader.ContentLoader>
                    <loaders:ErrorPageLoader.ErrorContentLoader>
                        <navigationLoader:PageResourceContentLoader />
                    </loaders:ErrorPageLoader.ErrorContentLoader>
                    <loaders:ErrorPage ErrorPageUri="/Views/ErrorPage.xaml" />
                </loaders:ErrorPageLoader>
            </navigation:Frame.ContentLoader>
        </navigation:Frame>
    </toolkit:BusyIndicator>
    

    Note that I’ve hidden the BusyIndicator’s default progress bar, and added one to its BusyContent that binds to the XapContentLoader’s progress.  Now, when users navigate to pages and have to wait for them to load, they are presented with the BusyIndicator and a progress bar letting them know how much is left to be downloaded.  The application continues to appear responsive, and users can continue to work with the rest of the application.

    Cross-domain considerations and limiting access

    We’ve now unleashed a lot of power.  Your application can now load pages in any xap that Silverlight can get access to using a WebClient.  If the Frame control you’re using integrates with the browser, users can type any uri into the browser to navigate to, and right now, the XapContentLoader will blindly go and load their code.

    This could be a bit of a security issue (I’m no expert, but this one sticks out like a sore thumb).

    Suppose domain supersecret.com has a cross-domain policy that allows my domain (and only my domain), davidpoll.com, to access services on it.  My domain is using the XapContentLoader, and can load pages in any xap that WebClient can access.  A developer whose domain is evil.com realizes this, and decides to try to get access to supersecret.com’s services.  He’s able to do this by:

    • Adding a cross-domain policy that allows davidpoll.com to access xaps on evil.com
    • Pointing the Silverlight application on davidpoll.com to his xap on evil.com (this will work, since WebClient just checks evil.com’s cross-domain policy)
    • Now that evil.com’s xap has been loaded and is running on davidpoll.com’s application, he can access supersecret.com’s services (since the evil.com’s code is now running on davidpoll.com)!

    Because of this problem, I’ve disabled cross-domain loading on the XapContentLoader by default.  You can re-enable it, but please be aware of this potential problem.  The AuthContentLoader is a convenient way to restrict access to domains you don’t want users to be able to access just by changing the Uri.  Here, I’ve enabled cross-domain access, but restricted access only to my other domain (this one happens to be my personal website that I don’t update too often :)):

    <auth:AuthContentLoader>
        <auth:AuthContentLoader.ContentLoader>
            <xapLoader:XapContentLoader EnableCrossDomain="True" />
        </auth:AuthContentLoader.ContentLoader>
        <auth:NavigationAuthorizer>
            <auth:NavigationAuthRule UriPattern="pack://((siteoforigin:,,)|(authority:,,)|(http:,,open\.depoll\.com)).*">
                <auth:Allow Users="*" />
            </auth:NavigationAuthRule>
            <auth:NavigationAuthRule UriPattern="pack://.+:,,.*">
                <auth:Deny Users="*" />
            </auth:NavigationAuthRule>
        </auth:NavigationAuthorizer>
    </auth:AuthContentLoader>
    

    This allows users to access xaps on my site (open.depoll.com), while denying access to other pack uris.  Coupled with the ErrorContentLoader, a consistent, safe experience can be provided for users.

    MEF and Prism

    At this point, you might be asking yourself why I rolled my own solution to this problem?  MEF and Prism both have very effective implementations for modularization of applications, and you could certainly build very similar ContentLoaders based upon their libraries for loading xaps (in fact, I hope to see folks out there do so! :)).  Really, the reason I rolled my own libraries for this is twofold:

    • Support for cached assemblies – I wanted to make sure to attempt to solve the shared dependency problem described earlier
    • Size – it’s important to keep the size of the bootstrapping assemblies small in order to reap the benefits of dynamic loading.  The total size of the libraries required for the XapContentLoader is about 25k compressed.  I’d still like to pare that down, so if folks have ideas, let me know :)

    If you’ve got ideas for how best to use MEF or Prism with INavigationContentLoader, let me know!  If you’re already using them for modularization and want to integrate them with navigation, this is possible in Silverlight 4 thanks to INavigationContentLoader.

    The goods

    As you know by now if you’ve been following my blog, I never leave you stranded without code and a live sample!  Take a look!

    An application using XapContentLoader

    Click around using the links on top and see what happens to the Uri in the browser’s address bar.  You’ll note the cross-domain access as well as the use of QueryStrings (which still work, of course!).  Open up Fiddler or some other tool to verify that xaps and zip files for cached assemblies are only downloaded once thanks to browser caching.  Enjoy it!

    Finally, some source code for you:

  • Live Sample (source — found in the SLaB v0.3 source under "ScratchApplication")
  • SLaB v0.3 (includes source, a sample app, some tests, and binaries)
    • For the latest version, please check out SLaB on my Downloads and Samples page.
    • The v0.3 download of SLaB includes the following changes:
      • Added more extensible UriMapper that replicates the built-in UriMapper’s behavior but allows UriMappings to be more extensible.
      • Added UiUtilities, the first of which allows you to execute a function on the UI thread and block the calling thread until it has completed (safe to call even from the UI thread)
      • Added XapLoader, which downloads a Xap and any "cached assemblies"
      • Added XapContentLoader, which uses the XapLoader to navigate to pages in downloaded assemblies
      • Added PackUri utilities so that pack Uris can be used to download and navigate to pages in Xaps
      • Signed all assemblies (public binaries use a private key, another key is distributed with source)
      • Added a build task that will generate extmap files for all libraries — now assembly caching works with SLaB assemblies
      • Fixed a bug with the AuthLoader where all rules would be run, even if one rule already allowed access
      • Other minor bugfixes

    Enjoy, and let me know if you have any questions, thoughts, or ideas!

    Remember, SLaB is just a collection of the samples and experimental components I’ve been putting together so that they’re all in one place.  I can’t make any guarantees about maintaining them, fixing bugs, not making breaking changes, etc., but you’re more than welcome to try them out, use them, and let them inspire your development (or show you what not to do if you really dislike something I’m doing!) :).