Posts Tagged Navigation

Common Navigation UI and Authorization-driven Sitemaps

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

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

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

A TreeView Sitemap.

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

A BreadCrumb sitemap.

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

How does this type of UI work?

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

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

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

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

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

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

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

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

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

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

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

And for the BreadCrumbNavigator:

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

What can I customize?

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

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

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

So, can I see it in action?

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

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

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

User: Test

Password: _Testing

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

Authorization-driven navigation controls 

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

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

Cool… but where are the bits?

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

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

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

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

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

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

  • , , , , , , ,

    39 Comments

    A “refreshing” Authentication/Authorization experience with Silverlight 4

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

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

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

    How does refreshing help?

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

    Now, our ContentLoader XAML looks like this:

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

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

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

    My LoginPage code looks like this:

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

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

    Cool!  Can I see it in action?

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

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

    A WCF RIA Services application with the AuthContentLoader

     

    You can find the source for this application here.

    Anything else I should know about Refresh()?

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

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

    Is that it?

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

    , , , , ,

    32 Comments

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

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

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

    Getting a jump-start

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

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

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

    Whoa, what just happened?!

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

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

    Why load pages in external xaps?

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

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

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

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

    XapLoader

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

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

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

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

    Xaps with a cached assembly dependency

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

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

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

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

    XapContentLoader

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

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

    PackUriParser.Initialize();

    Then, in XAML:

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

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

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

    pack://<authority>/<path>

    There are three parts to this Uri:

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

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

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

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

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

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

    Enhancing the experience

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

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

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

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

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

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

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

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

    Cross-domain considerations and limiting access

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

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

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

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

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

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

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

    MEF and Prism

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

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

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

    The goods

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

    An application using XapContentLoader

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

    Finally, some source code for you:

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

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

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

  • , , , , , ,

    73 Comments

    Opening up Silverlight 4 Navigation: Authentication/Authorization in an INavigationContentLoader

    Continuing my series of posts on ways to use INavigationContentLoader (a feature in the Silverlight 4 Beta SDK), in this post, I’ll explore another idea for a composable INavigationContentLoader that protects access to your pages based upon the credentials of the user of your Silverlight application.  To demonstrate its use, I’m using a WCF RIA Services application (purely for their Authentication/Authorization provisions).

    The basic problem is this: as you would with a website, you build an application with multiple pages – some of which are intended for anonymous users or users in a particular role and some are intended for users with greater privileges.  How do you prevent such users from navigating to those pages and give them an appropriate user experience if they do try to reach pages for which they are not authorized?

    To that end, I’ve added another INavigationContentLoader to my SLaB examples – the “AuthContentLoader” – that checks to see whether your user is authorized to view a page before navigating to it.  If the user is not authenticated, the AuthContentLoader throws, resulting in a NavigationFailed event on the Frame/NavigationService that you can handle in order to provide better feedback to your users if there is an UnauthorizedAccessException.

    Cool – How does it work?

    If you’re familiar with authorization with ASP.NET (settings you might add to your web.config file), this ContentLoader’s use should come pretty easily to you.  For example, in ASP.NET, you might have the following in your web.config:

    <system.web>
      <authorization>
        <allow roles="Role1, Role2" />
        <allow users="SuperUser"/>
        <deny roles="Role3, Role4" users="LessImpressiveUser" />
        <deny users="?" />
        <allow users="*"/>
      </authorization>
    </system.web>
    

    I tried to keep the API for the AuthContentLoader quite similar.  With the AuthContentLoader, you can:

    • Allow or deny users access to pages that match a Regular Expression (allowing you to scope the authorization to particular pages)
    • Allow or deny users access to pages based upon their roles, authentication status, and user name
    • Wrap any other INavigationContentLoader in order to protect access

    To accomplish this, there are just a few steps:

    1. Set your Frame.ContentLoader to an AuthContentLoader.
    2. Bind AuthContentLoader.Principal to any IPrincipal (in my example, I’ll use the built-in authentication context in WCF RIA Services).  This is what the ContentLoader uses to check the user’s credentials.
    3. Add rules for your pages.  If no rule matches a page, the page is assumed to be broadly accessible.

    Put all of this together, and you end up with something like this:

    <navigation:Frame ...>
        <navigation:Frame.ContentLoader>
            <authLoader:AuthContentLoader Principal="{Binding User, Source={StaticResource WebContext}}">
                <authLoader:NavigationAuthorizer>
                    <authLoader:NavigationAuthRule UriPattern="^/Views/About\.xaml\??.*$">
                        <authLoader:Deny Users="?" />
                        <authLoader:Allow Users="*" />
                    </authLoader:NavigationAuthRule>
                    <authLoader:NavigationAuthRule UriPattern="^/Views/RegisteredUsersPage.xaml\??.*$">
                        <authLoader:Allow Roles="Registered Users" />
                    </authLoader:NavigationAuthRule>
                </authLoader:NavigationAuthorizer>
            </authLoader:AuthContentLoader>
        </navigation:Frame.ContentLoader>
    </navigation:Frame>
    

    Here, we have rules for About.xaml (with any querystring) and RegisteredUsersPage.xaml (again, with any querystring).  Note that the UriPattern is a Regex, and must also take into account the possible query strings that could be attached to the request.  I know it looks a little arcane, but it does the trick, and allows you to specify whole sets of Uri’s that share the same authorization characteristics (e.g. any page in the “PrivateViews” folder could be restricted to Administrators).

    The XAML snippet above places restrictions on two pages:

    • About.xaml – anonymous (Principal == null || Principal.Identity == null || Principal.Identity.IsAuthenticated == false) users are denied, and all other users are allowed
    • RegisteredUsersPage.xaml – only users that belong to the “Registered Users” role are allowed
    • Users are granted access to all other pages

    Like the ErrorPageLoader, the AuthContentLoader can take another ContentLoader (but defaults to the PageResourceContentLoader if none is specified), and will delegate the actual loading (after the user has been authorized) to that loader.

    And there you go!  Easy as pie!  Feel free to give it a try and play around with it!  Happy New Year!

    Wait!  Don’t stop yet!  Please tie this back to your other posts!

    Relax!  I won’t leave you hanging!  After all, what’s the point of having two composable INavigationContentLoaders (AuthContentLoader and ErrorPageLoader) if you’re not going to use them together? :)

    I made a very specific choice with the AuthContentLoader: when the user doesn’t have permission to access a page, the AuthContentLoader throws an exception.  That’s very convenient when you want to use the ErrorPageLoader to handle authentication failures.  The AuthContentLoader, by default, throws an UnauthorizedAccessException, so we can handle that exception explicitly using the ErrorPageLoader.  In this case, we’ll redirect users who visit an unauthorized page to another page that directs them to log in.  The XAML for this follows:

    <errorLoader:ErrorPageLoader>
        <errorLoader:ErrorPageLoader.ErrorPages>
            <errorLoader:ErrorPage ExceptionType="UnauthorizedAccessException" ErrorPageUri="/LoginPage" />
        </errorLoader:ErrorPageLoader.ErrorPages>
        <errorLoader:ErrorPageLoader.ErrorContentLoader>
            <errorLoader:ErrorRedirector />
        </errorLoader:ErrorPageLoader.ErrorContentLoader>
        <errorLoader:ErrorPageLoader.ContentLoader>
            <authLoader:AuthContentLoader Principal="{Binding User, Source={StaticResource WebContext}}">
                <authLoader:NavigationAuthorizer>
                    <authLoader:NavigationAuthRule UriPattern="^/Views/About\.xaml\??.*$">
                        <authLoader:Deny Users="?" />
                        <authLoader:Allow Users="*" />
                    </authLoader:NavigationAuthRule>
                    <authLoader:NavigationAuthRule UriPattern="^/Views/RegisteredUsersPage.xaml\??.*$">
                        <authLoader:Allow Roles="Registered Users" />
                    </authLoader:NavigationAuthRule>
                </authLoader:NavigationAuthorizer>
            </authLoader:AuthContentLoader>
        </errorLoader:ErrorPageLoader.ContentLoader>
    </errorLoader:ErrorPageLoader>
    

    Cool!  Now, if users navigate to a page they’re not authorized to see, they’ll be redirected to a login page!  Note the exception type being handled (UnauthorizedAccessException), the ErrorPageUri (unmapped, because we’re using the ErrorRedirector, which will cause a brand new navigation to take place – including mapping), and the use of the ErrorRedirector to redirect to a new Uri rather than just loading alternate content (allowing the user to come back to the page rather than assuming that the login page is the real content).

    Ok, we’re now in pretty good shape, but users can still hit problems besides the UnauthorizedAccessException, such as attempting to load a page that does not exist.  In my last post, we solved this using an ErrorPageLoader, and we’ll do the same this time.  In these cases, I actually do want to load alternate content rather than redirect to an error page, since this is the typical experience with web error pages (e.g. a 404 page).  I can accomplish this by adding a second ErrorPageLoader to the mix, like so:

    <errorLoader:ErrorPageLoader>
        <errorLoader:ErrorPageLoader.ErrorPages>
            <errorLoader:ErrorPage ErrorPageUri="/Views/ErrorPage.xaml" />
        </errorLoader:ErrorPageLoader.ErrorPages>
        <errorLoader:ErrorPageLoader.ContentLoader>
            <errorLoader:ErrorPageLoader>
                <errorLoader:ErrorPageLoader.ErrorPages>
                    <errorLoader:ErrorPage ExceptionType="UnauthorizedAccessException" ErrorPageUri="/LoginPage" />
                </errorLoader:ErrorPageLoader.ErrorPages>
                <errorLoader:ErrorPageLoader.ErrorContentLoader>
                    <errorLoader:ErrorRedirector />
                </errorLoader:ErrorPageLoader.ErrorContentLoader>
                <errorLoader:ErrorPageLoader.ContentLoader>
                    <authLoader:AuthContentLoader Principal="{Binding User, Source={StaticResource WebContext}}">
                        <authLoader:NavigationAuthorizer>
                            <authLoader:NavigationAuthRule UriPattern="^/Views/About\.xaml\??.*$">
                                <authLoader:Deny Users="?" />
                                <authLoader:Allow Users="*" />
                            </authLoader:NavigationAuthRule>
                            <authLoader:NavigationAuthRule UriPattern="^/Views/RegisteredUsersPage\.xaml\??.*$">
                                <authLoader:Allow Roles="Registered Users" />
                            </authLoader:NavigationAuthRule>
                        </authLoader:NavigationAuthorizer>
                    </authLoader:AuthContentLoader>
                </errorLoader:ErrorPageLoader.ContentLoader>
            </errorLoader:ErrorPageLoader>
        </errorLoader:ErrorPageLoader.ContentLoader>
    </errorLoader:ErrorPageLoader>
    

    And that’s it!  Now, when users access your site, they’re protected from any type of error and have access restricted appropriately!  Give it a shot with my live sample application:

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

    Also Note: I’ve been having a little trouble with my server, so if this doesn’t work for you, feel free to try downloading and running the code locally (see below for a link).

    Live Sample Application

    First, try clicking on the restricted links at the top of the application and observe the login page that appears.  Next, click the broken link (or type something random into your browser after the “#” in the URL), and observe the error page that appears.  Now, log in to the application (feel free to create your own account or use the test account above – any account should give you access to the pages that are currently restricted), and try visiting those pages again!

    Ok, I think I’m beginning to get it.  Give me the goods so I can go play with it!

    As always, I can’t leave you empty-handed.  I’ve added the AuthContentLoader to SLaB, which you can download to get both binaries and code.  I’ve also included the source (which requires WCF RIA Services and the Silverlight 4 Beta) for the demo application I linked to above:

    • Live Sample (source)
    • SLaB v0.0.2 (includes source, a sample app, some tests, and binaries)
      • For the latest version, please check out SLaB on my Downloads and Samples page.
      • The v0.0.2 download of SLaB includes:
        • AuthContentLoader and related classes
        • ErrorPageLoader moved into its own assembly (to keep its size down)

    In Conclusion…

    In my humble opinion, there is a lot of power in composing these types of INavigationContentLoaders.  With the AuthContentLoader, you can prevent Uri’s from being loaded in the context of your application.  Whether you’re just trying to provide a good user experience or actually prevent users from reaching certain Uri’s (e.g. dynamically downloaded XAPs/assemblies that should only be accessible if you’re logged in) a ContentLoader like this could be useful.  The AuthContentLoader works well with WCF RIA Services, which provides easy access through its “WebContext” concept to a User that represents both an IPrinciple and an IIdentity.  Stay tuned for more ideas – I’m still working on some fun little experiments.  Hopefully these posts inspire some cool ideas!  If you’ve got ‘em, I’d love to hear ‘em!

    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!) :) .

    Disclaimer

    The AuthContentLoader does not protect your data in any way – it simply provides a user experience around navigating to pages that may have restricted access.  Users can still open up your XAP and see its contents (so the XAML/code for those restricted pages isn’t protected), but it does do an effective job of limiting what users are able to access within your application.  You should still be aggressively securing your application if need be.  :)

    Don’t you have something else to say?

    Oh, yeah!  Happy New Year!  Here’s to (and good riddance to) the noughties, bring on the teens!  I hope you all have had a wonderful holiday season, and enjoy prosperity in the year ahead.

    , , , , ,

    43 Comments

    Opening up Silverlight 4 Navigation: Event-based and Error-Handling INavigationContentLoaders

    Last week, I gave an introduction to INavigationContentLoader, a Silverlight 4 Beta SDK extensibility point that allows you to load arbitrary content in conjunction with the Silverlight navigation feature, and walked you through building a Typename-based content loader.  That’s all well and good, but it’s an awful lot of work to go to in order to build a simple INavigationContentLoader (following the async pattern, fully implementing the interface, etc.).  Sometimes, all you really want to do is handle a few events in order to be up and running, fully integrated with Silverlight navigation.  Furthermore, because of the nature of the feature, Navigation has a high potential for error conditions.  For example, what happens if a user tries to follow a broken link or types a bad address into the browser’s address bar (with a browser-integrated frame)?  How do you gracefully let your users know that something went wrong and give them some options about what to do next?

    In this post, I’ll use the INavigationContentLoader extensibility point in the Silverlight 4 Beta SDK to address these two issues.  For convenience, starting with this post, I’ll be compiling my helper classes and utilities into a set of libraries I’ll call “Silverlight and Beyond” (SLaB), which you’re more than welcome to download and use (although I make no guarantees about its functionality or that I won’t introduce breaking changes as I make additions).

    An Event-Based INavigationContentLoader

    For simple custom content loading like we did with the Typename-based content loader, writing a full implementation of an INavigationContentLoader can really be overkill.  For quick-and-dirty navigation scenarios, it would be much easier to just use a generic INavigationContentLoader and handle some events in order to perform a load operation.  In the simplest case, loading is just a synchronous operation that creates an instance of a page based on your logic (a simple switch statement might be appropriate, and this gives you an opportunity to provide constructor parameters or do other initialization on your pages).

    With that in mind, I threw together a SynchronousEventContentLoader that simplifies these cases.  Now, you we can rewrite the Typename-based content loader as follows:

    In MainPage.xaml:

    <navigation:Frame x:Name="ContentFrame"
                  Source="/TypenameEventContentLoader.Views.Home">
        <navigation:Frame.ContentLoader>
            <loader:SynchronousEventContentLoader Load="SynchronousEventContentLoader_Load"
                                                  CanLoad="SynchronousEventContentLoader_CanLoad" />
        </navigation:Frame.ContentLoader>
    </navigation:Frame>
    

    In MainPage.xaml.cs, we handle the Load/CanLoad events as follows (virtually identical to our previous impelementation):

    private LoadResult SynchronousEventContentLoader_Load(Uri targetUri, Uri currentUri)
    {
        Type t = Type.GetType(GetTypeNameFromUri(targetUri), false, true);
        object instance = Activator.CreateInstance(t);
        var result = new LoadResult(instance);
        return result;
    }
    
    private bool SynchronousEventContentLoader_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;
    }
    
    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));
    }

    And that’s it!  If you just want a quick switch statement so that you can add initialization (constructor parameters, etc.) to your pages, this is a nice, easy way to go.  If there’s a need for something similar that supports asynchronous operations, making a similar INavigationContentLoader for that is fairly straightforward.

    Handling Errors using an INavigationContentLoader

    There’s a large variety of errors that can occur during navigation – the Uri may not resolve to anything real, the Page may throw an exception while being constructed, your user doesn’t have permission to see a particular page, or your particular INavigationContentLoader may hit an exceptional condition (no network access, invalid syntax when parsing a config file, etc.).  In order to develop a robust application, we need to be able to handle these error conditions gracefully.  For those of you familiar with web development, this is not too dissimilar from writing error pages to handle 404 (page not found) conditions, etc.

    One way to handle error conditions with the Navigation framework is to handle the NavigationFailed event on the Frame or NavigationService, but this means that when navigation does fail, your only options are to navigate to a new page altogether (resulting in extra history entries and the potential for further failures) or to show some other UI, which may leave your users with a blank page in front of them (in the Frame) if they navigate to the page directly (rather than from a link in your application).  Our approach will be to load a different page altogether when loading content fails.  For this, I’ve created an ErrorPageLoader, another INavigationContentLoader.

    Of additional importance is that this content loader doesn’t really own the content loading process from end to end.  In order for the ErrorPageLoader to be generalized, it must be composable, allowing it to delegate loading to another INavigationContentLoader except during error conditions.  In this case, the ErrorPageLoader has two INavigationContentLoaders that it may delegate its work to:

    • ErrorPageLoader.ContentLoader, which is what the ErrorPageLoader will attempt to use in order to service standard load requests.  This defaults to the PageResourceContentLoader built into Silverlight 4, which is what the Frame/NavigationService use by default.
    • ErrorPageLoader.ErrorContentLoader, which is what the ErrorPageLoader will use to load pages in case the ErrorPageLoader.ContentLoader fails.  If this value is null, the ErrorPageLoader uses ErrorPageLoader.ContentLoader to load the error pages.

    This dichotomy allows you to delegate to a more reliable INavigationContentLoader (e.g. the PageResourceContentLoader) should your primary one fail.  For example, if I use an INavigationContentLoader that downloads external assemblies on the fly, and the downlaod fails, error pages should be loaded locally rather than trying to load from a remote location.

    Next, we need a way to specify what Uri to load as an error page based on the type of error that occurred.  The ErrorPageLoader has an ErrorPages property that takes a set of IErrorPages – an interface that maps an exception type to a Uri.  I’ve provided a default implementation for use in XAML that takes a name of an Exception type to handle (or none at all, in which case it becomes a catch-all handler) and a Uri (unmapped) to load using the ErrorContentLoader when those error conditions arise.

    With these things in mind, the usage of the ErrorPageLoader looks like this:

    <navigation:Frame x:Name="ContentFrame"
                      Source="/Home">
        <navigation:Frame.UriMapper>
          <uriMapper:UriMapper>
            <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
            <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
          </uriMapper:UriMapper>
        </navigation:Frame.UriMapper>
        <navigation:Frame.ContentLoader>
            <loaders:ErrorPageLoader>
                <loaders:ErrorPage ExceptionType="System.InvalidOperationException"
                                   ErrorPageUri="/Views/InvalidOperationErrorPage.xaml" />
                <loaders:ErrorPage ExceptionType="System.InvalidCastException"
                                   ErrorPageUri="/Views/InvalidCastErrorPage.xaml" />
                <loaders:ErrorPage ErrorPageUri="/Views/DefaultErrorPage.xaml" />
            </loaders:ErrorPageLoader>
        </navigation:Frame.ContentLoader>
    </navigation:Frame>
    

    There are just a few things to note here:

    • Because I didn’t specify an ErrorPageLoader.ContentLoader in the example above, the PageResourceContentLoader will be used to load pages normally.
    • The ExceptionType isn’t actually of type Type, since Silverlight XAML doesn’t support custom properties of type Type at the moment.
    • The ErrorPageUri is an unmapped Uri (i.e. it does not follow the UriMapper-based scheme)
    • When an error page is loaded, the CurrentSource of the Frame/NavigationService (or the browser if the Frame is browser-integrated) remains the same.  If you want the Uri to change, use the ErrorRedirector INavigationContentLoader that I’ve provided to redirect to the error Uri.

    The final step in the process of error handling is to provide some good feedback to your users about what went wrong.  In order to do this, it’s useful to know what exception occurred that caused the error page to be loaded.  As such, the ErrorPageLoader has an attached “Error” property, which it attaches to any page loaded using the ErrorContentLoader.  This attached property holds the exception that was thrown during loading.

    I threw together a little example of an error page that uses this attached property, like so (alternatively, I could have bound to it in XAML):

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        this.errorInformation.Content = ErrorPageLoader.GetError(this);
        this.uriLink.NavigateUri = e.Uri;
    }

    You can see an example of the ErrorPageLoader in action here:

    Live ErrorPageLoader sample

    And here are some things to try:

    Notice what happens to the Uri (everything after the “#” in the URL) when navigating to pages that are in error.  Try changing the URI to anything you can think of – you’ll always be able to navigate there, but the links will just lead you to error pages.

    If you’re really brave, here are some other experiments to consider:

    • Wrap the ErrorPageLoader around the Typename-based content loader from my previous post, and try navigating to Types without a default constructor or that don’t exist
    • Wrap the ErrorPageLoader around your own INavigationContentLoader (or the SynchronousEventContentLoader).  When do you expect loading to fail?  What should the user experience be when something does go wrong?  (here’s an idea: throw an exception if the user isn’t logged in, and use the ErrorPageLoader to show a login page)

    So… How does it work?

    Well, the behavior of the ErrorPageLoader is pretty straightforward:

    • Try to load the page from the targetUri using the ErrorPageLoader.ContentLoader
    • If an exception is thrown during that INavigationContentLoader’s BeginLoad or EndLoad, or if the loader returns something invalid (e.g. the LoadResult contains something that’s not a Page or a UserControl)…
      • Find the first IErrorPage in ErrorPageLoader.ErrorPages
      • If an IErrorPage was found, try to load the Uri that the IErrorPage maps to using ErrorPageLoader.ErrorContentLoader
        • If the LoadResult has a Page rather than a redirect, attach the Exception using the Error attached property
      • Otherwise, throw the exception during EndLoad() (i.e. allow the exception to fall through)
    • Return the LoadResult

    And really, that’s the nature of a composable INavigationContentLoader: add some functionality around an existing INavigationContentLoader, and pass the remaining results on through to the Frame/NavigationService.  Such content loaders make it easy to decorate existing loaders with functionality that applies to your application.  I’ve got a few ideas for these, but I’d love to hear what you think!  Here are a few that I have on my mind:

    • Error pages (in case you didn’t just finish reading about those :) )
    • Authenticating/Authorizing (redirect me to a login page or an error page if I’m not authorized to see the one I requested)
    • QueryString initialization (reflect over properties on the page to set based upon the query string of the Uri)
    • Chainer (if the first INavigationContentLoader in my list didn’t work, try the next one!)

    With that said, what else would you like to see?  If something particularly compelling arises, I’d be happy to add it to my “Silverlight and Beyond (SLaB)” library!

    And, as always, the goods…

    You didn’t really think I’d leave you without some code and samples, did you?

    • Live sample
    • SLaB v0.0.1 (includes source, a sample app, some tests, and binaries)
      • For the latest version, please check out SLaB on my Downloads and Samples page.
      • The v0.0.1 download of SLaB includes:
        • ErrorPageLoader and related classes
        • SynchronousEventContentLoader

    P.S.  What on Earth is SLaB?

    I mentioned it briefly at the beginning of this post, but my plan is to start putting all of my utility classes, tools, controls, and so forth in one easily-downloadable and easy-to-use package.  For now, I’m calling this SLaB, or “Silverlight and Beyond” (just because I’m into really corny acronyms).  Hopefully you’ll find it useful either as an example of what to do (or if you really dislike me – what not to do :) ), or to use within your own applications.  If you’re curious about how or why I did something, or if you find a bug, let me know!  Who knows?  Maybe you’ll inspire another blog post!

    Just one note: it’s just little ol’ me working on SLaB, and I make no guarantees of correct behavior, frequent updates, lack of breaking changes, full documentation, support, or anything of the sort.  Nonetheless, I look forward to adding to it whenever my curiosity is piqued enough to make something useful or demonstrative, and I hope you find it useful too!

    , , , ,

    17 Comments