davidpoll.com
Posts Tagged WCF RIA Services
Common Navigation UI and Authorization-driven Sitemaps
Posted by david.poll in Silverlight on May 10, 2010
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
- 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
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&First Name=David&Last Name=Poll&Title=Penguins!&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&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&c=d&e=f&g=h" /> <SLaB:SitemapNode TargetName="ContentFrame" Title="Demo (more complex QueryString)" Uri="/Views/ObservableDictionaryDemo.xaml?a=b&Name=David Eitan Poll&Url=http://www.davidpoll.com&No Value&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.
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!
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!
Authorization, Controls, Navigation, Silverlight, Silverlight 4, Silverlight and Beyond (SLaB), Sitemap, WCF RIA Services
A “refreshing” Authentication/Authorization experience with Silverlight 4
Posted by david.poll in Silverlight on April 25, 2010
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”
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?
ContentLoader, Navigation, Silverlight, Silverlight 4, Silverlight and Beyond (SLaB), WCF RIA Services
Opening up Silverlight 4 Navigation: Authentication/Authorization in an INavigationContentLoader
Posted by david.poll in Silverlight on January 1, 2010
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:
- Set your Frame.ContentLoader to an AuthContentLoader.
- 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.
- 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).
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.
ContentLoader, Navigation, Silverlight, Silverlight 4 Beta, Silverlight and Beyond (SLaB), WCF RIA Services
Silverlight 4 and building business applications (PDC09-CL19)
Posted by david.poll in Silverlight on November 19, 2009
Hi everyone! Wow – yesterday was a big day, with a lot of amazing announcements at PDC ‘09 – especially the announcement that the Silverlight 4 Beta was publicly available. I was very excited to be given an opportunity to give a talk at PDC this year, and it was a real treat. My talk – Building Line of Business Applications with Silverlight 4 (PDC09-CL19) – focused on the new features in Silverlight 4 that are particularly useful in business applications, especially those that are data-centric. (Please ignore the abstract given on that page for the talk – it wasn’t updated properly from a change we made to it early on!
)

The talk covered a wide array of features, but I broke things down into three conceptual categories around data:
- Data Interactivity (i.e. how do I drill down into my data to find what I’m looking for?)
- Data Entry (i.e. how do users add/edit data and what kind of feedback do you give them to minimize mistakes?)
- Data Presentation (i.e. how do I communicate data to a user, but also how do I communicate intent for data entry, such as “choose from this list of options” to a user?)
The Silverlight 4 features I covered generally fit into these categories:
- Data Interactivity
- Data sources window (VS2010)
- Selector support (i.e. SelectedValue/SelectedValuePath on ComboBox and related controls)
- Binding TargetNullValue
- Binding FallbackValue
- ICommand support on ButtonBase (i.e. Command and CommandParameter) and Hyperlink
- Data Entry
- Asynchronous validation
- Cross-field validation
- Data Presentation
- Binding StringFormat
- CollectionViewSource Grouping
- Printing and pagination
- DataGrid * Columns (*-based column sizing, as with the Grid control)
And all of this is just the short list of features I could cover in my 50-minute talk! There are certainly other business application-friendly features out there, but more importantly, the feature list for Silverlight 4 is just huge! The talk also used Visual Studio 2010 Beta 2, which provides an awesome development environment for Silverlight.
I won’t go into too much detail here, but I wanted to share out my powerpoint deck and sample/demo code so that those who were in attendance at the talk can look back for reference, and those that weren’t can see what they were missing. I don’t know for sure yet, but I think there will be a webcast of the talk online at some point, and I’ll be happy to link to that once it’s available.
So, without further ado, here are the links:
- PDC ‘09 PPT deck
- Issue tracker demo application (source)
Before I leave you, I’d like to just give a brief overview of the sample application. The application itself is an issue tracker – allowing you to file bugs/issues, assign them to people, resolve the bugs, etc. It has 4 functional pages:
- New Issue
- Allows users to file a new bug/issue
- All Issues
- Allows users to see a list of all bugs in the database
- My Issues
- Allows users to see un-fixed issues that are assigned to them
- Reports
- Allows users to see a report of all of the issues in the database and print them if he/she so desires
The application was built using LINQ-to-SQL and WCF RIA Services (formerly .NET RIA Services), which made getting off the ground with real data running on a real database extremely quick and easy. If you’re still around at PDC, there are a few talks later today on RIA Services by Brad Abrams and Dinesh Kulkarni you should check out.
A few things to try in the application (some of which I didn’t go over in the talk):
- Right-click and change the theme of the application
- Many thanks to my co-worker Jesse Bishop for his ContextMenu control
- This feature uses implicit styles (new in SL4) to change the entire look of the application
- Set the priority on a bug to be lower than (i.e. a larger number than) severity and see the validation UI (cross-field validation)
- Set the title of an issue to be something wholly contained in another issue’s title to see the validation UI (asynchronously querying the server for “similar” bugs)
- Drag and drop a file from your disk into the list of files on a bug (one of the tabs at the bottom)
- Print out a set of reports on the reports page (click the “Print” button)
- Set a value in the “Tags” field and then change it in the DataGrid under the Attributes tab on a bug, noticing that they stay in sync (thanks to bindings to string indexers)
- Use the mouse-wheel almost anywhere and note that it works without any code to make it happen!
- Explore the code! I know there are some bugs in the application and in our beta product, but the hope is to give you an idea of how you can use these features in a business application. I’m sure there will be lots of content out there about all of these features – but this should help introduce you to them!
Well, thanks again everyone who was able to join me for my talk, and to all those who’ve been following me on twitter through this exciting announcement. Let me know if you have questions or if there’s anything you’d like me to expand on, and I’ll be more than happy to chime in!
Links to materials repeated here for convenience:
- PDC ‘09 PPT deck
- Issue tracker demo application (source)
Update (11/19/2009): Video of the talk is now available here: http://microsoftpdc.com/Sessions/CL19
Update (11/20/2009): Video of the talk is embedded below:
P.S. Sorry for the lack of posts recently – I’ve got a bunch of new topics lined up, but it was a pity not to be able to write about Silverlight 4 before it was announced. Expect another series on Navigation coming soon!
Update (12/21/2009): I think I’ve figured out the issue people were having with the downloaded project.
If you’re receiving an error like this when you try to build my project:
This is happening because Windows protects you from downloaded files by default (VS2010 will warn you when you open the project that they come from “untrusted sources.” Fixing this is pretty straightforward.
- Download the zip.
- Right-click the downloaded zip file and choose “Properties”
- At the bottom of the “General” tab, there is a “Security” section, saying “This file came from another computer and might be blocked to help protect this computer.” Click the “Unblock” button.
- Unzip and open the solution.
- Build and run!
Sorry it took me so long to figure this one out! It had me stumped for a while.
.NET RIA Services, BusyIndicator, CollectionView, Data Binding, PDC, PDC09, Silverlight, Silverlight 4 Beta, Validation, Visual Studio 2010, WCF RIA Services
Update 2: Displaying background activity in a Silverlight RIA application
Posted by david.poll in Silverlight on September 14, 2009
Hi folks! It’s been a little while since I’ve blogged, but fear not, I’m still watching and hoping to blog more in the coming weeks.
In the meantime, it’s been brought to my attention by a few people now that there are a few issues with the Activity control, and I wanted to address them.
- Performance – A bit of a mea culpa on my part. I included a feature for the control that I’ve called “AutoBind”, whereby it would watch for changes to the visual tree of its contents and subscribe to any control that has a property whose name matches “ActivityPropertyName”. By default, this is great when working with .NET RIA Service’s DomainDataSource, since ActivityPropertyName is “IsBusy” by default, but it also turns out to be a hefty amount of work, constantly searching the visual tree and registering/unregistering event handlers. This wouldn’t be so bad, except that AutoBind defaults to true, meaning even if you’re not using this functionality, the Activity control is doing the work. Below, you’ll find a new version of the Activity control that amends the situation, making AutoBind default to false. This is the only change to the control since my last post on the matter, but I’d love to hear if you have thoughts about the control, this feature, or other requests!
- .NET RIA Services’ Business Application Template – So, the .NET RIA Services guys included with their July Preview a project template to help you get started with a RIA Services application. In this template, they included a dll with the Activity control in it. A few people have noted that it has a slightly different API than they’re used to seeing with the control, which is due to their use of the original version of the control that I posted (its API has changed a bit since then, and a number of bugs were fixed, including some layout issues). Anyhoo, feel free to pick up the latest version below!
So there you have it – just a few changes and things to note. You can find the control here:
Thanks for all the great feedback since I first posted this control. As usual, let me know if you have questions or issues!
.NET RIA Services, Activity Control, BusyIndicator, Silverlight, Silverlight 3, WCF RIA Services
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
- What a great first week at the new job! It's great to feel so energized by work.February 4, 2012 7:08
- @andruwang Amen.February 3, 2012 7:50
- @andruwang @ParseIt Likewise -- it's been a fantastic first week!February 3, 2012 6:49
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.
Warning: Missing argument 2 for tweetable_write_widget() in /home3/depollco/public_html/davidpoll/wp-content/plugins/tweetable/tweetable.php on line 137


