davidpoll.com
Posts Tagged Navigation
Opening up Silverlight 4 Navigation: Introduction to INavigationContentLoader
Posted by david.poll in Silverlight on November 30, 2009
Quick links to followup posts:
- Event-based and Error-Handling INavigationContentLoaders
- Authentication/Authorization in an INavigationContentLoader
- On-demand loading of assemblies with Silverlight Navigation – Revisited for Silverlight 4 Beta
If you haven’t noticed by now (or been following my previous blog posts), I happen to really enjoy exploring the Navigation feature in Silverlight. A while back, I posted a number of workarounds and tips for some desirable scenarios using the Navigation feature in Silverlight 3. Then… I went silent. And the reason: I’ve been waiting for an extensibility point to be opened up in Silverlight navigation. In the Silverlight 4 beta, that extensibility point has arrived as the INavigationContentLoader.
The ContentLoader extensibility point allows developers to handle the page loading process themselves, much as you would with a GenericHandler in ASP.NET. You’re given some context on what to load (in this case a target Uri), then it’s up to you as the developer to decide how to load it. Your handling of these requests can be as specialized or as generalized as you find appropriate.
On the surface, opening up this extensibility point is a rather small change, but it’s actually very powerful when used to solve general problems. In this post, I’ll build a basic INavigationContentLoader that loads pages based on class name rather than project file structure. In future posts, I hope to explore some more general (and possibly composable) ContentLoaders.
So… Tell me about this INavigationContentLoader interface.
Fundamentally, the INavigationContentLoader interface just provides a cancellable asynchronous pattern for loading content based upon a target Uri. You can set a ContentLoader on the Frame control, which will cause the NavigationService to use your ContentLoader rather than built-in one, which is publicly available as the PageResourceContentLoader.
Here’s what the interface looks like:
public interface INavigationContentLoader { IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState); void CancelLoad(IAsyncResult asyncResult); bool CanLoad(Uri targetUri, Uri currentUri); LoadResult EndLoad(IAsyncResult asyncResult); }
The basic flow of its use with the Frame control and the NavigationService in the Silverlight SDK is as follows:
- Frame/NavigationService receives a request to navigate to a Uri
- Frame/NavigationService uses its UriMapper to map the Uri it was given to a Uri for use by the content loader
- Frame/NavigationService passes the current (post-mapping) Uri to the content loader as well as the target (post-mapping) Uri to the content loader, calling BeginLoad
- Frame/NavigationService waits for a callback from the content loader. If StopLoading() was called, the Frame/NavigationService calls CancelLoad
- Upon being called back, the Frame/NavigationService calls EndLoad() on the content loader, receiving a LoadResult
- If the LoadResult contains a redirect Uri, the Frame/NavigationService begins a new load with that Uri as the target – without adding a history entry for the target Uri
- Otherwise, the Frame/NavigationService attempts to display the fully-initialized UserControl or Page in the LoadResult
Great, I guess… Can you show me how to write one?
Sure! First, let’s choose a type of ContentLoader we’d like to create. For this ContentLoader, we’ll begin to break free of the file structure-driven bonds of the existing ContentLoader provided in Silverlight 3. Instead, we’ll allow navigation to Pages based upon the type name of the Page. For example, if I have a page called “MyNamespace.MyPage”, I should be able to navigate a frame to the relative Uri “MyNamespace.MyPage” or “/MyNamespace.MyPage” rather than having to point to the XAML file for the Page.
There are two parts to writing a ContentLoader: implementing the interface and implementing IAsyncResult to store the results of your asynchronous operation. There is ample documentation for writing an IAsyncResult out there, so I’ll conveniently ignore that for now
.
So, here’s our plan:
- Implement INavigationContentLoader
- Write a helper function that extracts a type name from a Uri
- Implement CanLoad to check to see if the type specified by the targetUri can be found and has a default constructor
- Implement BeginLoad to produce an instance of the page specified by the type in targetUri, store it in an IAsyncResult, and call the consumer’s callback
- Implement EndLoad to wrap the page in a LoadResult and return it to the consumer
- Implement IAsyncResult
- Add a “Result” property to hold the constructed page
- Use the ContentLoader
- Specify the ContentLoader in XAML
- Update Hyperlinks to navigate using our new Uri scheme
Alright, let’s hop to it!
Implementing INavigationContentLoader
Let’s start by implementing the interface:
public class TypenameContentLoader : INavigationContentLoader { }
Ok – easy! Granted, it’s a little empty, but it’s a start! Now, let’s flesh it out!
To make sense of our Uri scheme, we’ll write a method to extract a Type name from a relative Uri:
private string GetTypeNameFromUri(Uri uri) { if (!uri.IsAbsoluteUri) uri = new Uri(new Uri("dummy:///", UriKind.Absolute), uri.OriginalString); return Uri.UnescapeDataString(uri.AbsolutePath.Substring(1)); }
This method is pretty straightforward. First, it turns the relative Uri into an absolute one, using a dummy protocol. Then, it uses the Path of that Uri as the Type name (minus a leading slash and after unescaping any Uri-encoded values (e.g. %20 becomes a space character, so assembly-qualified type names can be used). The reason we don’t just use the OriginalString on the uri is because the Uri may contain a query string or a fragment (e.g. “TypeName?query=string#fragment”) – in this case we only want the Path in the Uri.
Next, we’ll implement CanLoad, which is called by the Frame/NavigationService before attempting to load. Here, we’ll check to see that the type exists and has a default constructor – both of which we’ll need in order to create an instance of the page:
public bool CanLoad(Uri targetUri, Uri currentUri) { string typeName = GetTypeNameFromUri(targetUri); Type t = Type.GetType(typeName, false, true); if (t == null) return false; var defaultConstructor = t.GetConstructor(new Type[0]); if (defaultConstructor == null) return false; return true; }
By implementing CanLoad, we can now safely assume (barring any concurrency-related race condition that could arise, but doesn’t apply for the ContentLoader we’re writing in this post because it operates neither statefully nor asynchronously) that the Frame/ContentLoader will only call BeginLoad after making this check. As such, our BeginLoad can just go ahead and try to create an instance of the type specified in the targetUri. Then, it must store the instance in an IAsyncResult, invoke the userCallback, and wait for EndLoad to be called:
public IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState) { var result = new TypenameContentLoaderAsyncResult(asyncState); Type t = Type.GetType(GetTypeNameFromUri(targetUri), false, true); object instance = Activator.CreateInstance(t); result.Result = instance; userCallback(result); return result; }
Our implementation of EndLoad will extract the instance of the page from the IAsyncResult and wrap it in a LoadResult. LoadResult is a simple class we introduced to represent the result of a load operation. It currently allows for two possible outcomes from a ContentLoader: (1) return/display a Page or UserControl, (2) provide a Uri to which users should be redirected (no history entry for the original page will be created).
public LoadResult EndLoad(IAsyncResult asyncResult) { return new LoadResult(((TypenameContentLoaderAsyncResult)asyncResult).Result); }
The final method of the INavigationContentLoader interface is CancelLoad. In our case, creating an instance of the page happens synchronously, so cancellation doesn’t really have any meaning or value. Other ContentLoaders, however, might use this method to stop a download or abort a large operation:
public void CancelLoad(IAsyncResult asyncResult) { return; }
And that’s it! Our Typename-based content loader is complete! A simple implementation of IAsyncResult will allow us to compile:
internal class TypenameContentLoaderAsyncResult: IAsyncResult { public object Result { get; set; } // Other IAsyncResult members }
Consuming the ContentLoader
Consuming our new ContentLoader is as simple as setting the ContentLoader property on your Frame in XAML:
<navigation:Frame xmlns:loader="clr-namespace:TypenameContentLoader.ContentLoader" x:Name="ContentFrame" Source="/TypenameContentLoader.Views.Home"> <navigation:Frame.ContentLoader> <loader:TypenameContentLoader /> </navigation:Frame.ContentLoader> </navigation:Frame>
You’ll note that in addition to setting the ContentLoader, I’ve set the source for the Frame control to match our new Uri scheme. We must also do the same for other hyperlinks in the application:
<HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}" NavigateUri="/TypenameContentLoader.Views.Home" TargetName="ContentFrame" Content="home"/> <HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}" NavigateUri="/TypenameContentLoader.Views.About, TypenameContentLoader, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" TargetName="ContentFrame" Content="about"/> <HyperlinkButton x:Name="Link3" Style="{StaticResource LinkStyle}" NavigateUri="/TypenameContentLoader.Views.ParameterizedPage?a=100&b=1000" TargetName="ContentFrame" Content="parameterized?a=100&b=1000"/>
And there you have it! The application is fully configured to use the new ContentLoader. You’ll notice that the Frame will happily pass along the complex Uris in all three of the hyperlinks above, and the loader will load them correctly. Query string values still get parsed by the navigation service, and all is well with the world
Ok, so now I can build a ContentLoader – can I actually see the code?
Yep, and I’ll do you one better! You can also try the live sample!
And, just to prove that query strings “just work”, try this link into the application with a long list of key/value pairs that get used by the page:
Feel free to play around with it and let me know what you think!
(Also note the screenshot above using Google Chrome – now a supported browser with Silverlight 4!)
Ok, so all of this is cool, but why is it useful? What’s next?
This Typename-based content loader is a neat trick to try, but its usefulness is still pretty limited. The extensibility point itself, however, is very powerful. Instead of having to come up with hacks and workarounds for things like on-demand downloading of assemblies containing pages as I did before, we can bake that logic right into a content loader! If you are an adherent of the MVVM pattern, you can use your content loader to connect your view to your model. If all you need to do is specify constructor parameters to your pages, you now have that option! If you need to pre-load data from a web service before navigating to a page, a content loader can help!
The ContentLoader extensibility point introduced in the Silverlight 4 beta really opens up Silverlight Navigation, allowing you to interject in the page loading process and enabling you to make navigation work with whatever framework or application structure you choose.
I’ve got a bunch of ideas for useful ContentLoaders that I’ll explore (and hopefully blog about) going forward. If you’ve got ideas, questions, or feedback, please let me know! I look forward to hearing from you!
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: Adding transitions to the Frame control
Posted by david.poll in Silverlight on July 19, 2009
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:
- Leave DynamicPage and DynamicPageShim as-is and live with the slight wonkiness during transitions.
- 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!
Silverlight 3 Navigation: Navigating to Pages in dynamically-loaded assemblies
Posted by david.poll in Silverlight on July 14, 2009
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:
- 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)
- 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!
- 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
Recent Posts
- Pitch Perfect for Android now available
- Tag Master for Android now available
- Pitch Perfect now available for free!
- Quickly building a trial mode for a Windows Phone application
- To XAML, with love (an experiment with XAML Serialization in Silverlight)
- Taking Microsoft Silverlight 4 Applications Beyond the Browser (TechEd WEB313)
- Common Navigation UI and Authorization-driven Sitemaps
- Samples updated and code in comments
Tags
.NET RIA Services Activity Control Android Authorization Barbershop Blend BusyIndicator CollectionView ContentLoader Controls Data Binding Dynamic Navigation Fun Konami Code logging MIX '10 Navigation Off-Topic Out-of-browser PDC PDC09 Personal Pitch Perfect Printing Projects Relative Links Server Silverlight Silverlight 3 Silverlight 3 Beta Silverlight 4 Silverlight 4 Beta Silverlight 4 RC Silverlight and Beyond (SLaB) Silverlight Toolkit Sitemap Tag Master TechEd TechEd North America 2010 Trusted Applications Validation Visual Studio 2010 WCF RIA Services Windows Phone 7 XAMLTwitter: @depoll
- @hectorramos @ParseIt Glad to have you with us!Saturday, 04.28.12 08:12
- Protect Your Parse App By Limiting User Authentication Methods: http://t.co/yS7xTBysTuesday, 04.24.12 21:02
- @andruwang Awesome stuff!Tuesday, 04.24.12 00:47
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.

