davidpoll.com
Posts Tagged Dynamic Navigation
On-demand loading of assemblies with Silverlight Navigation – Revisited for Silverlight 4 Beta
Posted by david.poll in Silverlight on February 1, 2010
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):
- Download and extract SLaB
- 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.
- Add a reference to SLaB.Navigation.ContentLoaders.Xap.dll from the extracted Binaries folder.
- Add the following line of code to App.xaml.cs: PackUriParser.Initialize();
- 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>
- Run the application.
- 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”
- 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:
- Download the xap
- Read the AppManifest.xaml within the xap to locate the assemblies therein
- Load all assemblies within the xap
- Download zip files for the “ExtensionParts” within the AppManifest (used for the “cached assemblies” feature)
- 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:
This 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:
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!
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:
- 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!)
.
BusyIndicator, ContentLoader, Dynamic Navigation, Navigation, Silverlight, Silverlight 4 Beta, Silverlight and Beyond (SLaB)
Relative hyperlinks with Silverlight navigation
Posted by david.poll in Silverlight on September 20, 2009
If you haven’t noticed already, I happen to like the Navigation feature in Silverlight quite a bit (I wonder why?
). In my other posts on Navigation, I’ve spent some time exploring how you can navigate to Pages in assemblies other than the main application assembly and how those assemblies can be loaded on-demand (granted, it uses some workarounds, but it gets us where we want to go!).
This is all well and good, but it presents an annoying problem that impacts the maintainability of such code. Specifically, it forces every hyperlink within each of the external assemblies to know how to refer to its assembly by name (this is akin to the problem with absolute URLs in hyperlinks on web pages – those links become tightly coupled to the page for which they were created, and can’t be copied into other projects).
Technically, almost all Uris used by the navigation framework today are relative Uris (unless UriMappings are used to turn absolute ones into relative ones), but they are application-relative and never Page-relative. This means that if you have a page at “/Views/Page1.xaml” and want to link to another page at “/Views/Page2.xaml” from within Page1, you must refer to the entire path (“/Views/Page2.xaml”) rather than just the relative path to the other page (e.g. “Page2.xaml” or “./Page2.xaml”).
In this post, we’ll look at a way to allow Page-relative navigation within your Silverlight Pages. The approach I’ll use will take advantage of the INavigate interface that was added in Silverlight 3 and the HyperlinkButton control that uses this interface to perform navigation when clicked.
The INavigate interface looks like this:
public interface INavigate { // Methods bool Navigate(Uri source); }
It’s a simple interface with a simple purpose: allow a component to provide a way to handle navigation to a Uri. Right now, the only component built into Silverlight that actually takes advantage of it is the HyperlinkButton control. We use this control quite often in Navigation-enabled applications, since it allows us to target a particular Frame control to navigate to a Page by Uri. In the Silverlight Navigation Application project template, you’ll see XAML like this:
<navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}" Source="/Home" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed"> </navigation:Frame>
<HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}" NavigateUri="/About" TargetName="ContentFrame" Content="about"/>
This all works because the Frame control implements INavigate. In other words, there’s no magic there – you can use it too! Here’s the way the HyperlinkButton works when you’re trying to target an INavigate (approximately
):
- For each parent FrameworkElement going up the visual tree from the HyperlinkButton…
- Check to see if the FrameworkElement is an INavigate and that its name matches TargetName (ignored if TargetName is null or empty)
- If so, call INavigate.Navigate() on the FrameworkElement
- Otherwise, recursively search for an INavigate that’s properly named within each of the children of the FrameworkElement
- If no properly named INavigate was found, keep moving up the visual tree
- Check to see if the FrameworkElement is an INavigate and that its name matches TargetName (ignored if TargetName is null or empty)
In other words, the HyperlinkButton will search its way up and down the visual tree (technically doing a pre-order breadth-first search from each parent of the HyperlinkButton, working its way up the visual tree) for an appropriate INavigate to call.
So, what does all this INavigate stuff mean to me?
With that technical detail out of the way, the question that arises is: how can we use this to enable Page-relative navigation? Well, the reason navigation of a Frame works within Pages today is because the Frame control implements INavigate, and the HyperlinkButton works its way up the visual tree until it finds this.
For our purposes, this is great, since it means we can intercept the call to INavigate.Navigate() by implementing the interface somewhere between the HyperlinkButton and the Frame. There’s a convenient place for this, since applications that use Page/Frame and HyperlinkButtons within those pages have a visual tree like this:
- Application
- Layout
- Frame
- Page
- HyperlinkButton
- Other controls
- Page
- Other Controls
- Frame
- Layout
What I’m suggesting is that the Page we navigate to implement INavigate and turn page-relative Uri’s into application-relative Uri’s before handing them off the NavigationService (or the Frame) to actually perform the navigation.
I’ve gone ahead and extended my DynamicNavigation library to make DynamicPage implement INavigate to do what we want, but you could do the same on any subclass of Page (including every one of your Pages if you didn’t want a common base class). Here’s my simple implementation (with a switch to turn off this feature on DynamicPages):
public bool RelativeLinks { get { return (bool)GetValue(RelativeLinksProperty); } set { SetValue(RelativeLinksProperty, value); } } public static readonly DependencyProperty RelativeLinksProperty = DependencyProperty.Register("RelativeLinks", typeof(bool), typeof(DynamicPage), new PropertyMetadata(true)); private static readonly Uri basePlaceHolderUri = new Uri("none:///", UriKind.Absolute); #region INavigate Members public bool Navigate(Uri navigateUri) { string original = navigateUri.OriginalString; if (RelativeLinks && !navigateUri.IsAbsoluteUri && !original.StartsWith("/")) { Uri result; if (NavigationService.CurrentSource.IsAbsoluteUri) { result = new Uri(NavigationService.CurrentSource, navigateUri); } else { Uri baseUri = new Uri(basePlaceHolderUri, NavigationService.CurrentSource); result = new Uri("/" + basePlaceHolderUri.MakeRelativeUri(new Uri(baseUri, navigateUri)).OriginalString, UriKind.Relative); } return NavigationService.Navigate(result); } else { return NavigationService.Navigate(navigateUri); } } #endregion
Now, within the page, you can use Page-relative Uri’s on HyperlinkButtons. All you need to do is avoid setting a TargetName (either through a style or directly on the HyperlinkButton), and the Page will handle the navigation!
Page-relative Uri’s can take a variety of forms. Assuming the Page you’re currently on is “/MyLibrary;component/Views/Main/Page1.xaml”, the following transformations will occur (as an example):
- “Page2.xaml” –> “/MyLibrary;component/Views/Main/Page2.xaml”
- “./Page2.xaml” –> “/MyLibrary;component/Views/Main/Page2.xaml”
- “../Page3.xaml” –> “/MyLibrary;component/Views/Page3.xaml”
- “../Secondary/Page3.xaml” –> “/MyLibrary;component/Views/Secondary/Page3.xaml”
- “../../BasePage.xaml” –> “/MyLibrary;component/BasePage.xaml”
- “SubMain/Page4.xaml” –> “/MyLibrary;component/Views/Main/SubMain/Page4.xaml”
- “SubMain/Page4.xaml?a=b&c=d” –> “/MyLibrary;component/Views/Main/SubMain/Page4.xaml?a=b&c=d”
- “/MyLibrary;component/Views/Main/Page5.xaml” –> “/MyLibrary;component/Views/Main/Page5.xaml” (no change)
Cool! Can I see it in action?
Of course!
As always, you can play around with a running app that does this here:
Click the link at the bottom of that page to peform a relative navigation that should take you on a journey between a number of pages – all of which navigate using relative navigation.
For reference, here is the file structure for the sample application.
So, what’s your point?
Well, to sum it up – being able to do page-relative navigation increases the portability of your Pages. It’s especially useful if you use it in conjunction with UriMapping. With the technique above, the “relative-ness” refers to the user-facing Uri. This means that you can create UriMappings in order to create a “virtual” file structure, and all of your relative links should continue to work (and new ones might be possible!). Give it a shot and let me know what you think! I’m continuing to experiment with Navigation, always on the lookout for things that might improve the experience when working with it.
Enough already! Give me the goods!
Patience! You didn’t really think I’d leave you hanging, did you? Here you go:
- DynamicNavigation libraries (see my other posts for an introduction to what it provides and how to use it – 1, 2)
- Sample Source
Stop talking to yourself!
Okay.
Dynamic Navigation, Navigation, Relative Links, Silverlight, Silverlight 3
On-demand loading of assemblies with Silverlight Navigation
Posted by david.poll in Silverlight on July 20, 2009
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:
- DynamicNavigation libraries (for your consumption)
- Live Sample
- Sample Source
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!
BusyIndicator, Dynamic Navigation, Navigation, Silverlight, Silverlight 3
Silverlight 3 Navigation: Navigating to Pages in referenced assemblies
Posted by david.poll in Silverlight on July 12, 2009
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.
This 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!).
For 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:
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:
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.
BusyIndicator, Dynamic Navigation, Navigation, Silverlight, Silverlight 3
Tags
.NET RIA Services Activity Control Blend BusyIndicator CollectionView ContentLoader Data Binding Dynamic Navigation Fun Konami Code logging Navigation Off-Topic PDC PDC09 Personal Projects Relative Links Server Silverlight Silverlight 3 Silverlight 3 Beta Silverlight 4 Beta Silverlight and Beyond (SLaB) Silverlight Toolkit Validation Visual Studio 2010 WCF RIA ServicesRecent Posts
- On-demand loading of assemblies with Silverlight Navigation – Revisited for Silverlight 4 Beta
- Opening up Silverlight 4 Navigation: Authentication/Authorization in an INavigationContentLoader
- Opening up Silverlight 4 Navigation: Event-based and Error-Handling INavigationContentLoaders
- Opening up Silverlight 4 Navigation: Introduction to INavigationContentLoader
- Silverlight Toolkit November 2009: Activity Control –> BusyIndicator (a.k.a. Update 3: Displaying background activity in a Silverlight RIA application)
Twitter posts
- @JustinAngel Awesome! Enjoy SF! Do you know where you'll be living yet?
Disclaimer
The content on this site represents my own personal opinions and thoughts at the time of posting, and does not reflect those of my employer in any way.Translator














