Welcome to MSDN Blogs Sign in | Join | Help

David Hill's WebLog

Iblogyoublogweblog
Prism & WCF RIA Services

Back in August I did a post that described how you could use .NET RIA Services and Prism together. That post, and the associated sample app, was based on the .NET RIA Services July CTP.

.NRS –> WRS

A couple of weeks ago at PDC those terribly nice RIA Services chaps released a Beta version, for both Silverlight 3.0 and 4.0. And in time-honored Microsoft tradition, they also changed the name – it now seems to be officially named WCF RIA Services (WRS for short) – to reflect the switch to WCF as the underlying service implementation. You can download the WRS Beta here.

I’ve updated the Prism/WRS sample to work with the Beta drop. You can download it here. The sample targets Silverlight 3.0, WRS Beta and VS 2008. I’m sure with some tweaking it will be relatively easy to get working on Silverlight 4.0 and VS 2010 too. As before, the sample requires the Northwind sample database to be installed and running.

Prism 2.1 –> Prism 4.0

The sample was also updated to use the latest Prism 2.1 release (which you can download here). This is a minor update to the 2.0 (February) release and contains a couple of minor updates in the commanding area. Prism 2.1 was also fully tested against Silverlight 3.0 and against Silverlight 4.0 Beta…

With the release of Silverlight 4.0 Beta, and with VS2010 and .NET 4.0 at Beta 2, we are ramping up our planning for the next major version of Prism. We’re thinking of calling it Prism 4.0 (skipping whole version numbers is another time-honored Microsoft tradition) – so that it lines up with Silverlight 4.0, WPF 4.0 and .NET 4.0!! Planned release date is late spring next year, but as always, once the project is underway we’ll be releasing intermediate drops every two weeks.

I’ll be posting much more on our Prism 4.0 plans in a week or so, but if you have any ideas for what you’d like to see in Prism 4.0 please send them my way…

The Breadcrumb Navigation Pattern

The Breadcrumb Navigation pattern provides a visual representation of the path the user took as they navigated to a particular state in an application. It provides context so the user can see where they are logically within the application structure, and it allows them to quickly navigate that structure by jumping straight to previous breadcrumbs.

Perhaps the most common example of the breadcrumb navigation pattern is Windows Explorer – as you navigate the file system, the breadcrumb control at the top of window displays the path to the current folder, with each folder in the chain displayed as a button. You can jump directly to any of the parent folders by clicking on it.

clip_image001

You often see the pattern used in web sites, especially ones where the user is navigating through a lot of hierarchical data. For example, a lot of ecommerce site allows the user to browse the product catalog by drilling into product categories and by specifying search criteria and filters. Here’s a good example from GuitarCenter.com – you can navigate around within the product catalog by product category and filter the view by price or manufacturer.

clip_image002

The Breadcrumb Navigation Pattern in Helix

This post describes how you can implement the breadcrumb navigation pattern in Helix, my prototype navigation framework for Silverlight. You can download the latest version of Helix from here, and run the sample described below here.

The BreadcrumbBar Control

Implementing the Breadcrumb Navigation pattern in Helix turned out to be quite straightforward. The main element is the BreadcrumbBar control. This control displays the breadcrumbs as the user navigates within an associated Frame. The user can click on any of the breadcrumbs causing the associated Frame to navigate back to the corresponding point in the navigation history.

The BreadcrumbBar control is actually a sub-classed and re-templated ListBox control that is bound to the target Frame's journal. As the user navigates between Pages in the target Frame, journal entries are added to the journal. Each journal entry is represented in the BreadcrumbBar control as a ListBox item. The BreadcrumbBar control's template displays each item horizontally as a chevron, along with the corresponding page title. The most difficult part to getting this to work is the control template itself. I used Blend 3.0 to edit the template so even that wasn't that difficult. I also made a couple of changes to the Helix library itself to support breadcrumb style navigation in the Journal. More details on this below.

The Sample Application

clip_image004

Patterns & practices guidance is organized by four high-level focus areas – Fundamentals, Client, Server and Services. Within each area there can be a number of sub-categories (such as security, performance, etc), and within sub-categories there is the guidance itself. Since the catalog is hierarchical, it’s a natural fit for the breadcrumb navigation pattern. I’ll describe a simple application that uses the BreadcrumbBar control and Helix to allow the user to browse through the patterns & practices guidance catalog. You can see the completed application and the BreadcrumbBar control in action here.

This is a simple application that has a simple shell that contains a BreadCrumbBar control and a Frame control in a grid:

<BreadcrumbBar Grid.Row="1"
       NavigationTarget="{Binding ElementName=frame}"
       ClearForwardStack="False"/>
 
<Frame x:Name="frame" Grid.Row="2"
    NavigationUIVisibility="Hidden" InitialUri="HomePage"/>

The BreadcrumbBar control is connected to the target Frame through simple data binding. Since we’re using the BreadcrumbBar control we don’t need the Frame’s back/forward buttons so we can hide the Frame’s navigation UI. The Frame navigates to the HomePage on startup. That’s pretty much it. I’ll talk about the ClearForwardStack below. You can tweak some of the visual aspects of the BreadcrumbBar control, or even replace the control template, to suit your application’s UI style.

How Does It Work?

The BreadcrumbBar control is just a sub-classed and re-templated ListBox. When the NavigationTarget property value is set, it sets the base class ItemSource to the journal back stack.

this.ItemsSource = NavigationTarget.Journal.BackStack;

If the user changes the current selection (i.e. by clicking on a previous breadcrumb), the target Frame is navigated to the associated Uri. To support this I added two new methods to the IJournal interface – GoBackTo and GoForwardTo. These two methods allow the journal to navigate directly to an entry that’s in the back stack or the forward stack, without having to navigate backwards or forwards multiple times.

NavigationTarget.Journal.GoBackTo( entry, ClearForwardStack );

Two other things to note:

  • The current selection of the underlying ListBox tracks the last entry in the journal. In other words, as the user navigates to new pages within the Frame, a journal entry for it is added and it becomes the current selection in the BreadcrumbBar control.
  • The ClearForwardStack parameter is used to control how the journal’s forward stack is affected when the user clicks on a previous breadcrumb. Most often you’ll want the forward stack to be cleared, and this is the default. Sometimes you might want to keep the forward stack intact so the user can go forward again. To enable this, just set the ClearForwardStack parameter to false.

What’s Next For Helix?

Now that Silverlight 3.0 supports navigation, the need for Helix is not as great as it was. I actually wrote the original specs for the Silverlight 3.0 Navigation feature. The original design in fact was very similar to Helix, but due to a number of constraints the design evolved and became a little less extensible than originally planned. There are key extensibility points that Helix provides which enable a whole host of interesting scenarios that are difficult or impossible to achieve with the current Silverlight navigation implementation. I’ve really only scraped the surface of these in this series so I’ll continue to evolve Helix in order to explore these scenarios. I’m working with the Silverlight team to explore ways in which these key extensibility points can be opened up in upcoming Silverlight releases.

In the meantime, if you’re building a Silverlight application that requires navigation functionality, you should use the Silverlight 3.0 navigation framework since it’s robust and fully supported. Hopefully, the need for Helix will go away altogether once the Silverlight navigation framework is more extensible.

The Application Architecture Guide 2.0 Is Here!

AAG2FrontCover-Small The Application Architecture Guide 2nd Edition is finally available! The complete guide is hosted on MSDN here. We’ve sent the guide off to MS Press for printing, so the printed version should be available from your favorite bookstore soon.

Since the final draft of guide was published on CodePlex early this year, we’ve been busy driving the guide through a final set of reviews and polishing the content. Based on community and p&p team feedback we’ve restructured the guide to make it easier to read and understand. We’ve also removed some of the duplication and made it easier to find your way around so you can more easily find the information that’s relevant to you. We’ve also incorporated a lot of the feedback that we’ve received from the community on topics like Domain Driven Design and Cloud Computing. It’s taken us a little longer than we thought, but we hope you’ll agree that the wait was worth it.

Of course, there are so many elements that go into producing a guide of this scope that it clearly represents a team effort. In particular, the many members of the community and the p&p team who brought their technical expertise and experience to the guide deserve a special mention, along with our esteemed writer Alex Homer and the rest of our content team who drove the guide through the edit, layout, indexing, and publishing phases.

What’s next for the guide? Well, that’s up to you! We designed the guide so that it could be more easily updated; for new architectural techniques and approaches, for new technologies, and for new application types and scenarios. For example, we could add a Windows Azure application archetype, or update the technology matrices for the .NET 4.0 wave of technologies. In order for us to prioritize where we go next with the guide we need your feedback, so please send it along and let us know what you think.

Blend Behaviors

Expression Blend 3 includes a number of very cool new features (see here for a good summary). But there are two that I think are particularly important – SketchFlow Rapid Prototyping, and Blend Behaviors. I’ll cover SketchFlow in some depth in a future post. In this post I’m going to talk about Blend behaviors and how they can be used to extend Helix, my prototype Silverlight navigation framework.

What Are Behaviors?

Behaviors are objects that encapsulate some form of interactive behavior. Blend allows them to be easily 'attached’ to visual elements in the UI, via drag-drop or declaratively in XAML. They enable developers or designers to rapidly add rich interactivity to the UI without having to write code.

image Blend 3 ships with a number of behaviors (shown left) that allow you to easily animate an element, change it’s visual state, start/stop a storyboard, play sounds, etc.

However, the key thing is that Blend allows you to create new behaviors of your very own. And not only that, but when you do they will automatically show up in the Blend toolbox ready for use by a developer or a UI designer.

There is also an Expression Gallery here dedicated to community developed behaviors, so if you develop a particularly cool behavior you can readily share it with other Blend users.

Behaviors – Think XAML Extension Methods!

The implementation details and concepts behind Blend behaviors are pretty simple. They leverage the simple but powerful ‘attached property’ mechanism in WPF and Silverlight. Instead of attaching a simple value though (like Grid.Row=”2”) you’re attaching an object that encapsulates behavior. Such objects are sometimes called Attached Behaviors. They provide an elegant way to extend existing controls without having to modify the control’s code or it’s UI template. I like to think of attached behaviors as the XAML equivalent of extension methods in C#.

Developers have been using attached behaviors for quite a while now as a way of extending Silverlight and WPF. In fact, they are pretty much the only way that you can extend Silverlight, since it lacks a number of other key extensibility mechanisms (such as custom markup extensions). As such, they’ve proven to be a very useful way to add missing functionality to Silverlight.

For example, since Silverlight controls do not (yet) inherently support commanding, we used this technique in Prism for wiring up button-derived controls to commands on the ViewModel:

<Button prism:Click.Command="{Binding ViewOrdersCommand}" />

I also used this technique in Helix to implement CollectionView support (now thankfully redundant since it’s supported in Silverlight 3.0).

Both Prism and Helix provide base classes that allow you to more easily create attached behaviors, and there are a number of other third party behavior frameworks that you can use too. But now that we have the Blend Behaviors Framework, we can hopefully all standardize on a single framework.

Triggers, Actions and Behaviors

Blend behaviors actually come in two main flavors – Actions and what I’ll call Full Behaviors.

Actions are simple behaviors that encapsulate an action (believe it or not) that are associated with a trigger. You can use an action and trigger pair to make something happen as the result of an event fired by the parent control. You can, for example,  change a property value, control a storyboard, play a sound, or cause a control to move to a particular visual state as the result of a Click, MouseLeave, MouseEnter, MouseLeftButtonDown event, or any other event that the parent control fires.

Here’s a simple example – when the user moves the mouse over the image, the opacity property is changed to 0.5:

<Image Source="MyImage.png">
  <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseEnter">
          <ic:ChangePropertyAction PropertyName="Opacity" Value="0.5"/>
      </i:EventTrigger>
  </i:Interaction.Triggers>
</Image>

You could of course choose a different event to trigger the action, or choose a different property to change. Blend makes it very easy to drag an action onto a control and to configure it to do what you want.

Some actions operate solely on the parent control that the trigger is connected to. Some actions can operate on a control other than the parent. These actions are called Targeted Actions. If no target is explicitly specified, the target defaults to the parent control.

You’ll notice that the EventTrigger is added to a triggers collection. That means you can add as many triggers to a control as you like. Other types of triggers are possible too, not just ones that are associated with the target control’s events. For example, you can imagine using mouse/stylus gestures as triggers, etc.

Full behaviors are useful for encapsulating more complex interactive behavior that aren’t necessarily associated with a single trigger. The following example uses one of the coolest behaviors that Blend provides – the MouseDragElementBehavior. By simply attaching this behavior to a control, you can allow the user to drag it around in the UI!

<Image Source="MyImage.png">
    <i:Interaction.Behaviors>
        <il:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </i:Interaction.Behaviors>
</Image>

Again, you’ll notice that it gets added to a behavior collection, so you can have multiple behaviors on a single control.

Blend provides an assembly, System.Windows.Interactivity, that contains a number of base classes that you can use to define your own triggers, actions and behaviors. Simply add a reference to this assembly to your project (you’ll find it in the ‘C:\Program Files\Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\Silverlight|WPF’ directory or thereabouts) and away you go. Any triggers, actions, or behaviors that you define will automatically be available in the Blend toolbox. Let’s see this in action…

A Custom Action

Some of you may have been following my series of posts on the Helix navigation framework for Silverlight. If so, you’ll know that Helix provides a NavigateLink control that you can use within a page to link to another page that the user can navigate to. The NavigateLink control derives from Silverlight’s HyperlinkButton control. It’s a very simple control – the only thing is really does is to fire a navigate event up the visual tree so that it can be handled by a Frame control which then manages the actual navigation.

But what if you don’t want to use a NavigateLink button control to initiate navigation? Say you want to navigate using a different control, like an Image or a ListBox, or in response to a different event than Click, like MouseEnter/Leave or SelectionChanged? Well, now you can with the HelixNavigateAction!

The HelixNavigateAction class is pretty simple. It derives from the Blend TargetedTriggerAction class – the target in this case is a Frame so you can initiate navigation on a specific frame. It defines two dependency properties, NavigateUri and NavigationParameter. The overridden Invoke method is the only interesting part of this class and is shown below.

protected override void Invoke( object parameter )
{
    Uri navigationUri = this.NavigateUri;
 
    // Navigate to the specified Uri.
    if ( this.NavigateUri != null )
    {
        // See if we have to format the navigation Uri with
        // any parameters.
        ...
 
        // See if the target frame has been specified explicitly.
        // If not, bubble a request navigate event through the visual tree.
        Frame frame = this.Target as Frame;
        if ( frame != null )
        {
            frame.Navigate( navigationUri );
        }
        else
        {
            // Bubble the RequestNavigate event to the nearest
            // parent Frame.
            UIElement parent = this.AssociatedObject as UIElement;
            parent.RaiseEvent(
              Microsoft.Samples.Helix.Controls.Frame.RequestNavigateEvent,
              new RequestNavigateEventArgs( navigationUri, TargetName ) );
        }
    }
}

As you can see, we first check to see if a target Frame has been specified. If it has, we call the Navigate method on it directly. If not, then we raise a RequestNavigate event which will bubble up through the visual tree until a containing Frame control is found. That’s pretty much it. In the next section we’ll see how we can use the HelixNavigateAction class in Blend.

While creating actions in Blend is fairly straightforward, there are a couple of wrinkles to be aware of…

If you look closely at the classes provided in the System.Windows.Interactivity namespace, you’ll see that there are two main action classes – TriggerAction<T> and TargetedTriggerAction<T>. Both ultimately derive from the TriggerAction base class. Now you’d probably think that the generic parameter <T> in each of these classes would specify the same kind of type.

Well, it seems that the <T> in TriggerAction<T> specifies the type of Associated (parent) control, but the <T> in TargetedTriggerAction<T> specifies the type of the Target control. For a TargetedTriggerAction, to constrain the type of the parent control, you have to add a TypeContstraint attribute to the class:

[TypeConstraint( typeof( UIElement ) )]

Not sure why they did it like this… This design seems a little weird to me. I would have thought something like TargetedTriggerAction<A,T> would have worked better, then you could specify the types of the Associated and Target controls in the same consistent way…

The other thing to be aware of is that, if a Target value is not explicitly defined for an Action, the Target property will be set to the Associated parent control instance. This means that the type of the Target has to be assignable to the type of the Associated control. For example, we’d ideally like our HelixNavigateAction class to target Frame controls, but be associated with any type of control. Something like this:

[TypeConstraint( typeof( UIElement ) )]  <- Type of Associated Control
public class HelixNavigateAction :
        TargetedTriggerAction<Frame> <- Type of Target Control

This won’t work unfortunately since if a Target is not explicitly specified, it will be assigned the Associated control (which is probably not a Frame) so an InvalidOperation exception will be thrown at runtime. Again, not sure why they did it like this. I would have thought that leaving Target as null if it hadn’t been explicitly specified would have worked better. Yes, you’d have to check for null and then perform the action on the Associated object (maybe) but you’d have much more control and flexibility… Ho hum…

HelixNavigateAction In Action

So with our newly minted HelixNavigateAction class all compiled, let’s put it through it’s paces in Blend. You can download the sample project (including the latest version of Helix) here.

We’ll start with a simple app with main screen that contains a frame (the big area on the left) and four headline controls (on the right).

image

We’re going to use the HelixNavigateAction to navigate the frame to various pages as the user clicks on the headline controls on the right. If you click on the Assets tab and then on Behaviors, you will see a list of Behaviors and Actions that you can use. You’ll notice that the HelixNavigateAction is already there for us!

 image

Simply drag the HelixNavigateAction over and drop it one of the headline controls on the right hand side of the main screen. You see the action get added to the object tree and the property grid will show various trigger and action properties. Let’s setup the trigger first by choosing the MouseLeftButtonDown event in the EventName dropdown. Next, we’ll set the target. For this we can use the rather nifty target picker! You just click on the round target icon and then click on the Frame and hey presto! the TargetName property is filled in:

image

Finally, we just have to specify the Uri to navigate to. For that we simply use the dropdown on the NavigateUri property and select whichever page we want to navigate to:

image

Repeat for the other three controls and that’s it, we’re all done! For grins, change the trigger event to MouseEnter to get a ‘hot-spot’ navigation effect. You can run the completed app here.

With Blend and the Blend Behaviors Framework we have a pretty powerful and flexible way to create re-usable components that encapsulate interactive behavior and a way to use them to snap together an application very rapidly.

I’ve only really scratched the surface here. There are plenty of other cool and powerful things that we can do with behaviors. Also, it may be that we can leverage this framework in the next release of Prism, and thereby replace our implementation in favor of the Blend implementation. Not only will this reduce the amount of code in Prism, it will also allow us to leverage the built-in design-time support that Blend provides…

Helix

I made a few small changes to the Helix framework to support the use of Blend Behaviors. I also updated the samples for Silverlight 3.0. You can download the latest version here (version 0.31).

Blend Behavior Resources

You might find the following resources useful as you explore Blend and the Blend Behaviors Framework:

Prism Training Classes

Due to popular demand, and hopefully signs of a recovering economy, the Rolling Thunder chaps are running another online Prism training course. It’s a 3 day course and runs from October 27th to the 29th. Full details here:

http://www.rollthunder.com/prism/prismpublicclass.htm

Prism And .Net RIA Services

For the past couple of weeks I’ve been working on a sample that shows how you can use Prism and .Net RIA Services (I’m going to call it .NRS for short) together. In this post I’m going to walk you through the sample and show how you can structure a Prism & .NRS solution that uses modules as a way to compose applications from both a services and a UI perspective. You can download the source code for the sample application here.

If you’re not familiar with .NRS, it’s framework and related tools that allows you to define a set of entities (or business objects if you prefer) on the server and have those entities made available automatically within your Silverlight client project. You can then use those entities within your Silverlight application where you can create, edit or delete them via the UI, and then save the changes back to the server. .NRS takes care of sending data and updates over the wire so you don’t have to worry about creating and maintaining web services and service references. .NRS also provides support for meta-data driven cross-tier validation and provides common application services, such as user profile, authentication and authorization. See here and here for more details on .NRS and download the July CTP from here.

Quite a few folks have asked me whether Prism and .NRS can work together. The answer, happily, is that Prism and .NRS not only work together they actually complement each other pretty well. When we developed Prism 2.0, we had an item on our backlog to provide guidance on getting data from the server to the client and back again. Unfortunately we didn’t get to that item in Prism 2.0, but .NRS provides support for exactly that scenario. Using Prism and .NRS together is relatively straightforward but there are few issues that you need to be aware of. .NRS is currently available as a CTP so there may be an opportunity for the .NRS folks to address some of these issues before the final release.

The Big Picture

As you know, Prism provides support for building modular client applications in WPF or Silverlight. Prism modules often encapsulate a ‘vertical’ slice of the application’s overall functionality by including all of the view, view model, model and service components required to implement that slice. Such modules are frequently re-usable across multiple applications, allowing you to compose or extend applications from packages of functionality. For example, you might have a financial services application with modules that provide real-time and historical market data, analyst reports, portfolio management, 401K management, options trading, etc. Each of these functional areas can be encapsulated in one or more modules and this allows you to build a single application from an open-ended set of modules, or even a family of applications that each focus on a particular user role or business area.

So how does .NRS fit into this picture?

More and more folks have ‘service enabled’ their back-end systems as part of their move to a service oriented architecture and that has enabled access to a lot of useful data and business processes. Having access to these services is great but it doesn’t really get you very far. The challenge then becomes how to build a compelling and consistent user experience on top of those services. To do that you need a client-side representation of the service that can be composed into a user experience. That representation can of course be a Prism module. The module interacts with the back-end service and provides a user experience for it that can be composed into an application alongside other such modules that represent other back-end services. In effect, Prism & .NRS together provide a way to construct data services and corresponding client-side modules that can be combined into interesting applications.

.NRS allows client-side and server-side projects to be linked together so that they can communicate with each other and share code. .NRS supports a number of configurations but the one we’re most interested in is where the client-side project is a Prism module, and the server side project is a .NRS class library that implements a single data service. In this configuration, the client-side modules are composed into a Shell, and the server-side class libraries are hosted in a web application.

PrismRiaServices

The Sample Application

To show how all of this works we’re going to create a simple order management application which uses two modules – one to display the user’s current orders, and one to display the product catalog. Each module consumes a corresponding data services on the server side. You can imagine that in a real enterprise, the order management system and the product management system could be entirely separate systems. In our simple example, we’re using a single database to represent both (the Northwind database) but we’ll build two independent data services to show how services can be composed.

Before we get started, you’ll need to install Silverlight 3.0, the .Net RIA Services July CTP, and the Northwind sample database. We’ll also use the Prism Quick Start Solution I outlined in a previous post. We’ll start by creating a copy of the Silverlight Quick Start solution and build our application on top of that. When you open the solution, Visual Studio will convert it into a Silverlight 3.0 project. The solution includes two modules called Module1 and Module2. Rename them OrderModule and CatalogModule (you might to change the corresponding assembly name, default namespace and XAP file name too).

The next step is to create the Order and Catalog data services. These are the server-side .NRS class libraries that implement the data services that we’re going to consume in the corresponding Prism modules. Add two new .Net RIA Services Class Library projects to the solution named OrderServices and CatalogServices respectively. You’ll see that this actually creates two projects in a folder – one for the server-side and one for the client-side. We don’t need the client-side project (since we’re going to use the Prism module projects to consume the services) so go ahead and delete the client-side projects OrderServices and CatalogServices, but keep the server-side projects OrderServices.Web and CatalogServices.Web. These server-side projects each come with WorkerRole class (for reasons that escape me) so delete those too.

Before we go any further we need to link the various projects together. We link the two server-side projects to the Web project by simply adding project references. This will cause the services to be ‘hosted’ in the Web project. That was the easy bit. Now we need to associate our client-side module projects with their corresponding server-side service projects. If you look at the module project properties dialog you’ll see there is a .Net RIA Service Link dropdown. This feature lets us link our client-side and server-side projects so that the .NRS tooling can copy and generate the right files. What we want to do is to link our module projects to the corresponding service projects.

Unfortunately, .NRS won’t let us do this easily within Visual Studio. The dropdown only shows the Web project, and not the server-side class library projects that implement the services. That’s because Prism module projects are considered Silverlight application projects (i.e. they produce a XAP file) and not Silverlight class library projects. .NRS only seems to allow Silverlight class library projects to be linked to .NRS server-side class library projects in the project properties dialog. I am not sure why .NRS has this restriction. The simple workaround is to open up the .csproj file in Notepad and add the link manually:

<LinkedServerProject>..\OrderServices.Web\OrderServices.Web.csproj</LinkedServerProject>

Now when you open up the module project properties dialog you’ll see the correct .NRS link in place:

image

The next step is to include the right assembly references in the Web and the Prism Module and Shell projects. For the Web project, add references to the .NRS DataAnnotations, DomainServices, and Web.Ria assemblies – Note that the .NRS version of the DataAnnotations assembly is marked as version 99.0.0.0 (don’t know why but I’m sure this is temporary). For the module and shell projects add references to the .NRS DataAnnotations and Windows.Ria assemblies.

Everything should now compile ok. If you view all files in the module projects you‘ll see a new folder called ‘Generated_Code’. This is where .NRS will generate or copy the code that will allow us to interact with the corresponding services.

The next step is to implement the services themselves and the client-side app logic to consume them. This step is pretty straightforward and follows the many tutorials out there on .NRS (like Brad Abrams’ great series on .NRS) so I’m not going to go into the details here (this post is long enough already). I will however summarize the process and call out a few interesting points along the way.

  • To implement the Catalog Service, we add an ADO.Net Entity Data Model that pulls in the Northwind Category and Product tables. We then add a Domain Service class that defines the queries on top of that data model – one for all products, one for all categories, and one for a specific product by ID. The Product entity queries include the corresponding Category entities so that the client doesn’t have to make a separate query for category information.
  • public IQueryable<Product> GetProductById( int productId )
    {
        // Include the category in the product query.
        return this.Context.ProductSet.Include( "Categories" ).
            Where( product => product.ProductID == productId );
    }

  • The Order Service is implemented in the same way except that the data model pulls in the Northwind Order, Order Details and Product tables. Again, the Order entity queries include the Order Details entities so the client doesn’t have to make a separate query for each Order line item. The Order Detail includes the Product name (rather than the entire Product entity).
  • As you create the ADO.NET Entity Data Models and the Domain Services for each service, an App.Config file is generated which contains the database connection string. You have to copy this connection string to the Web projects Web.config file. This allows the host web application to provide the connects to the databases that the hosted services projects need. Don’t forget to do this otherwise your services won’t be able to connect to the database and it can be difficult to track down the problem (experience talking here!).
  • In addition to including related entities in the data query, you have to provide meta-data to .NRS to tell it to serialize the related entities over to the client. You do this by creating a meta-data class that is associated with the entity class and adding an entry with an [Include] attribute:
  • [MetadataType( typeof( ProductMetadata ) )]
    public partial class Product
    {
        internal sealed class ProductMetadata
        {
            [Key]
            public int ProductID;
            [Include]
            public Category Categories;
        }
    }
     
  • The sample shows how you can use .NRS and the client-side classes that it generates to implement the ViewModel pattern. On the client side, .NRS generates classes for the Product, Category, Order, and Order Details entities and for the Service Context classes that provide access to the services themselves. You’ll see that these classes effectively replace the Model and Services classes that were included in the Prism Quick Start Solution. Each Prism module implements one or two ViewModels which use the service context classes to query data via the server. The entities themselves are considered Models. The ViewModel coordinates the query and selection of entities so that the Views can simply data bind to them.

The sample application is pretty simple. It’s meant to show how to structure a solution that uses Prism and .NRS together. It does not show how to use some of the more advanced features of .NRS, like data updates and application services for authentication and authorization. I’ll cover those in a future post…

The sample also uses some of the cool new Silverlight 3.0 features, such as the PagedCollectionView class and some of the new easing functions (for the compulsory gratuitous animation!) and many of the ‘standard’ Prism features, like the RegionManager, EventAggregator, ModuleCatalog, etc.

Summary

.NRS provides a simple way to create data services on top of a database and to expose data entities to the Silverlight client where you can perform CRUD operations on them. Coupled with Prism, it allows you to build flexible applications that compose data services into an rich user experience. To be sure, .NRS isn’t the only way to build and consume data services, and it isn’t suitable for all types of applications, but for some applications it can be very productive and effective.

A couple of words of caution though. While .NRS is technically independent of the data access technology used, it does make it rather too easy to simply expose tables from your database directly to the client. You will have to very careful not to couple your client application to your database by inadvertently exposing your database schema via the services. To avoid this, you should think first and foremost about the data model that you’re going to expose as a service to the client, and then worry about how that maps to persistent storage.

I would also be careful when using the .NRS DomainDataSource component. You can use this to connect your UI directly to the .NRS data services but I think it does mean that you’re implementing, in some sense, application logic directly in the View where it is difficult to test. Personally I’d rather do this kind of thing in the ViewModel where I can unit test it. YMMV though.

Prism Quick Start Kit Update

As promised, I have updated the Prism Quick Start Kit and added a WPF quick-start solution and WPF project templates. You can download the latest release here. In the zip you’ll find four project templates (Shell and Module templates for WPF and Silverlight) and two quick-start solutions, one each for WPF and Silverlight.

To install the templates, copy the project template zip files to your Visual Studio C# template folder. On my system the templates go here:

“My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#”

You should also remove the previous Prism templates if you have installed them. Next, register the templates with Visual Studio by running

devenv.exe /installvstemplates

in a Visual Studio command prompt window (as admin).

When you run Visual Studio and create a new project, you should see the four templates show up in the Visual C# node.

image 

Using the Prism project templates should be pretty straightforward. Couple of things to note though:

  • When you create a project with any of these templates you should first of all update the references to point to the Prism assemblies on your system. The quick-start solutions come complete with a Lib folder that contains pre-built Prism binaries so they work out of the box for convenience, but you should try and use the Prism binaries on your system where you can.
  • You will of course need the Silverlight Visual Studio tools to be installed before you can use any of the Silverlight project templates or the quick-start solution. See here for more information on getting started with Silverlight development.
  • The WPF shell project comes complete with a module catalog that looks for modules in the local output folder. If you add a WPF module to your project you will have to copy the output module assembly to the shell’s bin/Debug or bin/Release folder. I use a post-build step on each module project to automatically copy the assemblies over after every build:

    image
    You’ll need to update this with the name of your shell project.  You can achieve the same thing by simply adding project reference to your modules projects and then Visual Studio will copy over the assemblies for you, but since Prism advocates a  loosely-coupled composite architecture this seems like cheating to me :-).

The Silverlight and WPF quick-start solutions are essentially the same – the only difference between the two is that the WPF shell includes a menu-like button that’s hooked up the shell’s Exit command. I also updated the quick-start solutions to include a style that can be applied to ContentControl regions so that a banner containing the region name is displayed. This is just to make it easier for folks to see where each region is located within the shell.

image

The quick-start solutions are meant to provide a skeletal solution on which you can build real application. They are not very interesting as a standalone app, but if you’re curious to see what it looks like you can run the Silverlight version of the quick-start solution here.

Prism Training Course

David Platt of Rolling Thunder has just announced another 3 day Prism training course to be held July 7th-9th. You can find all of the details here. It’s web delivered so you don’t even have to travel!

It looks like it covers a lot of material – there’s a detailed syllabus here – from the basic goals and architecture of Prism, all the way through to advanced scenarios with modules, services, loosely-coupled events, and UI composition.

If you’re looking to use Prism to increase the quality of your WPF & Silverlight applications and to speed up your development it’s definitely worth checking it out.

Prism Quick Start Kit

Building applications from scratch starting from a blank page or screen in Visual Studio is a frustrating, time consuming and intimidating task. Instead, most developers like to start with a working application that they can modify, tweak and extend to suit their needs.

Far too often though, developers take a demo or a sample as the starting point for their application, and this often leads to a poor application design that’s complex, difficult to test and debug, and inflexible. Demos and samples have their place of course – they are great for illustrating a single concept or a cool new feature – but they are typically not designed to provide a solid base for an entire application.

Prism is a library of design patterns that work together to provide a solid architectural foundation on which you can build real-world Silverlight and WPF applications that are flexible and maintainable. Some of the patterns that Prism contains are fairly simple while others are more complex, but they are designed to work together to solve some of the challenges you face when building these real-world applications.

We illustrate individual patterns using what we call ‘Quick-Starts’ which are small focused sample applications. We illustrate how the patterns work together using what we call a ‘Reference Implementation’, which is a large sample application that implements a real-world scenario (during development, we actually use the RI to help us figure out what challenges a developer faces when building a non-trivial real-world application, and from those challenges we distil the patterns that help to address them and then implement those patterns in a reusable library). For Prism, the RI is a Stock Trader application that allows you buy and sell stocks and to manage your portfolio.

However, neither the Quick-Starts nor the Reference Implementation that we include in Prism are great for taking as a starting point for a new Prism application. The Quick-Starts are too fine-grained and focused on one specific pattern or technique, while the Reference Implementation is too coarse-grained and includes a lot of application logic that’s specific to the stock trader scenario.

The Prism Quick Start Kit

To help with this problem, we are considering building a number of solution and project templates for Visual Studio that would give you a simple working app that you could tweak and modify. These would fall somewhere in-between the Quick-Starts and Reference Implementation and provide a basic solution and project structure into which you could add your application specific files.

I spent a couple of days this week prototyping this approach. I built a couple of project templates (one for a Prism Shell, and one for a Prism Module) and a solution template that provide a complete multi-module working app. You can download these templates from here. Together, these templates make up what I call the ‘Prism Quick Start Kit’.

Installation

Installation of the project templates is fairly straightforward:

  1. Unzip the starter kit and copy the ‘Prism Shell.zip’ and ‘Prism Module.zip’ files into your Visual Studio templates folder. They are C# templates so they go here on my system:

        My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#
  2. To get Visual Studio to display the new project templates in the New Projects dialog, run the following command (as admin) in a Visual Studio Command Prompt window:

        devenv.exe /installvstemplates

Getting Started With The Prism Project Templates

To see the project templates in action, follow these steps:

  1. Fire up Visual Studio, and click File/New/Web Site. Click on ASP.NET Web Site and enter ‘PrismApp’ as the folder name. This will create the web project that will host our Prism application.
  2. Next, right click on the PrismApp solution and selected Add/New Project. Select the ‘Visual C#’ project types node and you should see the Prism Shell and Prism Module templates in the My Templates section:

    image
  3. Click on the Prism Shell template and then click on OK. This will create a Prism Shell project called ‘Prism.Shell1’.
  4. We need to tidy up the project references to point to the Prism and Unity assemblies. If you click on the References node you’ll probably see that these references need updating. If you’ve added these assemblies into your GAC then they should be ok, but if not, you’ll need to remove them and add them again by browsing to wherever you complied them on your system.
  5. Next, we need to link the Prism Shell project to the Web project. Right click on the web project and select Property Pages. Click on the Silverlight Applications node and then click the Add button. In the dialog, select the Prism Shell project and click Add then OK.

    image 
  6. This will link the Prism Shell project to the web project and create a test page. Right click on the Prism.Shell1TestPage.html page and select Set As Start Page. Press F5 and click Ok to enable debugging. You should see the Prism shell in all its glory:

    image
  7. The shell includes all of the basic things you typically need in a shell – a shell View and ViewModel, a bootstrapper and a module catalog. The shell’s UI includes a simple 3 region layout. [Eventually, you can imagine having a whole gallery of different shell layouts and themes to choose from…]
  8. The next step is to create a Prism module project. Right click on the PrismApp solution, select Add/New Project, choose the Prism Module project template and click OK. This will create a module project called ‘Prism.Module1’. The project template contains all of the basic things you need in a module – a View and ViewModel, a basic data model and a data service.
  9. We need to do the dance with the references as above. [We’ll hopefully figure out a way to make this experience much better in the future…]
  10. Next, link the module project with the web project as above, but this time make sure that the ‘Add a test page’ check box is unchecked – we don’t need a test page for the module. Click Add then OK. This step ensures that the module’s xap file gets copied to the web ClientBin folder.
  11. The last step is to add the module to the shell’s module catalog. Open the ModuleCatalog.xaml file and uncomment the first entry:
  12. <prism:ModuleInfo Ref="Prism.Module1.xap"
      ModuleName="Module1"
      ModuleType="Prism.Module1.ModuleInit, Prism.Module1, Version=1.0.0.0"
      InitializationMode="WhenAvailable"/>

    If you used a different name for the module, you’ll have to edit this to use the names that you chose.
  13. When you press F5, you will see the module get loaded into the shell and the module’s view displayed in the shell’s main region. You’ll also notice that the module includes a simple data model that gives the UI something to display. You can take this as a starting point and modify to suit your needs.

image

The Prism Quick Start Solution

I find the project templates described above pretty useful for creating new Prism projects, but there are way too many steps involved to make it a simple and clean experience. What I’d really like to do is to create a ‘Solution Template’ that includes all of the sub-projects and references all linked up and ready to go.

Unfortunately Visual Studio doesn’t by itself allow this to be done easily. There are additional tools and frameworks available that enable this, but at this stage I wanted to keep it simple so the next best thing was to just create a baseline sample project that I can manually copy and modify whenever I want to build a Prism multi-module solution. I call this the ‘Prism Quick-Start Solution’.

The baseline quick-start solution is the third zip file in the Prism quick-start kit. If you unzip it you’ll see that it contains Web and Shell projects, two Module projects and a ‘Common’ class library. The solution has all of these linked together and includes the Prism and Unity assembly so that you don’t have to fix up any references. In other words, you can unzip it and go!

image

If you run the app or examine the code, you’ll see that it contains a little more functionality than you get by just using the project templates described above. This is because, in a typical Prism application, there are a couple of common things that you need to do to coordinate the functionality between the Shell and the multiple Modules.

An example of this is when you implement loosely-coupled events between modules to coordinate context or user actions. The quick-start solution shows how to implement simple cross-module master-detail functionality – when you click on the Master View (from Module 1), the Catalog View (from Module 2) will update. This also shows how you typically coordinate data and context across two modules…

Another example is the use of a Controller class to programmatically coordinate the display of Views in a region in order to implement navigation or application workflow. The quick-start solution uses a controller class to programmatically display views in the main region when the user clicks on buttons in the master view.

The quick-start solution is meant to provide a basic structure for a Prism app and to include the most commonly used features of Prism. I find it very useful as a starting point because it contains all of the little code snippets and that you often need and has a basic structure in place making it pretty straightforward to take it and modify it to create many different types of applications. It’s hopefully also a good place to experiment with Prism and to learn about some of its basic features.

oO------Oo

I hope you find these templates useful. We’re hoping to provide templates like these in Prism 3.0 but we’d also like to provide item templates, code snippets and some simple in-tool automation to make building Prism apps really simple and straightforward. Let me know what you think, and whatever else you’d like to see in Prism 3.0…

Download the Prism Quick Start Kit here.

ViewModel and Dependency Injection

In my last post – Silverlight Navigation Part 3 – I outlined a mechanism whereby you could navigate to a View and have the application create and wire up the associated ViewModel automatically. I also showed the inverse of this, where you could navigate to a ViewModel and have the application automatically create and wire up the associated View automatically.

Whether you prefer the View-First or the ViewModel-First approach, the essential feature that really supports the ViewModel pattern is that the system should be able to create a ViewModel for a View (or vice versa) automatically. Otherwise, the burden falls to the developer to do this in code, which can result in a complicated architecture that’s either inflexible or difficult to understand and maintain.

Let’s say, for example, that you have adopted a View-First approach. Now, you could just have some code in your application (say, in a controller component or event handler somewhere) that simply creates the required View and it’s associated ViewModel and wires them together like this:

public ShowCustomer()
{
    CustomerView view = new CustomerView();
    CustomerViewModel viewModel = new CustomerViewModel();
    view.DataContext = viewModel;
 
    myContentControl.Content = view;
}

You can use this approach with a ViewModel-First approach too. Another simple approach is to just get the View to create its own ViewModel, either in its constructor:

public partial class CustomerView : UserControl
{
    public CustomerView()
    {
        InitializeComponent();
        this.DataContext = new CustomerViewModel();
    }
}

or via XAML:

<UserControl.DataContext>
    <CustomerViewModel />
</UserControl.DataContext>

All three of these approaches work great, except that they hard code your application to use specific View and ViewModel types. This may very well not be an issue for you, and if it isn’t, I say go for it!

However, there are times when you’ll want to have the View and the ViewModel types more loosely coupled. An example might be when you want to decide at run-time which View to display for a particular ViewModel based on, say, the user’s role, chosen UI theme, screen size, or even the type of device that the user is using(!). So, while the approaches above are simple, they are relatively inflexible.

Dependency Injection To The Rescue?

It is at this point that the Dependency Injection folks will start to gesticulate wildly and remind us that this is exactly the situation in which DI excels. Remember that with DI, if you have a dependency between one class and another, the system (i.e. the DI container) can automatically fulfill that dependency dynamically at run-time for you. This allows the classes to be more loosely coupled and removes the need for you to manage the creation of dependent classes yourself. Let’s see how this works…

Say we have a class ‘A’ that depends on (i.e. has a reference to) a class ‘B’. Typical DI containers (including Unity) require that we express the dependency between A and B using a type – typically (but not necessarily) an intermediate interface type, say IB – and that we define a constructor on A that takes a reference to that type. We then register our implementation of the intermediate interface type with the container – so that it knows that whenever anybody wants an implementation of IB it will create an instance of B.

So, when we want an instance of class A, we just ask the container to create one for us. It spots that class A requires a reference to an IB implementation, so it goes and creates a B for us automatically and passes a reference to it to A’s constructor. The container manages the creation of dependent classes for us!

It is of course true that in many situations DI is a good solution for this kind of problem. I think though, that for the ViewModel scenario DI is not ideal. To illustrate why, let’s see how DI typically works in View-First and ViewModel-First scenarios…

The Perils of IViewModel

In our View-First example above, we have a View that wants a reference to (depends on) a ViewModel, so we’d first register an implementation of our ViewModel with the container:

_container.RegisterType<ICustomerViewModel, CustomerViewModel>();

and we’d design the View so that it gets a reference to the ViewModel implementation in its constructor:

public CustomerView( ICustomerViewModel viewModel )
{
    this.DataContex = viewModel;
}

Finally, we’d get the container to create an instance of the View. The container will automatically create an instance of the registered ViewModel type and pass a reference to it into the View’s constructor.

CustomerView view = _container.Resolve<CustomerView>();

Ok this works, but I think there are a number of problems with this approach:

  • To create the View we have to use the DI container. We can’t just create the View using ‘new’ and we can’t create it declaratively via XAML (since that will use the default constructor which won’t pass in a reference to the required ViewModel). In other words, we have to have a controller or event handler or some code somewhere that creates the View via the container by calling Resolve.
  • The UI designer (even if the UI designer is really a developer) should not have to write code in the View just to make it work. If there is some complicated UI behavior that can’t be done declaratively, then code may be required, but this should be a special case and not required every time just to get stuff wired up and working. Even implementing the simple constructor above takes some explanation and can be easily forgotten or incorrectly implemented.
  • We have defined a ‘marker’ interface type that we don’t really need – i.e. the interface has no properties or methods, we’re just using it as a marker. Yes, we could define some properties and method on it, but the View should not be programmatically calling into the ViewModel. Remember, UI designers should not have to write any code. All interactions between View and ViewModel should be done via bindings and attached behaviors so that the View is just a loosely coupled observer of the ViewModel.

The Evils of IView

So that’s Dependency Injection in a View-First world. What about a ViewModel-First world? Well, things are no better here either. Similar to the process outlined above, we’d probably define an IView interface; register an implementation of it with the container; define a constructor on the ViewModel that accepts an IView reference; then create an instance of the ViewModel using the container:

_container.RegisterType<ICustomerView, CustomerView>();
...
public CustomerViewModel( ICustomerView view )
{
    ((FrameworkElement)view).DataContext = this;
}
...
CustomerViewModel viewModel = _container.Resolve<CustomerViewModel>();

Again, a couple of problems with this approach:

  • Again, we can’t create a View declaratively using XAML – the container will create the View as a result of creating an instance of the ViewModel class – so we’d have to have a controller or event handler or some code somewhere to kick things off.
  • We’d have a marker interface that we’d don’t really need and that won’t define any properties or methods – the ViewModel should not be programmatically calling into a View.
  • The UI designer would have to implement an interface on the View each and every time they create one. It’s not terribly complicated, but the UI designer should not be required to write any code except for advanced scenarios.
  • The ViewModel-First approach is actually slightly worse that the View-First approach because of the nasty cast in the constructor. This is required in order to set the view’s data context to the ViewModel.

Wouldn’t It Be Nice If…

In my last post on navigation, I showed a couple of different approaches to the problem of conjuring up a View for a ViewModel (or vice versa) without using a Dependency Injection approach.

  • For View-First, instead of using DI and defining interfaces and constructors, I just used an attached property on the View to specify the type name of the ViewModel (ViewModel.TypeName) and the system automatically constructed the ViewModel for me and wired it up to the View’s DataContext.
  • Going the other way (ViewModel-First) , I just used a naming convention to infer the name of the View from the ViewModel’s type name, created an instance of that View and set it’s DataContext.

Neither of these approaches are ideal though, so I got to thinking what an ideal approach might look like… The key is that we need a simple way of expressing the relationship between the View and the ViewModel types so that the system can just make the right things happen!

If you’re familiar with DataTemplates in WPF, you know that it’s possible to define a DataTemplate (somewhere in the application’s resources) for a particular (non UI) type. Whenever the system has to display an object of that type, the DataTemplate is automatically used to visually represent it. Under the covers, the system creates an instance of the DataTemplate, sets its DataContext to the object that it represents, and then displays it in the UI. Silverlight does not yet support implicit data templating – you have to specify the DataTemplate explicitly for each control – but the mechanism is very similar.

I think this is close to what we want…

I think of DataTemplates simply as “Thin Views” – i.e. purely declarative Views with no code behind. They are very useful, but sometimes you just need to have some code in the View (for complex visual behavior that can’t be done declaratively). So, if the system could be extended to include Views that could have code behind, it would all fit together in a nice, simple, consistent model. It could look something like this…

We define a View as usual and simply declare that it is associated with a ViewModel data type:

<UserControl x:Class="MySample.CustomerView"
             DataType="{x:Type MySample.CustomerViewModel}"

For the ViewModel-First approach, we simple create (or navigate to) an instance of the ViewModel and display it. For example,

MyContentControl.Content = new CustomerViewModel();

The system would then step in and create an instance of the View that corresponds to this type and would wire up the DataContext for us – just like the system does today with DataTemplates!!!

Similarly, for View-First, where we simply create (or navigate to) a View, the system would automatically create an instance of the associated ViewModel type for us and wire up the DataContext. There would likely be another property to control this behavior.

I think this approach has a number of benefits:

  • The system carries the burden of finding and creating corresponding Views and ViewModels, making our application code much, much simpler. And simpler means that it’s faster to write, easier to debug, and easier to unit test!
  • It gives us a single consistent model that works for Views with and without code behind.
  • It works declaratively as well as programmatically giving us a lot of freedom to create Views or ViewModels in code or in XAML as desired. It works great with navigation too.
  • It allows Views to express a dependency on a particular ViewModel, while allowing ViewModels to remain completely View agnostic. This opens up a whole host of interesting design-time tooling possibilities – like you get with DataTemplates today – but with more explicit support for the ViewModel pattern. For example, you can imagine that the UI designers can provide intelli-sense or drag & drop support for binding expressions and behaviors (because the design-time system can determine the ViewModel’s commands, notifications and properties).

You’ll have noticed that we’re not using an intermediate interface type to loosely couple the View and ViewModel. The approach could be extended to support that though, for example by using the upcoming Managed Extensibility Framework (MEF), or by building in some form of simple Dependency Injection mechanism into the XAML loader system.

Until I prototype this approach more fully, it’s not clear whether it will really work as well as expected. Also, it’s not clear at this stage when (or if) we could expect it this approach to be implemented in the platform.

We can but dream though…

Silverlight Navigation Part 3

Welcome to the third post in my series on navigation in Silverlight! The goal of this series of posts is to provide a simple to use framework (called Helix) for building Silverlight applications that are based on a flexible navigation mechanism and the ViewModel separated presentation pattern. This post is long and was a tough one to write (which is partly why it took so long to complete!) but this post takes us much closer to our goal.

If you’ve been reading this series from the beginning, you’ll have noticed that we’re taking something of an agile approach to building Helix. You can think of each post in this series as an iteration. And like all good agile projects, we’re not afraid of a bit of refactoring, or of adding or significantly altering features as we tackle new scenarios. So in the latest version of Helix you’ll find some changes compared the version in part 2.

Some of these changes are bug fixes, but most are new features or extensions to existing features to support the ViewModel pattern alongside navigation. You’ll also find more samples and unit tests in this drop. There is a summary of the main changes and new features at the end of this post. You can download the latest release from here and you can run all of the latest samples from here.

The Story So Far…

Before we get into any details, let’s quickly review what we’ve covered in previous posts…

In the first post in the series, I introduced the Helix Frame and NavigationLink controls and showed how they could be used together with a simple Journal to implement a simple navigation mechanism between pages in a Silverlight 2.0 application.

In the second post in the series, I introduced the Route, NavigationHandler and NavigationController classes and demonstrated how they can be used to implement navigation between pages based on parameterized navigation links. That post also showed two ways of passing parameters via the navigation link to the target page, so that the page can be initialized or have it's context set appropriately.

One way was to use the NavigationPageController class which passes all of the navigation parameters to the target page's OnNavigate method (through the INavigationPage interface). The other way was to use the PageActionController class which invokes a page action method on the target page by mapping the navigation parameters to the method's name and it's parameters.

Both of these approaches created an instance of the target page and then passed the navigation parameters directly to it. As noted in the second post, this is clearly not ideal since it means that the page will then contain application logic as well as UI – not good for a lot of reasons!!!

Separated presentation patterns like the ViewModel pattern help to keep the UI and application logic cleanly separated. I described the ViewModel pattern in a previous post, but to recap, the ViewModel pattern separates UI and presentation logic into View and ViewModel classes, and uses data binding and commands to communicate between them. In this post, I provided an implementation of a generic ViewModel for handling collections, imaginatively called CollectionViewModel. In this post, I described two strategies in which the View and the ViewModel can get created and linked up. In View-First composition, the view is logically created first. In Presenter-First composition, the presenter (the ViewModel is our case) is logically created first.

These three additional posts can be considered parts 2a, 2b and 2c of this series, so please check them out if you haven't already done so. We’ll be building on the concepts and features they describe in this post.

Ok, that’s the background information out of the way. Let’s get started extending the Helix navigation framework so that it works alongside the ViewModel separated presentation pattern…

The Challenge: Mixing ViewModels and Navigation

One of the challenges with any separated presentation pattern is that you have to have some way of creating, hooking up and managing the additional components that are involved. In our preferred ViewModel pattern these additional components are principally Views, ViewModels and Models.

Now, if your application is fairly static, it’s fairly straightforward to create and hook up these components. But if your application is more dynamic (for example, when the UI changes constantly because the user is navigating around within the application!) then things are not quite so simple. As well as creating and hooking up these components during navigation, we also have to figure out how the other parts of the application are going to interact and communicate with them.

In my experience, this issue – the handling of Views, ViewModels and Models in a dynamic application that includes navigation – is the one that causes the most confusion and pain for folks building real-world applications using the ViewModel pattern. It is this very issue that we’re going to tackle in this post…

Choosing A Navigation Scheme

Before we get into the details on the integration of the ViewModel pattern into the Helix navigation framework, we first have to think about the different ways in which we can structure our application so we can and navigate around within it.

Helix essentially allows you to design a navigation scheme for your application by allowing you to decide how the various elements in your application are linked together by parameterized Uri's. When you define the format of the navigation links in your application, you are designing the way in which the user will navigate through your application to access its functionality and content by identifying the main navigational elements in your application and identifying which parameters are passed to them. At a high level, there are two basic navigation schemes to choose from.

Perhaps the simplest navigation scheme is one where the application's navigational links refer directly to the application's visual elements. Using this scheme means that we'll link the application together using Uri's that refer to pages or controls within the application and allow the user to navigate between them. This is the navigation scheme that we used in the last two posts of the series. I think this type of navigation scheme tends to work great for content-centric applications – i.e. when the user expects to be primarily navigating through content. Blog readers, news readers, and media sharing apps are good examples of this type of application.

With Helix you are not limited to using simple page-based navigation schemes. You can link your application together in other interesting ways. In particular, you can structure your application so that it's composed of tasks or actions that the user carries out. I call these types of applications task-centric applications.

Let's look at a simple example – an expense reporting application. In terms of tasks, the user can create, edit, submit, approve, reject, or archive expense reports, so we could structure our application so that the user naturally navigates between these tasks in sequences that are natural. For example, the user may start by creating a new expense report and then submit it for approval; then they may edit a draft expense report and save it for later submission; then they may review their approved expense reports and archive them away for safe keeping.

I think this type of navigation scheme is very interesting. It means for instance, that we can align our application’s navigational structure with the application's use-cases and the user’s tasks, rather than having to strictly follow the visual structure of the application. This means that we can more cleanly separate the visual structure of the application from its logical structure and work flow, which in turn means that we can more easily test the application, and have more flexibility when designing a fluid, animated UI for it. In addition, when we consider deep linking (in a future post) we'll see that the user, or other systems, very often will be exposed to the navigational structure of the application, so having a navigation scheme that’s independent of the visual structure can also be important for many other reasons.

At this point you might be asking: “Yes, but does it really matter what the navigational scheme for an application is since the user never sees it – they just click on links and the UI gets updated?”. This is of course true, up to a point. It’s not clear that one approach is superior to the other – I can see advantages and disadvantages with each – so we’ll explore both approaches to see what each feels like when building an application.

Whatever your choice of navigation scheme, content-centric or task-centric, the important thing is that you are comfortable with it and use it consistently throughout your application. Using multiple schemes within the same application can lead to user confusion and an application that’s difficult to maintain or extend. Choosing a navigational scheme that's natural for your application will help you build, test and extend it much more easily and will help to make it easier to use, so it’s important to design your navigation scheme wisely and to stick to it.

Ah, But What About The ViewModel?

Regardless of the navigation scheme, things get even more interesting when we introduce the ViewModels pattern into the navigational picture. Using the ViewModel pattern means that we'll have a component that encapsulates the UI (the View), and a component that encapsulates the presentation logic and state (the ViewModel). My post here describes the ViewModel pattern in some detail.

The View and the ViewModel have to get created and hooked up together and this can happen in one of two ways – the view is either logically created first followed by the ViewModel on which is depends, or the ViewModel is logically created first followed by the View on which it depends. I call these two mechanisms View-First or ViewModel-First composition respectively – see my post here for more details.

Now – and this is a key point – if you think about a content-centric navigation scheme as described above, you'll see that this maps very naturally to View-First composition! The user is logically navigating to a View so we construct the View first, followed by the ViewModel on which it depends and that provides a clean separation between UI and presentation logic.

On the other hand, with a task-centric navigation scheme, the user is logically navigating to a component that manages an activity or task. This component (as we'll see below) maps quite naturally to a ViewModel, so logically we're creating the ViewModel first, followed by the View on which it depends so that it can be visually represented in the UI. In other words, task-centric navigation maps naturally to ViewModel-First composition!

So, we can clearly identify two distinct navigational styles:

  • View-First Navigation – Where the user navigates between Views in a content-centric application,
  • ViewModel-First Navigation – Where the user navigates between ViewModels that represent tasks or activities within the application.
Interestingly, you can also see the correlation between content-centric navigation and view-first composition, and task-centric navigation and presenter-first composition, in ASP.NET web applications.

With traditional ASP.NET web applications, the application consists of a number of pages that are linked together by simple Uri's. In other words, the navigational structure of the application is based on visual elements linked together. With ASP.NET WebForms, the pages can be richly defined using server-side controls, client-side AJAX controls, and with MasterPages and so on, but the navigational structure is always based on pages and the ASP.NET runtime will create the pages as you navigate to them. You may optionally choose to separate the presentation or business logic from the UI by using an MVP pattern, but in this case, the Presenter will be constructed by the page itself.

On the other hand, using ASP.NET's MVC framework, we can define a navigational scheme that follows the logical structure of our application and that is independent of the visual pages within the application. By defining suitable navigation routes we will logically navigate to a controller component which then allows us to create a suitable view and hook it up to a data model component. We technically have controller-first composition, but hopefully you can see that this is the moral equivalent of constructing a ViewModel before the View.

In this latest drop of Helix, I’ve added support for both View-First navigation and ViewModel-First navigation by implementing a navigation controller for each. The rest of the Helix architecture remains essentially the same (though there are some new features and some fixes as detailed at the end of this post). Remember, you can always implement a custom controller if you want to change the implementation that’s described below.

Instead of walking through the implementation of these controllers, it’s probably more useful to walk through a sample application for each navigation style so you can see how they are both put together. In the examples below, I’m also using some of the new and improved features in Helix that are common to both styles of navigation.

Ok, enough theory, let’s see some code!

View-First Navigation

To illustrate View-First Navigation, I took the Order Entry sample application from the second post and converted it to use ViewModel pattern. You’ll remember that this sample was based on a navigation scheme where the links referred to the pages within the application, so it was relatively straightforward to keep that navigation scheme and introduce the ViewModel pattern into it. You can run the final application here. Let’s walk through the application so you can see how it all fits together…

Helix1The application consists of a number of Models, ViewModels and Views, plus a RootPage and an Application  class. The RootPage is a simple page with a Frame control – as we navigate between pages, they will displayed here.

The application uses three model classes to represent the customer, sales order and the sales order line items. In this sample these are just simple classes with a number of properties. These are all defined in the Models folder.

The ViewModels for the application are defined in the ViewModels folder. The ViewModels implement a number of commands and properties that the Views can bind to. The application’s pages are all defined in the Views folder. None of the pages have any code behind; all of the UI is defined declaratively in XAML. The pages bind against the ViewModel’s commands and properties.

All of these classes are connected together at run-time through navigation. The navigation scheme for the application is defined in App.xaml. With the latest drop of Helix, we can define the navigation routes, and associated controller and default parameter values, as an application resource. This allows us to define the navigation scheme for our application declaratively without having to write any code.

<n:RouteTable x:Key="GlobalNavigationRoutes">
    <n:Route UriTemplate="/[PageName]">
        <n:Route.Controller>
            <c:PageController DefaultResourcePath="Views" />
        </n:Route.Controller>
    </n:Route>
    <n:Route UriTemplate="/[PageName]/[CustomerID]">
        <n:Route.Controller>
            <c:PageController DefaultResourcePath="Views" />
        </n:Route.Controller>
    </n:Route>
    <n:Route UriTemplate="/[PageName]/[CustomerID]/[SalesOrderID]">
        <n:Route.Controller>
            <c:PageController DefaultResourcePath="Views" />
        </n:Route.Controller>
    </n:Route>
</n:RouteTable>

In this application we have three navigation routes. The first route defines no parameters just the page name, but the second and third routes add CustomerID and SalesOrderID parameters. Each route uses a PageController. The DefaultResourcePath tells the controller where to look in the application for the pages that we will navigate to.

The bulk of the application’s logic is defined in the ViewModel classes. The ViewModels implement a number of commands and properties and expose them to the UI for binding. Helix includes a number of features to help with View to ViewModel binding.

Simple properties exposed by the ViewModel are easy to bind to. In the case where the underlying data managed by the ViewModel is a collection (for example, a collection of customers), the ViewModel creates a CollectionViewModel class to wrap it. This class manages currency, selection and sorting of the underlying collection. The View and CollectionViewModel are kept in sync using the SynchronizeCollectionView attached behavior like this:

<ListBox ItemsSource="{Binding Customers}"
     h:SelectionChanged.SynchronizeCollectionView="{Binding Customers}">

My post here on CollectionViewModel describes in detail how this attached behavior works. I have now rolled the CollectionViewModel and the SynchronizeCollectionView attached behavior classes into Helix so everything is in one place.

The ViewModels also implement commands that the View can bind to. Commands are implemented using the Prism DelegateCommand class – see here for more information on Prism and Delegate Command pattern. Commands can be bound to UI elements using the Prism Command attached behavior. Command parameters can also be defined using the CommandParameter attached behavior.

<Button Content="Edit"
    prism:Click.Command="{Binding ViewOrdersCommand}"
    prism:Click.CommandParameter="{Binding Customers.CurrentItem}" />

In the example above, we’re binding the Edit button to the ViewOrders command and passing in the currently selected customer as a command parameter. When the user clicks the button, the command’s method will be invoked with the current customer as a parameter. If the Edit command is not available, the button is disabled automatically.

Many of the commands in the application result in a navigation. Commands which result in navigation are typically implemented like this:

private void ViewOrders( Customer customer )
{
    // Navigate to the Orders page.
    Uri navUri = new Uri( string.Format( "/Orders/{0}", customer.CustomerID ),
                          UriKind.Relative );
    _navigationContext.Target.RequestNavigate( navUri );
}

The Uri above is formatted in accordance with the navigation scheme that we defined in App.xaml. The Uri can include parameters such as the customer ID and these are passed to the target ViewModel when it’s created. This makes it very easy to pass parameters around during navigation. Since we have a View-First navigation application, we could also use the Helix NavigationLink control and navigate directly from the page.

The navigation context you can see above is passed to the ViewModel by the framework when it is first constructed as a result of navigation. You can use the navigation context class to get access to the navigation parameters, or to ask the navigation target to navigate to another Uri as shown above. The NavigationContext class is discussed in more detail below.

There are just a couple of final things that we need in order to stitch everything together. Since we’re using a View-First navigation controller, navigation Uris, such as the one above, specify the name of the page to navigate to. In the example above, we’re navigating to the Orders.xaml page in the Views folder. So far so good, but how does the framework know which ViewModel to create for this view?

There are a number of ways to solve this problem. Ultimately we need to know the Type of the ViewModel class so we can instantiate it. One way to get this type is to infer it from the type of the View – so, for example, a view with a type name of ‘MyApp.MyView’ would infer a ViewModel of type say ‘MyApp.MyViewModel’. This would work but means that we would have to know about the naming convention and the relevant namespaces and we would have to follow both carefully when creating our ViewModel classes.

Another approach, and the one that is implemented in this sample application, is to allow the View to explicitly specify the type of the ViewModel it was designed for. To do that we just use a simple attached property. The Customers page, for example, specifies that it needs an instance of the CustomersViewModel class like this:

<NavigationPage
x:Class="Microsoft.Samples.Helix.OrderEntrySample.CustomersPage" ... ViewModel.TypeName=
"Microsoft.Samples.Helix.OrderEntrySample.ViewModels.CustomersViewModel"
>

You can imagine some day in the far flung future, when the tooling folks finally embrace the notion of separated presentation patterns, that the ViewModel’s type could be automatically specified by the tool when the user is designing the view – maybe even as a proper Type parameter making the View a generic type, for example MyView<ViewModelType>. We can only hope that that day will come soon…

In any case, when the framework creates the View it checks to see if there is a ViewModel specified, and if so, it instantiates the ViewModel and sets it as the View’s DataContext. All of this is handled by the PageController which is described in more detail below.

The last piece of the puzzle is the navigation context. Once the View and ViewModel have been created and hooked up, the controller passes in the navigation context which contains the navigation parameters and a whole bunch of other stuff. The ViewModel (or the View) can opt to receive the navigation context by implementing the INavigationAware interface, which consists of a single method OnNavigate:

#region INavigationAware Members
 
public void OnNavigate( NavigationContext context )
{
    // Store the navigation context for later.
    _navigationContext = context;
    ...
}
 
#endregion

The ViewModel can then retrieve the parameters it’s interested and retrieve the relevant data to initialize itself.

The PageController Class Dissected

The View-First application described above uses the PageController class to handle navigation. This controller does all of the heavy lifting and stitches everything together. It carries out four steps in sequence:

Helix2

  1. The first step is to create the View. The View’s name is specified as a parameter as part of the navigation Uri, as defined in the navigation routes in App.xaml. The View is created by loading the resource, prefixed with the DefaultResourcePath if one is specified.
  2. The next step is to create the ViewModel. The ViewModel's type is specified using an attached property value on the View. If the View doesn’t specify a ViewModel type, this step is skipped.
  3. If a ViewModel has been created, the next step is to set the View’s DataContext to the it. This allows the View to binding to the ViewModels properties and commands.
  4. The final step is to set the navigation context on the View or ViewModel.

The last step probably needs some explanation. In part 2 of this series you may recall that we passed the navigation parameters to the target View using the INavigationPage interface. Now that we have ViewModel support, we probably don’t want to pass the navigation parameters to the page; we want to pass them to the ViewModel instead. In the latest drop of Helix, I have added a new interface INavigationAware that can be implemented by a View or a ViewModel (or both). The PageController checks to see if either the View or the ViewModel implements this interface and if so, calls the OnNavigate method, passing in the NavigationContext.

NavigationContext is a new class. It provides a single object from which to retrieve all of the information about the current navigation operation, including the navigation parameters, mode, Uri and target, etc. Most of the ViewModels in the sample application store a reference to the NavigationContext to use for initiating further navigation operations later on and for retrieving the parameters that they require.

The implementation of the PageController class described here is pretty simple. The strategy it implements is the one I settled on during my investigations, but you can easily change the implementation to suit your needs. For example, you can change the way in which the View or ViewModel gets created, or they way in which they get hooked-up, to whatever strategy you prefer. The beauty of the Helix framework is that you can make these changes in a single place without having to make multiple changes throughout the entire application!

ViewModel-First Navigation

OK, so much for View-First navigation. Let’s see what ViewModel-First navigation looks like…

To illustrate ViewModel-First navigation, I implemented a sample expense reporting application. You can run the application here. As described above, this application provides a number of tasks that the user can carry out. Each task will be rendered visually, so the user will experience these states through the UI, but to a large extent the tasks exist independently of how they are rendered.

The following diagram illustrates the tasks and the commands that lead to the transitions (navigation!) between the tasks. From the View Expense Reports task, for example, the user can create, edit, review, submit or archive an expense report; from the Edit Expense Report task the user can save the expense report and the application moves back to the View Expense Reports task.

Helix5

Helix3The structure of the project is similar to the Order Entry sample described above. It consists of three folders that contain the application’s Models, ViewModels and Views, a root page and an application class.

The essential difference between this application and the Order Entry application described above is that navigation occurs between ViewModels. Each ViewModel represents a task so the bulk of the application logic is defined in the ViewModels. Each ViewModel implements properties and commands similar to those described above.

The ViewModel folder also contains a couple of ViewModel helper classes that perform data formatting for expense amounts and dates. These classes aren’t ViewModels per se, but they are used by the Views to help them render the data correctly.

There is a corresponding View for each ViewModel, defined in the Views folder. Again, the views contain no code behind.

Ok, let’s see how all of this fits together. First, the application’s navigation scheme is defined in App.xaml:

<RouteTable x:Key="GlobalNavigationRoutes">
    <Route UriTemplate="/[ViewModelTypeName]/[ExpenseID]">
        <Route.Controller>
            <ViewModelController DefaultResourcePath="Views"
                DefaultNamespace="Microsoft.Samples.Helix.ExpenseSample.ViewModels"/>
        </Route.Controller>
        <Route.Defaults>
            <NavigationParameter ParameterName="ExpenseID" ParameterValue="-1" />
        </Route.Defaults>
    </Route>
</RouteTable>

This application defines a single route that has two parameters – the ViewModel type name, and the expense report ID. A default value for the expense report ID is specified, so the navigational Uri’s don’t necessarily have to specify it. This route uses the ViewModelController navigation controller class. This is the class that coordinates how the ViewModels & Views get created, hooked-up, and initialized with the navigation context.

The ViewModelController has two properties – DefaultResourcePath, which tells it where to look for Views, and DefaultNamespace, which specifies the default namespace for the ViewModel classes. The operation of this controller class is described below, but essentially it works by creating a ViewModel then a suitable View for it, hooks them up via the View’s DataContext and then sets the navigation context.

The interaction between the Views and the ViewModels is the same as described above and includes commands and the CollectionViewModel sync attached behavior. Navigation between tasks occurs as commands are invoked on the ViewModels. A typical implementation of a command looks like this:

private void CreateExpenseReport( ExpenseReport expenseReport )
{
    ExpenseReport newExpenseReport = _expenseReports.CreateNewExpenseReport();
 
    // Navigate to the Edit ViewModel.
    _navigationContext.Target.RequestNavigate( new Uri(
            string.Format( "/EditExpenseReport/{0}", newExpenseReport.ExpenseID ),
                           UriKind.Relative ) );
}

The format of the Uri is as defined in the navigation route in App.xaml. In the example above, we’re passing an expense report ID as a parameter to the target EditExpenseReport ViewModel. When that ViewModel is instantiated, the parameter will be passed in as part of the navigation context and the ViewModel can retrieve the corresponding expense report. In this way, we can control not only what gets instantiated during navigation, but also how parameters flow around the system. This really simplifies how applications like this are put together…

The ViewModelController Class Dissected

Hopefully you won’t be surprised to learn that the ViewModelController creates the ViewModel first and then creates a suitable View for it. The sequence goes like this:

Helix4

  1. In the first step, the ViewModel is instantiated using the ViewModelTypeName navigation parameter, prefixed with the DefaultNamespace if one is specified. So for a ViewModel type name of ‘EditExpenseReport’, the type ‘Microsoft.Samples.Helix.ExpenseSample.ViewModels.EditExpenseReport’ will be instantiated.
  2. The next step is to create a suitable View. The details of this step are described below. If a View can’t be instantiated, an exception is thrown.
  3. The next step is to set the View’s DataContext to the ViewModel. This allows the View to binding to the ViewModels properties and commands.
  4. The final step is to set the navigation context on the View or ViewModel.

In the View-First strategy described above we had the challenge of figuring out which ViewModel to instantiate for a given View. In ViewModel-First navigation we have the opposite problem – given a ViewModel, we have to decide which View to instantiate for it.

The current implementation takes a simple approach – we just append the ViewModel’s short type name with ‘View’ and load the corresponding View resource. So for the ‘EditExpenseReport’ ViewModel, we’d load the View ‘EditExpenseReportView’ located in the Views folder. This was an experiment to see how a naming-convention based approach would work.

There are other ways to solve this problem, but for the purposes of this sample, it works pretty well. You can always implement an alternate strategy in a custom controller class if you prefer a different way to create and hook-up the ViewModel or View.

End of Part 3

Well, that was a long post wasn’t it? We covered a lot of ground though. Since we’re building Helix from the ground up there are a lot of details to grok, and just like sausages and laws, it’s not always pretty seeing how things are made. The final framework, though, should be drop-dead simple to use – that’s the goal anyway!

We’ve been experimenting with alternate approaches to discover their advantages and disadvantages and to see which one might work as a default approach that will work for most applications. We’ve essentially identified two broad approaches that have potential and we can now build applications with a View-First navigational style, or with a ViewModel-First navigational style.

Which approach you use depends on your application and which approach feels most natural to you. The implementations described here work pretty well for both approaches but there are few things that need some improvement. The nice thing about Helix, though, is that it’s simple to implement alternate strategies or to tweak the behavior of the navigation scheme in an application. With a few changes here and there we can customize navigation without having to rewrite big chunks of our application.

Personally, I believe the ViewModel-First approach has a lot of advantages over View-First approach, but it takes some getting used to. The example above doesn’t really highlight the advantages of this approach in terms of testability and UI flexibility. I’ll try and focus on those in the next post in the series, as well as deep linking. I promise that you won’t have to wait as long for that post…

On another note, whatever approach we choose, there is always the ‘tooling problem’. In other words, what would the ideal tooling experience be like for building applications based on both a separated presentation pattern and a flexible navigation system? It’s not an easy question to answer. I have some ideas but they will have to wait for a future post too…

As always, please let me know what you think of Helix – what you like or don’t like, etc. If you have any feedback on Helix, please drop me a line.

oO------Oo

Helix 0.3: Changes and New Features

A quick summary of the main changes and new features in this drop of Helix:

  • Added support for global routes. Global routes are managed by the Navigation Manager and can be defined as an application-level resource in XAML. If not global routes are defined, a default global rout is added automatically. Frame-local routes can also be defined and are checked for a match first during navigation. If a match at the Frame level is not found, then the global routes are checked. This provides a lot of flexibility when implementing hierarchical navigation scenarios in an application.
  • Moved the page loader code to the static Navigation Manager class. Centralizing this code allows for multiple controller classes to take advantage of it (and allows for it’s ultimate replacement by the Silverlight framework itself if and when it supports the ability to load pages by resource name).
  • Removed the need to register the application’s main assembly with the Navigation Manager class. The Navigation Manager now searches all assemblies in the application manifest (except those beginning with System). This also the Navigation Manager to instantiate Views and ViewModels without the developer having to specify which assembly they are defined in, which in turn allows for easier integration between UI and non-UI application layering.
  • Default constructors added for Route and Journal classes. Using the default constructor for a Route object instantiates a default PageController instance. Similarly, using the Journal’s default constructor instantiates a default RouteNavigationHandler instance. These default constructors allow for simpler declarative setup in code or XAML.
  • NavigationParameter and related classes were also changed to support default construction and the ability to declaratively specify default values in Routes.
  • Refactored the regular expressions in the Route class to const strings to allow for easier customization. Also tidied up the regular expression for identifying fields in the navigation Uris. This allows you to more easily change which characters are allowed in navigation fields (e.g. you can now define fields that include period and dash, so you can use GUIDS for example).
  • Refactored all Controller and Journal classes into their own namespaces.
  • NavigationUIVisibility is now in the Helix Controls namespace.
  • Controller parameters – added the ability for a controller to specify its required parameters using an attribute. This allows the controller base class to automatically check incoming parameters to make sure that all required parameters have been provided. This simplifies error handling and the implementation of derived controller classes. This also allows for the associated Route object to check for a compatible controller when the Route is first registered.
  • Navigation Context – Added Navigation Context class which includes all of the information pertaining to the current navigation operation, including the navigation parameters, original Uri and the navigation target. This provides for a simple API, better extensibility and allows ViewModels to store a reference to their navigation context so they can initiate or initiate/cancel/redirect a navigation operation.
  • Added PageController and ViewModelController classes. Removed the NavigationPageController class (this functionality is now provided by the PageController class). The PageActionController class is now derived from the PageController class.
  • Added DefaultResourcePath property on PageController & ViewModelController to allow views to be loaded from a sub-folder in the project. The previous version of Helix required all pages to be defined at the project root level.
  • Added InitialUri dependency property on the Frame Control. This allows the Frame to navigate to the specified Uri when the Frame is first loaded, removing the need for code behind in the root page.
  • Added CollectionViewModel to Helix library. Also added a number of bug fixes in the Refresh and OnModelChanged method. The latter is required due to weird behavior with the Silverlight DataGrid control.
  • Added a unit test project with unit test for Routes, Navigation Manager, Page and ViewModel Controllers, CollectionViewModel, etc.
  • That’s all the changes I can remember…

A quick note on Silverlight 3.0 Beta: Helix and all of the associated samples are built for Silverlight 2.0. However, you should have no problem using Helix with the Silverlight 3.0 Beta. There are a few known issues in Silverlight 3.0 Beta to do with memory leaks but these probably won’t affect you too much and they’ve been fixed in later versions.

Mix 09!

mix09header

Mix 09 starts today! There have been a number of key announcements made at Mix, especially concerning Silverlight 3.0 and Blend 3.0. If you are at all interested in Web and Silverlight development then be sure to check out the "Gu's" keynote highlights here.

The next releases of Silverlight and Blend have lots of interesting features. I'll cover them in detail in a future post, but one question that I'm sure is top of mind is how the new version of Silverlight relates to Prism and Helix.

Silverlight 3.0 provides a lot of new features that are nicely complementary to Prism. These new features help with data validation, data forms, navigation and with accessing business entities over the network. Prism focuses on patterns for flexible, modular, loosely coupled, unit-testable applications. These patterns can of course be used in Silverlight 3.0 just as effectively as in 2.0. The combination of Prism and the new Silverlight features provide a very powerful platform for building line of business RIA applications.

We're planning the next release of Prism which will target Silverlight 3.0 (and WPF 4.0), so we're beginning to look at how we can evolve Prism to further integrate and complement Silverlight, Blend and WPF. We're especially looking forward to support the new Silverlight out-of-browser feature(!). So if you have any ideas on what you'd like to see in Prism 3.0, please send them our way!

You'll also see that Silverlight 3.0 now has some support for navigation! I was part of the team behind the navigation features in Silverlight 3.0 last year before moving to the patterns & practices team. My original design for Silverlight navigation was of course very similar to Helix. The design changed quite a bit since I left that team, specifically so that it is more compatible with WPF's navigation model. I'll be posting details on the differences between the two designs, the advantages and disadvantages of each, and how to use them together soon.

Prism 2.0 Refresh

We just posted a refresh to the Prism 2.0 bits. You can download the latest release from the same location on MSDN here.

The recent release of the GDR update to Silverlight 2.0 (which takes Silverlight from version 2.0.31005 to version 2.0.40115) causes a problem when building the Composite.Silverlight.Tests project. This issue only affects the unit tests and there is no change required to the core library or any of the quick-starts or the reference implementation. The issue was due to an incorrect path in one of the batch files in the unit test project. You can read more details on the issue here.

While we were refreshing the bits, we thought we'd also slip in a fix to a recently reported issue with view activation in tabbed regions. This issue caused a difference in behavior between Prism 1.0 and 2.0. You can read the details here. This issue has been fixed with the refreshed release.

We also just released a PDF version of the Prism 2.0 documentation so you can print it more easily. You can download the PDF file from here.

Coming Soon! We are working on Visual Basic versions of the quick-starts and documentation. I'll post more details once we've released these in the next week or so...

Prism 2.0 Is Live!

Prism2 StockTrader

WooHoo! Prism 2.0 is done and is now live on MSDN! You can access the Prism 2.0 documentation here, and download the code from here.

Prism is a library of patterns that help you build robust, flexible and modular WPF and Silverlight applications. These patterns also support unit testing, separation of concerns, loose coupling and the ability to share application logic between Silverlight and WPF applications. The download includes the source code for the library itself, extensive documentation, a sample application that shows how the patterns work together in a real-world application, and a whole bunch of quick-starts and how-to's. There's even a snazzy Visual Studio add-in to help you easily share code between WPF and SilverlightBlaine and Adam.

The Prism team has been busy writing blogs and recording videos to get the word out...

Blaine Wastell (program manager extraordinaire for Prism) chats to Adam Kinney about Prism on Channel 9 here. He's even written a blog post on Prism here.

If you haven't had enough Blaine you can catch even more of Blaine and Bobhim here on Channel 9, alongside Bob Brumfield (one of the developers of Prism), as Ajoy Krishnamoorthy (our product manager) ponders the eternal question - What is Prism? Ajoy's post on the release is here and Bob's is here.

Still hungry for more information on Prism?

Check out Erwin's post here, and Julian's post is here. Erwin and Julian were part of the super-talented Prism development team. Expect more videos and posts from the dev team on how to use the various super-cool features of Prism soon.

And last but by no means least, Prism's test lead Larry Brader has a post here.  Larry's going to be delivering a whole series of posts that will tell you everything you ever wanted to know about unit testing and acceptance testing in WPF and Silverlight, so be sure to check his blog often.

Master-Detail With CollectionViewModel

Implementing a Master-Detail style UI with the CollectionViewModel I described in my previous post is pretty easy. With a selector control bound to a CollectionViewModel as shown in my previous post, you just need to add a content control to the View and bind its Content property to the current item and define how you want it to be rendered by defining a data template.

For the sample in my previous post the view's XAML contains this:

<ContentControl Content="{Binding Path=Catalog.CurrentItem}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            ...
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

Note: In WPF, you strictly only need to bind the content control's Content property to the Catalog - WPF automatically binds to the Catalog's current item for you. Not sure why they did it this way. I think an explicit binding to the CurrentItem property is easier to understand, and I don't mind typing the extra characters. Sometimes a little more is definitely more :-)

You can run the updated sample here and download the updated source here. I also updated it to use the final release assemblies from Prism 2.0, and fixed a glitch in the Silverlight Unit Testing assembly references...

More Posts Next page »
Page view tracker