(X) Hide this
    • Login
    • Join
      • Say No Bots Generate New Image
        By clicking 'Register' you accept the terms of use .

WinRT Business Apps with Prism: Getting Started

(5 votes)
Brian Noyes
>
Brian Noyes
Joined Jun 10, 2010
Articles:   19
Comments:   117
More Articles
12 comments   /   posted on Feb 20, 2013


 

UPDATE: This article was updated from the original version because the name of the guidance changed from “Kona” to “Prism for Windows Runtime” after initial publication. The content has not changed in the update other than the name of the guidance and the namespaces in the code.

This is Part 1 in the series WinRT Business Apps with Prism.

Introduction

Even if you are an experienced XAML developer, to be successful building business applications for the Windows Runtime (WinRT), you can't just start slinging code in the code behind of pages and let your application evolve into a pile of new spaghetti code. You need to focus on maintainability and testability of your application. You need loose coupling and separation of concerns. But if you get started by looking at the samples and documentation that comes with the platform, you will have a hard time figuring it how to get started with that.

Luckily someone has already blazed a trail for you - Microsoft patterns & practices (p&p). For the last 6 months or so I have had the privilege of working as a member of the p&p team whose charter is to provide guidance for line of business XAML developers starting to build Windows Store applications. This project was originally code named "Kona", but was renamed for release to Prism for Windows Runtime.  I will be referring to the code and samples and documentation that comes with the guidance collectively as "Prism" for short, but just realize I am referring to this new variant of Prism targeting WinRT apps, not Prism 4 which targets WPF and Silverlight apps. For Prism 4 you can check out my other article series Working with Prism 4.

In this article series I will be showing you everything that Prism has to offer to help you build your WinRT application right, to leverage the reusable code of Prism, to follow the coding patterns of Prism where no reusable code exists, and to leverage the features of the platform that most business applications will need to integrate with. A lot of these same things can apply whether you are building a game, productivity app, or line of business applications that only employees of your company will use. But the main focus of the guidance is for line of business applications including internal business applications (which will probably be side loaded and never go in the Windows Store, but are still referred to by Microsoft as “Windows Store apps”) as well as business-to-consumer applications where the end users of your application are mostly outside your control as the development organization.

You will learn about structuring your application with MVVM, navigation, application state management, loosely coupled communications, validation, calling Web APIs, and leveraging platform features including Settings panels, Search charm integration, Live Tile updates, Toast Notifications, Roaming Settings, and more. I will do this mostly by building out a Windows Store application in the series, but for the things that are a little too involved to build up in a single sample, I will end up pointing to some example code in Prism.

This is not a introductory tutorial in building Windows Store applications. I am assuming you have already had some exposure to the WinRT platform, Windows Store applications, and have some experience building XAML applications. I also expect you have some exposure to the MVVM pattern, its goals and structure. If you want a good comprehensive overview of all of these, check out my Pluralsight course “Building Windows 8 MVVM XAML Apps”. I also will have a Pluralsight course titled Building Windows Store Business Apps with Prism out by June 2013.

Prism Guidance Overview

A big part of the Prism guidance is a realistic sample application, the AdventureWorks Shopper application. This is referred to as a "Reference Implementation" (RI) by p&p. It is more than your average sample application, it is a complete end to end application that represents the kind of applications many businesses will need to build for WinRT, whether they deploy through the Windows Store to consumers or whether they deploy through side loading in the Enterprise. In building the AdventureWorks Shopper RI, the p&p team constantly looked for opportunities to write code in a reusable way so that developers could not only learn from the code of the application , they could also use some of the common code we were writing. The result of that is a library called Microsoft.Practices.Prism.StoreApps that is part of the Prism download that you can reuse in your own applications. There is also a separate reusable library called Microsoft.Practices.Prism.PubSubEvents that I will cover in a later article in the series. The RI also includes extensive unit and integration tests that you can use to learn how to write tests for your own application. Additionally, Prism comes with several Quickstart applications that demonstrate distinct features or capabilities of Prism in isolation, including a Hello World, Validation, PubSubEvents, and Search. Finally, there is fairly comprehensive documentation of the RI and Quickstarts that can walk you through that code.

There is a conceptual tie between Prism for Windows Runtime and Prism 4. Prism 4 was a previous set of guidance from Microsoft p&p focused on building loosely coupled, maintainable, and extensible desktop client applications with WPF and Silverlight. Some of the same concepts and even a tiny bit of the code was carried over where appropriate, but from the outset the goal of Prism was not to just port Prism 4 to WinRT, it was to build a good set of guidance for WinRT XAML applications without presuming that you should build WinRT applications in any way similar to WPF or Silverlight.

One thing that was definitely carried over in concept was the presumption that we would be focused on writing maintainable code. That meant we wanted to make sure that the core logic of our application would be unit testable and well factored. We wanted the code that supported one view to be decoupled from the code that supported another view. That of course led us quickly to plan on using the Model-View-ViewModel (MVVM) pattern that is common in WPF and Silverlight and that was also used in Prism 4. But we also quickly found that the WinRT platform is substantially different in the way you go about doing MVVM and we had to come up with a number of new things that our view models were responsible for - including integrating nicely with the WinRT navigation system and with the application lifecycle and state management of the platform.

So this series of articles will help you explore the concepts covered in Prism by demonstrating them in code.

At the time of writing this article, the Prism team is in the process of getting Prism for Windows Runtime ready for release. However, the current source code for Prism is available as open source and can already be downloaded from http://konaguidance.codeplex.com.

Getting Started

I have to start somewhere, so the most logical place to start is the same place you will – with a blank slate. In this article I will show you how to quickly put together a new application based on the Prism reusable class library (Microsoft.Practices.Prism.StoreApps). The code I write in this article will be the stuff you will end up doing in probably every Windows Store application you choose to build leveraging Prism – specifically it will lay down the patterns that enable you to use the MVVM pattern, manage your dependencies, integrate with the navigation system, and manage your application state through your view models and application services. I won’t go into detail in this article on the navigation and state management – those are both big enough topics that I will get into those in the next couple articles in the series. This one will just get you bootstrapped on using Prism.

The scenario for the application I will be building up over the series is for a line of business worker whose job it is to take sales order calls and enter the sales. They may also need to look up past sale information, product information, and enter and modify customer information as part of their normal job task.

Step 1: Create a Windows Store Application

The first step is to open Visual Studio 2012  and create a new Windows Store Application. Select the Blank application template, and name the project HelloPrismForWinRT.

Figure1

After the project is created, you have a single page in the application named MainPage with no content to it.

Step 2: Create a couple Pages and ViewModels

In a Windows Store application, you design your application around Pages. The user navigates from Page to Page to get to all the functionality in your application. Your Pages are your top level Views from an MVVM sense, and you will set up ViewModels to support them. You might have views that are children of the pages – for example you could have a ContentControl within a page that you swap different child views into as the content. But this kind of composition is much less common than it was in WPF and Silverlight because of the Modern UI style guidelines – you should be keeping things a lot less dense than traditional line of business applications have tended to in the past, and spread the functionality of the application over multiple pages that the user navigates between instead of doing everything in one big complicated view.

Prism uses convention over configuration for a number of things. There is a ViewModelLocator class that makes it really easy to get views (Pages primarily) wired up to their ViewModels following the conventions of MVVW. This ViewModelLocator has a default convention that assumes you will put your Pages in a subfolder of the project named Views, and your ViewModels in a subfolder named – you guessed it – ViewModels. If you don’t like that convention, there are hooks to put them wherever you want.  But a lot of the reusable code of Prism is designed around doing things based on common patterns, and if you follow those patterns you have less work to do in getting your application up and running.

So to start structuring things this way, delete the MainPage.xaml that was added to the root of the project by the template. Add two project folders: Views and ViewModels. Next, right click on the Views folder and select Add > New Item from the context menu. In the Windows Store category, select the “Basic Page” item template and name the first one “MainPage”.

Figure2

When you click Add, you will be prompted to add some common files to your project that Visual Studio wants to add for every Windows Store application. Go ahead and click Yes, even though in the end we won’t use most of those classes – there are Prism equivalents that fit better with the MVVM pattern that we will use instead.

Figure3

Go into the XAML of MainPage and change “My Application” to “Hello Prism” in the resources section.

Repeat Add > New Item to add a second Basic Page named AddSalePage to the Views folder.

Now you can see we have some duplicate resources in the different pages declaring the application name.  I moved those up into the App.xaml resources dictionary and removed them from each of the pages to eliminate the duplication.

   1: <Application.Resources>
   2:     <ResourceDictionary>
   3:         <ResourceDictionary.MergedDictionaries>
   4:             <ResourceDictionary Source="Common/StandardStyles.xaml" />
   5:         </ResourceDictionary.MergedDictionaries>
   6:         <x:String x:Key="AppName">Hello Prism</x:String>
   7:  
   8:     </ResourceDictionary>
   9: </Application.Resources>

Next add two classes to the ViewModels folder: MainPageViewModel and AddSalePageViewModel. At this point, your project should look like this in Solution Explorer:

Figure4

Step 3: Add Microsoft.Practices.Prism.StoreApps to your solution

Now it is time to get Prism involved. If you haven’t already, go download the Prism bits from http://konaguidance.codeplex.com. It is a self extracting executable that will unpack all the samples and code to a local folder. I extracted mine to the same root solution folder that was created when I created the project so that the references can remain local and I can just zip things up for the samples.

Once you have done that, go ahead and add the Microsoft.Practices.Prism.StoreApps project to your solution – right click on the solution root node in Solution Explorer, select Add > Existing Project, and navigate to the Microsoft.Practices.Prism.StoreApps project in the extracted code from Prism. This is a Windows Store Class Library project that contains all the classes that were designed for direct reuse in Prism. I will be using base classes for our application, views, and view models from it.

Once you have added the project to your solution, add a reference to Microsoft.Practices.Prism.StoreApps to your HelloPrismForWinRT application.

Step 4: Replace the App base class with MvvmAppBase

The App.xaml.cs code behind of your App.xaml file in the project contains the definition for the App class – which derives from the WinRT Application class by default. It also has a bunch of code in there for managing the lifetime of the application, creating the first view, handling suspension and some other stuff. All of this has been encapsulated into the MvvmAppBase base class with some overridable methods for the hooks that you may need to customize on an application by application basis.

So strip out all the code in the App class except the constructor that calls InitializeComponent, and change the base class to inherit from MvvmAppBase. You will also need to override OnLaunchApplication and navigate to the main page using the NavigationService that is exposed from the base class. Note that there is also an OnLaunched base class method that you should not override.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using Microsoft.Practices.Prism.StoreApps;
   5: using Windows.ApplicationModel.Activation;
   6:  
   7: namespace HelloPrismForWinRT
   8: {
   9:     sealed partial class App : MvvmAppBase
  10:     {
  11:         public App()
  12:         {
  13:             this.InitializeComponent();
  14:         }
  15:  
  16:         protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
  17:         {
  18:             NavigationService.Navigate("Main", null);
  19:         }
  20:     }
  21: }

Note that I am overriding the OnLaunchApplication method in the App class. This is an abstract method in the base class and the minimum thing you need to do in this override is what I am showing here: you need to navigate to the right initial view for your application. For a “cold start” of your application, that means navigating to whatever the “main” page of your application is. But keep in mind that your Windows Store application can be launched in a number of ways, including being launched as a target for a Search charm operation, a secondary tile on the Start screen, or even an application protocol mapping launch. In these cases you might need to navigate somewhere different based on the launch arguments that come into this method. To make that more clear, MvvmAppBase has other overrides for handling search or settings activations. But for now just going to the MainPage from the OnLaunchApplication override is good enough.

Note that we navigate to “Main”, not MainPage as a type. This was a design decision we made in Prism that navigation requests like this should not be coupled to the specific type of the view or page. Keep in mind that if you are really planning your application appropriately, you will first storyboard or wireframe out what the pages are in your application and what the navigation between them is. You will probably define logical names for the views even though you probably won’t have decided on specific type names for the views at that point, even though they will most likely start with type names that are those view names + Page. Nor should you couple code that (as you will see in a future article) will often live in a decoupled view model to a specific view type. So the convention used for navigation in Prism by default is that you navigate to a  logical view name, and it assumes that the type name is that logical view name + Page.

If this is not your convention, you can override a method on the MvvmAppBase class named GetPageNameToTypeResolver. This method returns a Func<string,Type>, so you are expected to return a delegate that points to a method that takes in a logical view name and returns a type. So for example if you wanted to adopt a convention where you would navigate to views based on their view type name, and they would live in the application root namespace + “.Views”, you would define a GetPageNameToTypeResolver that looks like this:

   1: public override Func<string, Type> GetPageNameToTypeResolver()
   2: {
   3:     return (viewName) =>
   4:         {
   5:             var rootNamespace = this.GetType().Namespace;
   6:             var viewNamespace = rootNamespace + ".Views";
   7:             return Type.GetType(String.Format("{0}.{1}", viewNamespace, viewName));
   8:         };
   9: }

 

But I won’t do that in the sample application, I’m going to stick to the Prism conventions that the page token is simply the Page type name with Page left off.

Next open the App.xaml file and replace the root element opening and closing XML elements with ones that use the MvvmAppBase base class, as well as adding a XAML namespace for Microsoft.Practices.Prism.StoreApps:

   1: <prism:MvvmAppBase x:Class="HelloPrismForWinRT.App"
   2:              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:              xmlns:prism="using:Microsoft.Practices.Prism.StoreApps"
   5:              xmlns:local="using:HelloPrismForWinRT">
   6:  
   7:     <Application.Resources>
   8:         <ResourceDictionary>
   9:             <ResourceDictionary.MergedDictionaries>
  10:                 <ResourceDictionary Source="Common/StandardStyles.xaml" />
  11:             </ResourceDictionary.MergedDictionaries>
  12:             <x:String x:Key="AppName">Hello Prism</x:String>
  13:  
  14:         </ResourceDictionary>
  15:     </Application.Resources>
  16: </prism:MvvmAppBase>

At this point you should be able to launch the app and land on a totally underwhelming main page that says Hello Prism.

Step 5: Change the Page base class to ViewStateAwarePage

Prism has a base Page class that is similar to the LayoutAwarePage that Visual Studio injects, but it is just about layout and not state management and navigation. In an MVVM application, you really want the navigation and state management code to live in the ViewModel, so the Prism ViewModel base class takes care of those responsibilities, which we will hook up in the next step.

For the Pages, replace LayoutAwarePage as the base class in both the XAML and the code behind, with the addition of a corresponding XAML namespace like we did in the App.xaml:

   1: <prism:VisualStateAwarePage x:Name="pageRoot"
   2:                             ...
   3:                             xmlns:prism="using:Microsoft.Practices.Prism.StoreApps">
   4: ...
   5: </prism:VisualStateAwarePage>

You can also strip out all the other code in the code behind of the Pages other than the constructor with the InitializeComponent call:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using Microsoft.Practices.Prism.StoreApps;
   5:  
   6: namespace HelloPrismForWinRT.Views
   7: {
   8:     public sealed partial class MainPage : VisualStateAwarePage
   9:     {
  10:         public MainPage()
  11:         {
  12:             this.InitializeComponent();
  13:         }
  14:     }
  15: }

Make sure to make this same change for both MainPage and AddSalePage, and for each Page you add to the app after that.

Any reader with experience in MVVM should already be giving a little sigh of relief – yes, you can stick to almost zero code in the code behind, even in the Windows Store world.

You’ll need to get rid of one thing that is in the Basic Page template by default – it has a button wired up in the header for the GoBack navigation action, and it expects to find a Button.Click handler named GoBack in the code behind of the view. So in both the MainPage.xaml and AddSalePage.xaml, locate this code and remove the Click handler. Change this:

   1: <Button x:Name="backButton"
   2:         Click="GoBack"
   3:         IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}"
   4:         Style="{StaticResource BackButtonStyle}" />

to this:

   1: <Button x:Name="backButton"
   2:         Style="{StaticResource BackButtonStyle}" />

 

Step 6: Add the ViewModel base class to the ViewModels

Add a base class to the view models of ViewModel from the Microsoft.Practices.Prism.StoreApps namespace:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using Microsoft.Practices.Prism.StoreApps;
   5:  
   6: namespace HelloPrismForWinRT.ViewModels
   7: {
   8:     public class MainPageViewModel : ViewModel
   9:     {
  10:     }
  11: }

We won’t actually be doing anything in this article where it makes any difference what the view model base class is, but we will in future articles in the series, and in general when you are building out a Prism-based MVVM application, you will want to inherit from ViewModel for the Page view models so that you can integrate with the navigation and application lifecycle state management that I will cover in the next couple articles.

Step 7: Add the ViewModelLocator to the views to hook up their view models

Prism defines a reusable ViewModelLocator that can be used to hook up views and view models. It can do this automatically based on conventions, you can provide it factory methods that map a given view type to a given view model type, or you can override the default conventions of the ViewModelLocator to use your own conventions.

The default conventions of the ViewModelLocator are that for a given View type, it will assume the view is defined in a “.Views” child namespace off the project root or a sub-namespace, and the view model type has the same type name of the View plus “ViewModel” on the end of it and lives in a sibling “.ViewModels” namespace to the view. And this is precisely the folder and namespace structure I had you set up by adding the Views and ViewModels project folders in Step 2.

The way you use the ViewModelLocator from Prism is through an attached property on the view root element. So add the view model locator to the MainPage and AddSalePage root elements like so:

   1: <prism:VisualStateAwarePage ...
   2:                             xmlns:prism="using:Microsoft.Practices.Prism.StoreApps"
   3:                             prism:ViewModelLocator.AutoWireViewModel="True">

The ViewModelLocator will take care of creating an instance of the view model type for this view instance, and will also set the view model as the DataContext for the view, which is standard MVVM structuring.

After you have added this to MainPage.xaml, you could add a default constructor to MainPageViewModel and you should see that the constructor gets called as the app starts and navigates to the MainPage.

So at this point you should be able to fire up the application, and you have MVVM structuring and you could start fleshing out your views and view models to do some more meaningful work. To do much more, we need to get into navigation a little deeper, as well as managing dependencies. For example, the next logical step is to add a button to the MainPage that will let us navigate to the AddSalePage. But to do that in an MVVM way, we should fire a command from the button into the MainPageViewModel and control the navigation from there. That requires commands, some sort of Navigation service, and dependency injection of that service into the view model. It’s all there in the Prism code, and I’ll cover it in the next article. But that is all I have room for in this installment. For those that can’t wait for the next article, you could go check out the HelloWorld Quickstart in the Prism bits. It covers some of the same stuff I will get into in the next article that lets you get to the point of controlling navigation in your view models.

You can download the completed code for this article here.

Summary

In this article I introduced you to the concepts behind the Prism guidance from Microsoft patterns & practices. I showed you how to create a simple application based on Prism, using the Prism MvvmAppBase class, VisualStateAwarePage, and ViewModel base classes. I also used the ViewModelLocator to get the views and view models hooked up to one another.

Next time I’ll show you how you can use factories to construct the ViewModels so that you can inject dependencies into them manually, or how to instead use a container such as Unity to do Inversion of Control and Dependency Injection through a container to resolve dependencies when your view model gets constructed. You’ll see how to use Prism’s DelegateCommand, which is a ported version of the Prism 4 DelegateCommand it was based on, and you’ll also see how to have the view model know when it is navigated to, as well as how to control navigation.

About the Author

Brian Noyes is CTO of Solliance (www.solliance.net), a software development company offering Architecture as a Service, end-to-end product development, technology consulting and training. Brian is a Microsoft Regional Director and MVP, Pluralsight author, and speaker at conferences worldwide.  Brian worked directly on the Prism team with Microsoft patterns and practices. Brian got started programming as a hobby while flying F-14 Tomcats in the U.S. Navy, later turning his passion for code into his current career. You can contact Brian through his blog at http://briannoyes.net/ or on Twitter @briannoyes.


Subscribe

Comments

  • ChrisBordeman

    Re: Windows Store LOB Apps with Kona: Getting Started


    posted by ChrisBordeman on Feb 22, 2013 10:25
    This was useful, thanks!  When can we expect part 2?
  • brian.noyes

    Re: Windows Store LOB Apps with Kona: Getting Started


    posted by brian.noyes on Feb 22, 2013 15:54

    In about a week. I will be publishing the articles about once every two weeks.

  • RichardWakefield

    Re: WinRT Business Apps with Prism: Getting Started


    posted by RichardWakefield on Jun 28, 2013 08:00

    Great article, very easy to follow.  And I'm loving your other training courses on Pluralsight too Brian.  Did you get round to Part 2?  I'm eager to continue reading :D

  • brian.noyes

    Re: WinRT Business Apps with Prism: Getting Started


    posted by brian.noyes on Jun 28, 2013 16:44

    Richard,

    Parts 2,3,4, and 5 are linked in the right margin of this article.

    I'm planning one more part on server validation to finish up the series.

  • RichardWakefield

    Re: WinRT Business Apps with Prism: Getting Started


    posted by RichardWakefield on Jun 30, 2013 01:25

    Thanks!  I'll take a look now.

  • KyleChang

    Re: WinRT Business Apps with Prism: Getting Started


    posted by KyleChang on Aug 20, 2013 05:06
    Could you put this series into Microsoft Virtual Academy?
  • ken1

    Re: WinRT Business Apps with Prism: Getting Started


    posted by ken1 on Mar 17, 2014 10:17

    Hi Brian,


    Good article. What I am finding with your app as with mine is that when the user closes the app by dragging I down to the bottom of the screen, then launching the app again,  none of the state is restored. Is there something else we must do with the PRISM framework? BTW I'm using windows 8.1.

  • brian.noyes

    Re: WinRT Business Apps with Prism: Getting Started


    posted by brian.noyes on Mar 17, 2014 14:16

    Hi Ken,

    You have to get to the third article in the series and it's sample code before I cover the hooks to retain state when you shutdown.

    Brian

  • UsamaFaisalKhatri

    Re: WinRT Business Apps with Prism: Getting Started


    posted by UsamaFaisalKhatri on Jul 07, 2014 15:04
    Really nice article. I was expecting an article of this high stature from you quite a weeks ago. And you are delivering that article now. A bit disappointed I am but, the fact that this article is really good has finished off my disappointment. Bravo! kontorimööbel

  • UsamaFaisalKhatri

    Re: WinRT Business Apps with Prism: Getting Started


    posted by UsamaFaisalKhatri on Jul 08, 2014 23:05
    Fantastic article this is. When I compare this article to the other articles that I've read over the past few weeks, this article beats all of them with a big margin! Brilliant work! manifestation miracle
  • UsamaFaisalKhatri

    Re: WinRT Business Apps with Prism: Getting Started


    posted by UsamaFaisalKhatri on Jul 10, 2014 23:39
    I have never seen a post of this high magnitude in all my life time. I am really just shocked and impressed to my utmost extent by this post. I really am! Wow! Just keep giving posts like this. I always admire your work. gambling with bitcoins
  • hclcdc1

    Re: WinRT Business Apps with Prism: Getting Started


    posted by hclcdc1 on Jul 29, 2014 09:21
    Well for the information that will be good.
    best institution of life sciences

Add Comment

Login to comment:
  *      *       

From this series