Archive for July, 2009

On-demand loading of assemblies with Silverlight Navigation

As those of you who’ve been reading my blog may know, I’ve been spending a bit of time with some enhancements to navigation in Silverlight surrounding the use of dynamically-loaded assemblies.  I’ve still got a bunch of things I’d like to try to implement, but in the meantime I thought I’d share what I’ve got so far.

Now that I have a mechanism for navigating to Pages in dynamically-loaded assemblies in Silverlight, the question arises: how can I improve the user and developer experience around partitioning applications in this way?

In particular, this is the flow I’d like to be able to create:

  • Developer knows the set of Pages his user will be able to navigate to, and partitions them into assemblies that he will load at runtime
  • Furthermore, the developer knows the dependencies those assemblies have on other dynamically-loaded assemblies (e.g. multiple assemblies contain Pages that use DataGrid, but System.Windows.Controls.Data should be shared/downloaded when the first of those assemblies is downloaded)
  • The user is presented with some sort of navigation UI (e.g. HyperlinkButtons, buttons that call Frame.Navigate(), etc.)
  • When the user requests a page in an assembly that has not yet been downloaded, it should be automatically downloaded, and navigation with the Frame should only complete once the Page can be loaded.

With this on-demand loading behavior, deep-linking into applications with dynamically-loaded assemblies can be re-enabled (you’ll notice if you try to deep-link into my sample from my previous post about dynamically-loaded assemblies, you get an exception, since the assembly hasn’t been loaded yet).

I’m developing some utilities that will make this flow easier to accomplish.  Please note that at this point all of the API, etc. is subject to change, and I’m definitely not making any assurances around bugs, quality, or anything of the sort, but I thought I’d share what I’ve been working on and start getting some feedback from you folks!

Anyhoo, let’s take this step by step:

Dividing an application into multiple assemblies

This is fairly straightforward, and something I’m sure most of you have been doing for a long time.  For our purposes, there are a number of things to consider:

  • Pages in these assemblies that will be dynamically loaded should use the DynamicPage and DynamicPageShim (or some other workaround you may have come up with) described in my earlier post
  • Any dynamically-loaded assemblies need to be in a place accessibly using the WebRequest APIs in Silverlight.  I usually put them in my ClientBin folder, and I used a post-build task to copy any dlls for those assemblies into the correct folder (feel free to see my Sample project for an example of this)
  • The libraries I’ve built support loading DLLs as well as XAP and ZIP files with dlls in them. Just using DLLs is probably the easiest way to go, but using ZIP or XAP files will keep the transfer time/size small.
  • Remember to take careful note of any dependencies between the libraries.  You’ll need to make sure they’re all loaded into your application before attempting to use the assemblies.

One thing I might do in the future is (attempt to) make a project template that will create a XAP class library that places the XAP in the ClientBin folder for you.  I’m still experimenting with how to do this, but it’s still worth noting that using XAPs can be problematic if you’re sharing libraries (VS will automatically package shared assemblies into your XAP, so you might end up with copies of System.Windows.Controls.Navigation.dll in 3 or 4 XAPs, and since they’re all packaged up with the rest of the assemblies, you’ll end up downloading the same DLL multiple times.

Describing how to load assemblies dynamically

I’ve created a little utility that I call “DynamicLoader,” which allows you to declare, in XAML, where your dynamic DLLs can be downloaded from and their interdependencies.  In my App.xaml, I specify the various libraries that may be loaded dynamically (incidentally, some of these libraries are also in my XAP, and the loader will use the ones built into the XAP rather than re-downloading them automatically).  I also describe the various interdependencies between my libraries.  Some are unnecessary (because the dependencies are already in the XAP), but I chose to be explicit for some of the more complex ones to remove all doubt.  An example (from my sample project) can be seen below.

<load:DynamicLoader x:Key="loader">
    <load:AssemblyDescription AssemblyName="DynamicallyLoadedLibrary"
                              Location="./DynamicallyLoadedLibrary.dll" />
    <load:AssemblyDescription AssemblyName="DynamicallyLoadedLibraryVB"
                              Location="./DynamicallyLoadedLibraryVB.dll" />
    <load:AssemblyDescription AssemblyName="LargeDynamicallyLoadedLibrary"
                              Location="./LargeDynamicallyLoadedLibrary.dll">
        <load:Dependency AssemblyName="System.Windows.Controls" />
        <load:Dependency AssemblyName="System.Windows.Controls.Data" />
        <load:Dependency AssemblyName="System.Windows.Controls.Data.DataForm.Toolkit" />
        <load:Dependency AssemblyName="System.Windows.Controls.Data.Input" />
        <load:Dependency AssemblyName="System.Windows.Controls.DataVisualization.Toolkit" />
        <load:Dependency AssemblyName="System.Windows.Controls.Navigation" />
        <load:Dependency AssemblyName="System.Windows.Data" />
        <load:Dependency AssemblyName="System.ComponentModel.DataAnnotations" />
    </load:AssemblyDescription>
    <load:AssemblyDescription AssemblyName="System.Windows.Controls"
                              Location="./System.Windows.Controls.dll" />
    <load:AssemblyDescription AssemblyName="System.Windows.Controls.Data"
                              Location="./System.Windows.Controls.Data.dll">
        <load:Dependency AssemblyName="System.ComponentModel.DataAnnotations" />
        <load:Dependency AssemblyName="System.Windows.Controls.Data.Input" />
        <load:Dependency AssemblyName="System.Windows.Data" />
    </load:AssemblyDescription>
    <load:AssemblyDescription AssemblyName="System.Windows.Controls.Data.DataForm.Toolkit"
                              Location="./System.Windows.Controls.Data.DataForm.Toolkit.dll">
        <load:Dependency AssemblyName="System.ComponentModel.DataAnnotations" />
        <load:Dependency AssemblyName="System.Windows.Data" />
    </load:AssemblyDescription>
    <load:AssemblyDescription AssemblyName="System.Windows.Controls.Data.Input"
                              Location="./System.Windows.Controls.Data.Input.dll">
        <load:Dependency AssemblyName="System.ComponentModel.DataAnnotations" />
    </load:AssemblyDescription>
    <load:AssemblyDescription AssemblyName="System.Windows.Controls.DataVisualization.Toolkit"
                              Location="./System.Windows.Controls.DataVisualization.Toolkit.dll" />
    <load:AssemblyDescription AssemblyName="System.Windows.Controls.Navigation"
                              Location="./System.Windows.Controls.Navigation.dll" />
    <load:AssemblyDescription AssemblyName="System.Windows.Data"
                              Location="./System.Windows.Data.dll" />
    <load:AssemblyDescription AssemblyName="System.ComponentModel.DataAnnotations"
                              Location="System.ComponentModel.DataAnnotations.dll" />
</load:DynamicLoader>

The Location specified in each AssemblyDescription is a URI.  In this case, all of my dlls are in my ClientBin directory, so they all begin with “./”, but these could be any URI that can be reached by the Silverlight application.  Furthermore, if you wish to use the new ClientHttp networking stack to do the downloading, you can choose to do so (as part of the AssemblyDescription).

The loader will asynchronously load any requested library (by name), and will only fire Loaded events once all of each assembly’s dependencies have been loaded.  This allows us to know when it’s safe to try to navigate to a Page in a dynamically-loaded assembly.

Creating Navigation UI

Nothing too special to share here.  HyperlinkButtons use the exact same URI scheme as before (for navigating to pages in referenced/dynamically-loaded assemblies).  Here’s what my XAML for my navigation bar looks like:

<Border x:Name="LinksBorder" Style="{StaticResource LinksBorderStyle}">
    <StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">

        <HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}"
                     NavigateUri="/Home" TargetName="ContentFrame" Content="home"/>

        <Rectangle x:Name="Divider1" Style="{StaticResource DividerStyle}"/>

        <HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}"
                     NavigateUri="/About" TargetName="ContentFrame" Content="about"/>

        <Rectangle x:Name="Divider2" Style="{StaticResource DividerStyle}"/>

        <HyperlinkButton x:Name="csharp" Style="{StaticResource LinkStyle}" IsEnabled="True"
                     NavigateUri="/DynamicallyLoadedLibrary;component/CSDynamicPage.dyn.xaml" TargetName="ContentFrame" Content="C# Class Library"/>

        <Rectangle x:Name="Divider3" Style="{StaticResource DividerStyle}"/>

        <HyperlinkButton x:Name="vb" Style="{StaticResource LinkStyle}" IsEnabled="True"
                     NavigateUri="/DynamicallyLoadedLibraryVB;component/VBDynamicPage.dyn.xaml" TargetName="ContentFrame" Content="VB Class Library"/>

        <Rectangle x:Name="Divider4" Style="{StaticResource DividerStyle}"/>

        <HyperlinkButton x:Name="large" Style="{StaticResource LinkStyle}" IsEnabled="True"
                     NavigateUri="/LargeDynamicallyLoadedLibrary;component/LargeDynamicPage.dyn.xaml" TargetName="ContentFrame" Content="Large Class Library"/>
    </StackPanel>
</Border>

Again, nothing too scary here – the XAML remains identical to its form without the dynamically-loaded libraries.

Adding on-demand navigation

The other important piece of this puzzle is a Frame control that uses the loader to ensure that dynamically-loaded libraries are loaded into the AppDomain before attempting to navigate to pages within those libraries.  I’ve provided a derived Frame class (DynamicNavigation.Utilities.Controls.Frame) that does precisely this.  As with my DynamicPage class, you should expect a few quirks, since the Frame class from which it derives doesn’t have any virtual methods.  Don’t cast my Frame to a System.Windows.Controls.Frame if you don’t want to get a bunch of extra events for Loading, Loaded, etc.  Also, since I couldn’t replace the NavigationService, if you subscribe to events on that service, you’ll see a large number of extra events being raised.  Neither of these eccentricities should hamper functionality, but you may see some unexpected activity if you watch those events!

My Frame class takes an DynamicLoader and delegates all loading of dynamic libraries to it.  Here’s what my XAML declaration of the Frame looks like (plus or minus some extraneous attributes):

<dnav:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}"
            DynamicLoader="{StaticResource loader}"
            Source="/Home">
    <dnav:Frame.UriMapper>
        <uriMapper:UriMapper>
            <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
            <uriMapper:UriMapping Uri="/{a};component/{p}" MappedUri="/{a};component/{p}" />
            <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
        </uriMapper:UriMapper>
    </dnav:Frame.UriMapper>
</dnav:Frame>

And that’s it!  With my custom Frame class, it take *zero* code to get dynamic loading up and running – only XAML is necessary.  Attach an Activity control to the loader, and you’re hot to trot!

In Conclusion

Well, there you have it!  I’d like to remind folks that none of the APIs here are intended to be concrete, and I make no guarantees of quality – I’m just trying to demonstrate how it can be done, and if the interest is there, I’ll keep investing some time in exploring this.  I’ve got a bunch of ideas for where I can go from here, things I’d like to change/improve, and I look forward to playing some more with these prototypes.

Without further ado, here are the links I’m sure you’re all waiting for:

What’s next?

Well, I’ve got a lot of ideas, and I’d love to hear some from you all.  Here are some of mine (not making any promises – I’m just experimenting with these):

  • Cache to IsoStore – downloaded libraries could be stored in Isolated Storage and loaded from there if they’re already on the machine
  • Install – When the application is taken out of browser, automatically download the assemblies to Isolated Storage and load from there, allowing the entire application to be run offline
  • URI scheme/custom loading – I’d love to be able to just specify the whole deal in a URI to a page, such as “pack://http:,,www.davidpoll.com,Samples,ClientBin,MyLibrary.dll;component/Page2.dyn.xaml” and not need the big manifest with assembly name/location mappings and dependencies.
  • Dependencies for particular URIs – allows the Frame control to pre-load assemblies before a particular page is loaded, even if the page is a local one (thanks, Austin, for this idea!)

Anyway, I’ve got a thousand other ideas racing through my mind right now, but those are just a few.  What do you think?  Is there anything you dislike about my approach or anything you particularly like?  Speak up!

, , , ,

49 Comments

Silverlight 3 Navigation: Adding transitions to the Frame control

Continuing with my recent theme of enhancing the built-in support for Navigation in Silverlight 3, I thought I’d use this post to look briefly at enhancing user experience during navigation.  On the surface, the Frame control is pretty unexciting from a UX perspective – its job is really just to display pages as a result of requests to navigate (either through the browser’s address bar, responding to HyperlinkButton clicks, or direct calls to Frame.Navigate()).  It has barely any UI of its own, and can usually be thought of as an enhanced ContentControl (incidentally, it is one!).

Most of the time, all the Frame is doing is displaying a Page, and this (in my opinion at least) is an appropriate presentation – the Frame shouldn’t get in the way of displaying my Pages.  Where I do want the Frame to intervene now and then is during page changes, allowing me to provide rich transitions when navigating from Page to Page.  The Frame control provided in the Silverlight 3 SDK doesn’t do anything for us as far as transitions go out of the box, but with a little templating magic and the Silverlight Toolkit’s TransitioningContentControl (which Jesse Liberty has a great blog post on), I think we can get the desired effect!

Let’s begin by taking a peek at the ControlTemplate for the Frame control:

<ControlTemplate TargetType="navigation:Frame">
    <Border HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
            Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}">
        <ContentPresenter Cursor="{TemplateBinding Cursor}"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          Margin="{TemplateBinding Padding}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          Content="{TemplateBinding Content}"/>
    </Border>
</ControlTemplate>

As you can see, there’s very little to it: a Border and a ContentPresenter – with all the appropriate TemplateBindings.

All we have to do to get transitions on the Frame control is replace that ContentPresenter with the TransitioningContentControl:

<ControlTemplate x:Key="TransitioningFrame" TargetType="navigation:Frame">
    <Border Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}"
            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
        <toolkit:TransitioningContentControl Content="{TemplateBinding Content}"
                                             Cursor="{TemplateBinding Cursor}"
                                             Margin="{TemplateBinding Padding}"
                                             HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                             VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                             HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                             VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                                             Transition="<Transition Name>" />
    </Border>
</ControlTemplate>

The “toolkit:” xml namespace uses the following definition (since you can find the TransitioningContentControl in the System.Windows.Controls namespace and the System.Windows.Controls.Layout.Toolkit assembly): xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"

To change the type of transition the Frame will use, just change the value of the Transition property on the TransitioningContentControl.

There’s not much more to it!  Short, sweet, and to the point :) .

Check out the live sample and source if you’re curious:

 

Caveats and Questions

I know you’d be disappointed if I really left it at that, so here’s the one caveat I’ve observed with this technique:

My dynamically-loaded libraries with navigation workaround will cause a few problems with this technique, since it sets the Frame’s Content property twice (once to load the DynamicPageShim, the other to load the DynamicPage itself).  The result is that you will see the Frame transition to a blank page and then to the DynamicPage with your content.  So here’s the question: how important is this transitioning behavior to you?  There are two options for how I proceed here, neither of which are truly ideal:

  1. Leave DynamicPage and DynamicPageShim as-is and live with the slight wonkiness during transitions.
  2. Make DynamicPageShim avoid changing the content of the Frame twice (making transitions work just fine :) ).  This will mean that you won’t be able to use the DynamicPageexactly as you would the standard Page (e.g. binding to "Frame.Content.MyCustomPropertyOnMyPage” won’t be possible… instead you’d have to bind to “Frame.Content.Content.MyCustomPropertyOnMyPage”).

Neither of these options significantly hampers functionality – just impacts either user experience or developer experience, but I’d love to hear your thoughts!  Do you prefer option 1 or option 2?

In the meantime, I’m working on some fun little utilities that will make dynamically loading assemblies with navigation much simpler and more declarative, and am looking forward to blogging it when it’s ready!

 

Update: Credit where credit is due

About 10 minutes after I posted this, I came across someone (Koen Zwikstra) who posted almost the exact same thing before me, and I want to make sure he gets fair mention for getting there before me :)

You can find his post here: http://firstfloorsoftware.com/blog/animated-page-navigation-in-sl3/

Sorry for duplicating!  Great stuff!

, , ,

10 Comments

Silverlight 3 Navigation: Navigating to Pages in dynamically-loaded assemblies

In my last post on the new navigation feature in Silverlight, I explored how you can navigate to pages in assemblies/projects referenced by your main application.  Almost immediately, a number of you asked how you can navigate to pages in assemblies that have been dynamically loaded, allowing you to delay downloading certain pieces of your application until users request them.  This allows you to reduce the initial size (and thereby load/download time) of your application to something more appropriate for your users and avoid using bandwidth to download components to users’ machines that they may never actually user/encounter.

Out of the box, Silverlight 3’s navigation feature only allows navigating to Pages in assemblies referenced by your application project and packaged in your XAP.  There are a number of technical reasons behind this that I know we’d like to explore and hopefully address in future versions, but I won’t go into the details here.  There is, however, one exception to this rule that prevents us from navigating to Pages in dynamically-loaded assemblies: you can load Pages with no code behind that live in such assemblies.

After a few months of thinking about this problem in the back of my mind, it finally clicked for me: this exception is the way in!  All of the other workarounds I was able to think of required Pages located in the XAP that would load their contents dynamically and didn’t really take advantage of the Navigation feature at all.

Anyway, I think I finally found a reasonably good workaround, and while it’s a little hacky-er than I would’ve liked, it doesn’t fundamentally change the feel of using Silverlight navigation.  Here’s the gist of my strategy:

  • Load an assembly containing a Page dynamically
  • Include in this assembly a “shim” Page with no code behind.  In its XAML, reference the real page with code behind, and forward any navigation-related information (events, title, query strings, etc.) to that Page
  • When that page is navigated to, replace the Frame’s content with the real page.
  • From the application, navigate to the “shim” page in the dynamically-loaded assembly

Ok, I know that sounds a little roundabout, but I think I’ve made it pretty easy to accomplish for a developer now.  More importantly – it works!

Let me go into a little more detail…

The Library

I’ve created a tiny little assembly that I’ve called “DynamicNavigation”.  It contains two classes, both of which are made for use in XAML:

  • DynamicPage: A descendant of the Page class that allows the Shim to communicate with it.  If I did my job correctly, for 99% of cases, you can navigate directly to this page (rather than its Shim) if you haven’t dynamically loaded the assembly.  There shouldn’t really be any new public interface (except for some “new” properties that hide the original Page properties, since they aren’t virtual).
  • DynamicPageShim:  Another descendant of the Page class, meant to be used in XAML with no code behind.  This class will forward any navigation events, etc., to the DynamicPage it takes as its content.  The goal here was to minimize the XAML so that the additional size due to these files is small.  There may be further optimizations I can do, but it’s getting pretty close :)

The Developer Experience

Ok, that’s all great, but what do I have to do to use it?

Well, instead of 2 files (<PageName>.xaml and <PageName>.xaml.cs/vb), creating a Page now takes 3 files:

  • <PageName>.dyn.xaml:
<dyn:DynamicPageShim xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:dyn="clr-namespace:DynamicNavigation;assembly=DynamicNavigation"
           xmlns:my="clr-namespace:DynamicallyLoadedLibrary;assembly=DynamicallyLoadedLibrary">
    <my:PageName />
</dyn:DynamicPageShim>

I’ve underlined two important lines here.  First, “assembly=DynamicallyLoadedLibrary” – normally, this would be unnecessary in an xmlns definition, since I can refer to the library in which the XAML file exists without the “assembly=” syntax.  For the same technical reasons that we normally can’t load a Page in a dynamically-loaded assembly, this name needs to be fully specified, since it allows the XAML loader to find the dynamically-loaded assembly in which your DynamicPage resides.  Next, you can see that this Shim takes an instance of the DynamicPage as its content.  This allows it to forward navigation-related information to the Page and ensure that the Frame has the correct content.

  • <PageName>.xaml
<dyn:DynamicPage x:Class="DynamicallyLoadedLibrary.CSDynamicPage"
           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:dyn="clr-namespace:DynamicNavigation;assembly=DynamicNavigation"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           mc:Ignorable="d"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Page Title">
    <Grid x:Name="LayoutRoot">

       ...

    </Grid>
</dyn:DynamicPage>

As you can see, there’s really nothing special about the DynamicPage except that the open/close tags are of type DynamicPage rather than Page.  Gotta love it!

  • <PageName>.xaml.cs/vb

I won’t show an example here, but there’s really nothing special about this.  You’ll develop exactly as though the DynamicPage were a real Page.  The only thing to watch out for: please don’t cast the DynamicPage to a Page, since this will cause it to refer to hidden properties that may not be set.  Again, for 99% of cases, this is probably not an issue, but it bears a little bit of consideration.

The last piece of the puzzle is actually navigating to the page.  Well, it’s pretty straightforward: navigate just as we did in my other post (using “;component” pack URI syntax).  The only difference: instead of navigating to <PageName>.xaml, you’ll navigate to <PageName>.dyn.xaml.

And that’s it!  The rest should just work!

So, without further ado, I’ve got some tools for you!

The Goods

The download above is a zip containing 3 things:

  1. DynamicNavigation.dll – an assembly you should reference in both your application project (and include in your xap) as well as any assemblies you wish to dynamically load (so that you can include the XAML files above)
  2. DynamicPageCS.zip – this is a Visual Studio item template that will help get you started.  Drop this zip (without extracting) in “<My Documents>\Visual Studio 2008\Templates\Item Templates\Visual C#”.  Now, if you open Visual Studio and a C# Silverlight 3 project, right-click the project (in the solution explorer) and choose “Add new…”.  Select “Silverlight Dynamic Page” and choose a name for your page.  The item template will create the 3 files for you.  Open up “<PageName>.xaml” and start editing!
  3. DynamicPageVB.zip – I didn’t forget about you VB guys!  Follow the same instructions above (but placing the item template in the VB folder instead of the C# one), and you should be set to go!

I’m sure there are some bugs and issues with what I did (for example, the item templates don’t add a reference to DynamicNavigation.dll to your project yet… I hope to fix this once I figure out how!).  Let me know if something’s causing you problems, and I’ll see if I can work it out in my (not so) copious free time :)

The Sample

You know me – I can’t leave you without a live sample of this thing in action!  Take a look here (for your viewing pleasure):

Enjoy!  You may even find a cameo from a previous post in there!

The Tips

When using my DynamicNavigation tools, there are a few things you should keep in mind.  Hopefully this list will get smaller going forward, but in the meantime, these are some things to remember:

  • It’s still up to you to load the assemblies dynamically into your AppDomain before attempting to navigate to them.  A super-simple example of how to do this can be found in the code-behind of my MainPage.xaml.  You can also use tools like Prism to accomplish something similar.  There are definitely some tricks that would make this feel more on-demand than what I’ve done in the sample, but that’s a topic for a future post! :)
  • Along those lines, please make sure any assemblies your dynamically-loaded assembly is dependent upon are loaded before trying to navigate.  I don’t do anything to try to resolve those dependencies.
  • Try to avoid casting your DynamicPage to its parent type – Page.  If you do, you’ll find some properties aren’t set to your desired values (such as Title, NavigationCacheMode, etc.).
  • My libraries should replace Frame’s Content with the intended page, so feel free to bind into Frame.Content just as you would otherwise.  You may find that Frame.Content does change twice during a navigation rather than just once, but otherwise, you should get the same events/virtual methods called/etc. on your Page.
  • Expect Caching and Title to still be honored properly on your page!
  • Once you’ve created your <PageName>.dyn.xaml file, you should rarely, if ever, need to modify it.  It’s just a shim, and any other work you’d like to do should be possible directly through the DynamicPage files (.xaml and .xaml.cs/vb)

I tried to keep the library as small as possible.  Anything I build on top of this, I intend to put in a separate library, so that you’re not forced to take additional overhead for the simplest of cases, where you’ve already done your dynamic loading and just want to navigate to pages in those libraries.

The Conclusion

My hope is that this will get you started down the road to navigating to dynamically-loaded assemblies.  I know it’s a bit obtuse, and still harder to do than it ought to be, but what I’d like to do going forward is take this development and create an SL3 library that will make it really simple to download assemblies from your server on-demand during navigation (and perhaps devise some other nifty features).

Please, let me know what you think.  Should I spend more time on these things?  How valuable is using navigation in this way to you?  What kinds of scenarios would you still like to see enabled?

If I’ve confused the heck out of you, I sincerely apologize.  I know I found myself struggling to describe this adequately, so please, ask questions!  I’m happy to share my thoughts/experiences.

Comment away!

P.S. I’m finally on Twitter (at least partially to my dismay :) ).  You can find me at @depoll

 

Update: Julian Biddle has posted a wholly different strategy that would allow you to divide your Silverlight application across multiple XAPs on his blog: http://anoriginalidea.wordpress.com/2009/07/22/how-to-build-huge-dynamic-cross-platform-silverlight-business-applications/.  Take a look – it’s an interesting read/approach :)

, , ,

38 Comments

Downtime – Apologies…

Hey folks!  For those of you who were trying to access my blog in the last 3 or 4 hours (or more, I’m not 100% sure when it started), you were probably not met with much success.  Unfortunately, my server’s ISP had been hit with a DDoS attack, bringing down my server’s internet access.  I just finished working with my service provider to get things up and running again.  In the meantime, my sincere apologies!  I hope it didn’t leave folks in the dark for too long!

,

No Comments

Silverlight 3 Navigation: Navigating to Pages in referenced assemblies

At long last, Silverlight 3 has arrived!  That, in and of itself, is worth a thousand blog posts, but since there’s a plethora of folks out there doing precisely that as I type, I’ll start right out with some content on one of the new features of Silverlight 3 – Navigation.

In this post, I’ll look at some basic navigation functionality in Silverlight 3.  Silverlight 3 navigation is based on navigating a Frame control to a particular Page control.  On top of allowing non-linear navigation throughout your Silverlight application, the Frame control will integrate with your browser’s history and address bar, allowing you to provide deep-links to Pages within your application and provide a more web-like experience within Silverlight applications.

Using Pages and Navigation in this way allows you to structure your application much like you would a web page, with various pages providing differing functionality.  Like web pages, Silverlight 3 navigation allows you to pass data through query strings, perform fragment navigation, and so on – great topics for another post :)

Basic navigation to pages in your main (application) project is simple – HyperlinkButtons can target a Frame, and specify the path to the Page’s XAML file, like so:

<navigation:Frame x:Name="ContentFrame" Source="/Views/Home.xaml">
</navigation:Frame>
<StackPanel>
    <HyperlinkButton NavigateUri="/Views/Home.xaml" TargetName="ContentFrame" Content="home"/>
    <HyperlinkButton NavigateUri="/Views/About.xaml" TargetName="ContentFrame" Content="about"/>
</StackPanel>

In this case, my Pages are “Home” and “About”, located in a Views folder within my Silverlight Application project.  Clicking on the links results in changes to the address bar in my web browser, as you can see in the image below.  The path in the hyperlink is displayed after the hash mark (#) in the URL.  I could send someone this link to bring them right back to the specified page in my application.

Address bar after navigatingThis navigation functionality is very valuable in and of itself, but what happens if I want to put my pages in a separate assembly, ripe for reuse in other applications?  You’ll notice that the URIs for the Pages were relative to the application project (i.e. “/Views/Home.xaml” represents “<ApplicationProject>/Views/Home.xaml”).  This actually comes from the short form of the pack URI syntax in WPF (note: the full syntax is not supported in Silverlight, just a narrow subset).  If you want to access Pages in referenced assemblies, you can do so using the same “short” syntax: “/<ReferencedAssemblyName>;component/<PathToPage>/<PageName>.xaml”

With this syntax, I can place (and reference) pages in a class library that will be referenced by my Silverlight application, allowing me to create a structure like the one in the image below (a simplified example, I know, but it does illustrate the point!).

Solution structure showing /Pages/PageInLibrary.xaml in a class library called PageClassLibraryFor this project structure, my hyperlinks look like this:

<navigation:Frame x:Name="ContentFrame" Source="/Views/Home.xaml">
</navigation:Frame>
<StackPanel x:Name="LinksStackPanel">
    <HyperlinkButton NavigateUri="/Views/Home.xaml" TargetName="ContentFrame" Content="home"/>
    <HyperlinkButton NavigateUri="/Views/About.xaml" TargetName="ContentFrame" Content="about"/>
    <HyperlinkButton NavigateUri="/PageClassLibrary;component/Pages/PageInLibrary.xaml" TargetName="ContentFrame" Content="page in a class library"/>
</StackPanel>

Upon running and clicking on the “page in a class library” link, you’ll notice that the address bar shows a rather long and ugly URI:

http://www.davidpoll.com/Samples/MultiAssemblyNavigation/TestPage.html#/PageClassLibrary;component/Pages/PageInLibrary.xaml

Thankfully, we’ve supplied a great feature for the Frame control that helps you deal with ungainly URIs – the UriMapper.  UriMappers allow you to write code that takes a URI as input and produces a different URI as output.  The output URI will be used to locate the page, while the input URI is what the user will see.  In the SDK, we’ve supplied a default UriMapper that allows you to use some basic pattern matching to map URIs and keep your deep-links nice and tidy.

In my case, I’d be quite happy if I could get rid of the “/PageClassLibrary;component" that I had to add to my URI to reference Pages in a class library altogether.  Instead, I’d like my URI to look like this: “/Pages/PageInLibrary.xaml”.  To accomplish this, I add a UriMapper to my Frame:

<navigation:Frame Source="/Views/Home.xaml">
    <navigation:Frame.UriMapper>
        <uriMapper:UriMapper>
            <uriMapper:UriMapping Uri="/Pages/{path}" MappedUri="/PageClassLibrary;component/Pages/{path}" />
        </uriMapper:UriMapper>
    </navigation:Frame.UriMapper>
</navigation:Frame>
<StackPanel>
    <HyperlinkButton NavigateUri="/Views/Home.xaml" TargetName="ContentFrame" Content="home"/>
    <HyperlinkButton NavigateUri="/Views/About.xaml" TargetName="ContentFrame" Content="about"/>
    <HyperlinkButton NavigateUri="/PageClassLibrary;component/Pages/PageInLibrary.xaml" TargetName="ContentFrame" Content="page in a class library"/>
    <HyperlinkButton NavigateUri="/Pages/PageInLibrary.xaml" TargetName="ContentFrame" Content="(mapped URI) page in a class library"/>
</StackPanel>

Now, users who navigate to the page are greeted with this, much “prettier” URL:

http://www.davidpoll.com/Samples/MultiAssemblyNavigation/TestPage.html#/Pages/PageInLibrary.xaml

And there you have it!  Dividing your pages across multiple assemblies doesn’t have to degrade user experience, and once you’re familiar with the style of URI that the navigation framework expects for such pages, it’s no more complex than standard navigation within your Silverlight application.

One last thought…

Before I leave you, I think it’s important to point something out: the Silverlight 3 SDK ships with a project template for Navigation for Visual Studio.  This template makes it really easy to get started with a styleable, Navigation-enabled Silverlight application, and does quite a lot for you, including specifying some default UriMappings:

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

This is great – it makes the common case of having Pages within your “Views” folder in your application project really clean, allowing developers to reference “/Home” instead of “/Views/Home.xaml”.  However, if you look closely at the UriMappings, you’ll notice that “/{pageName}” will match our “/<AssemblyName>;component” syntax, mapping it to something else entirely, and preventing any attempts to link directly to such URIs.

There are a number of ways to address this issue, depending on your desired URI scheme, such as:

  • Delete the UriMappings entirely and go back to the full paths for all of the hyperlinks
  • Modify the existing UriMappings so that the “catch-all” doesn’t match the desired syntax
  • Add UriMappings for each referenced library before the catch-all mapping, like so:
<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="/Pages/{path}" MappedUri="/PageClassLibrary;component/Pages/{path}" />
        <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
      </uriMapper:UriMapper>
    </navigation:Frame.UriMapper>
</navigation:Frame>

  • Add a UriMapping to restore the original syntax before the catch-all mapping, like so:
<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="/{assemblyName};component/{path}" MappedUri="/{assemblyName};component/{path}" />
        <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
      </uriMapper:UriMapper>
    </navigation:Frame.UriMapper>
</navigation:Frame>

This list is certainly not exhaustive, but some combination of these options is likely to help you re-enable navigation to Pages in referenced assemblies.

If you’re still having trouble getting this to work, let me know, and I’ll try to help you troubleshoot!

Last, but not least…

You thought I might leave you without source and a link to the sample, didn’t you?!  Well, guess I showed you!  Oh, wait, I haven’t linked them yet.  Uhhh… pretend I didn’t say that :)

More posts will come now that Silverlight 3 is out!  I’ve been waiting with bated breath!  Thankfully, you folks aren’t around to suggest I use a mint :)

P.S.  Now that Silverlight 3 is out, I’ve updated all of my samples/source to work with Silverlight 3, the July 2009 Silverlight Toolkit, and .NET RIA Services July 2009 CTP.  You’ll find my Konami Code control and Activity control should both work out-of-the-box with Silverlight 3 RTM, and the rest only needed minor updates.  If folks are curious about my experiences updating those projects, let me know and I’ll do a short post.

, , , ,

24 Comments