Composite Applications
Source code, documentation and UML diagrams: http://SolrContrib.CodePlex.com
See Video clip of application discussed in this blog HERE

Prism developers wanting to build composite Metro style applications for the enterprise environment will be faced with some challenges; it could be some time before the Patterns and Practices (P&P) teams can update the projects we rely on, i.e., Prism and Unity. In the absence of such tools we’ll need to roll our own extensible, maintainable and scalable framework comparable to what we were accustomed to. Fortunately, the P&P teams provided guidance that has proven to withstand the test of time (even in a highly agile environment); looking to meet the challenge I rolled up my sleeves and used their Microsoft Application Architecture Guide (MAAG) (http://AppArchGuide.CodePlex.com) to build a framework that complied with most, if not all, of the principles it contains. The resulting framework (that this article is based on) is available in the open source project http://SolrContrib.CodePlex.com (change set 96548). The Gwn.DataBinding.Demo application (a proof of concept) resides within the solution, it looks and feels very much like Prism and uses a “Unity like” Inversion of Control (IOC) container that is based on Ian Randall’s open source project at http://metroioc.codeplex.com/; without his IOC container this undertaking would not have been feasible. Note: I added the IUnityContainer interface to his container, pulled in the Unity unit test and performed test driven development (TDD) until I achieved basic functionality. Once completed, I was able to pull in the Prism classes that supported event aggregation and commands so that I could perform TDD using Prisms unit test.
The MAAG architecture guide, published in 2009, is best described by the reputable Microsoft personnel involved in its creation:
The purpose of the guide is to help solution architects and developers to design and build applications on the Microsoft platform that are more effective, to support key decision making at the early stages of a new project, as well as providing topic-specific content to help architects and developers improve their existing solutions. This guidance incorporates the contributions and reviews from more than 25 external experts and customers. - S. Somasegar, Senior Vice President of Developer Division
The guide is based on a number of key architecture and design principles that provide structure. It includes guidelines for identifying and dealing with key engineering decisions, and an explanation of the quality attributes, crosscutting concerns, and capabilities that shape your application architecture; such as performance, security, scalability, manageability, deployment, communication, and more. - Scott Guthrie, Corporate Vice President of .NET Developer Platform
The field of application architecture and design is dynamic and constantly evolving. The foundations on which successful solutions have been built in the past will continue to serve us well into the foreseeable future, but we should also expect that the pace of innovation, in both technologies and new design approaches, will not decrease. The Microsoft platform and the .NET Framework and the range of technologies and scenarios that they support are both deep and wide, and getting deeper and wider all the time. On the other hand, we don’t need to wait for what might be. We can build compelling valuable solutions right now, and hopefully this guide will help you do just that. - David Hill, patterns and practices, September 2009
Since data binding is the basis for communications between the WPF View and ViewModel it seemed an appropriate (necessary) place to start with my new enterprise composite framework. I downloaded the Windows 8 Developer Preview DataBinding sample project (not available in the Beta) and used it to create the business rules that would be used by my first Metro application. I would take the seven scenarios and apply the “Key Design Principles” as outlined in Chapter 2 of the MAAG. It is beyond the scope of this article to cover all of the design principles covered by the MAAG, but I will cover the basics of the more applicable principles. Note: you will find that I quote the MAAG throughout this article.
I started with “Minimize upfront design”, a seemingly under-rated topic with agile development but something I firmly believe in. I was pleased to find the UML architectural tools readily available within Visual Studio 2011 developer preview. Within the guidelines set I came up with the following design (figure 1) which clarified the shared and overlapping responsibilities for the seven scenarios in the Microsoft DataBinding sample project. The use case diagram adequately covered separation of concerns, single responsibility principle, principle of least knowledge, and don’t repeat yourself (DRY) principles discussed on page 11 of the MAAG. The diagram also served as a means to conduct a gap analysis which will provide an understanding of what the existing application does while outlining the components required for the new design.

Figure 1 Sample overview
Within the spirit of “The Composite Approach”, as outlined by chapter 1 of the Prism 4.0 – November 2010 guidance, that states the following:
An effective remedy for these challenges is to partition the application into a number of discrete, loosely coupled, semi-independent components that can be easily integrated together into an application “shell” to form a coherent solution. Applications designed and built this way are often known as component application
My shell (MainPage.xaml in Figure 2) will have a MenuRegion, MainRegion and StatusBarRegion. The MenuView and StatusBarView will always be visible with only the active scenario being visible at any given time within the MainRegion. The framework will be responsible for loading the seven modules, MenuModule, and StatusBar module’s views into their respective regions while providing a decoupled means of communication between components (using IOC event aggregation); more specifically communication between layers, each scenarios presenter with the status bar presenter, and Menu events.

Figure 2 MainPage.xml
Where both the Model-View-Presenter (MVP) and Presentation Model (MVVM) patterns are discussed in the MAAG I opted for the MVP approach as it is one I learned early in my Prism design (reference my MSDN article on MVPVM at MSDN for more details). In Figure 1, I breakdown the MVPVM triad for the Menu, Status bar, and Scenario 6 (in Figure 1) showing their relationship with the Business Logic Layer (BLL) and Data Access Layer (DAL) so that I can “be explicit about how layers communicate with each other”.
To comply with the guideline “Do not overload the functionality of a component” while applying the single responsibility and separation of concerns it encompasses, it was important for me to breakdown the responsibilities of the various ViewModels as shown in figure 3. All of the scenarios have a reset button thus all ViewModels will derive from ResetViewModel. Since scenarios 1 and 2 don’t have properties to bind to they will have instances of ResetViewModel. Likewise scenarios 4 and 5 do not have properties outside of those available on ScenarioViewModel so each will have an instance of it. Scenarios 3, 6 and 7 have unique requirements so each will have to have their own ViewModels.
The application of the above noted principle allows us to easily reuse available components making it the responsibility of the presenters to populate the ViewModels or handle reset button commands as applicable.

Figure 3 ViewModel overview within the context of their MVPVM triads
With the basic high-level architecture out of the way I could then get to the business of data binding. Although the original DataBinding sample project didn’t provide a “last reset” time stamp, I figured I’d add this feature and placed the property on my ResetViewModel as shown in figure 4 line 26. Note that unlike the DataBinding sample I don’t subscribe to the “Click” event of the button (from code-behind) instead I use the Command and CommandParameter (lines 11 and 12 in top pane of image 4). The ResetViewModel will derive from the Gwn.Library’s MvpVmViewModel in an effort to “use abstraction to implement loose coupling between layers”. The MvpVmViewModel wires-up the command (line 50 of figure 5) which will raise a ProcessEvent (line 105 of figure 5). Each ViewModel simply notifies the application it was clicked – it doesn’t concern itself with subscribers of the event allowing it to remain loosely coupled.

Figure 4 Reusable ResetButton control and its respective ResetViewModel ViewModel

Figure 5 MvpVmViewModel base class; command, wire-up and handling (publish)
Presenters that are interested in the Reset button click event need only override the GenericCommandLocalHandler method (a function of a shared ScenarioPresenter base class) and handle it as applicable. For example in figure 6 we show that Scenario 1 will use Passive MVP to directly reset the three view sliders to default values. We all are aware that we could use data binding (slider to ViewModel properties) however the exercise of this application is to honor the intent and business rules of the original DataBinding sample which directly sets the view controls – this was another reason MVPVM was a good choice for this solution because this is not possible with Presentation Model as the ViewModel will not have a reference to the View.
I could have used a more traditional approach by creating a ResetCommand, versus reusing a GenericCommand property on the ViewModel, and in the presenter’s initialize method bind my button to a HandleResetCommand method in the presenter. Instead I opted to “define a clear contract for components” as they are reusable and I want to “establish a coding style and naming convention for development” that will “lead to better maintainability”, i.e. Without looking at my code you now know exactly where every reset button click is handled within each scenarios presenter; in the respective Presenter’s GenericCommandLocalHandler. Note: naming conventions dictate that a LocalHandler will only handle its modules button clicks versus overriding the GlobalHandler which handle “any” reset button click (any module).

Figure 6 Reset button handler
Now that we have a very high level understanding of the application and are armed with the knowledge that our Presenters will populate our ViewModels with data, wire-up event handling for event aggregation, and handle the reset button clicks in the applicable presenter’s GenericCommandLocalHandler (allowing our view’s to handle user interaction via the MVP Supervising Controller pattern), we need to discuss how the framework is bootstrapped (started up). A process that was recently changed with the Visual Studio 2011 Beta released, requiring me to perform a little refactoring to get the Gwn.Databinding.Demo application working again.
The traditional Prism approach to bootstrapping an application is shown in Figure 7 (pointed to by the arrow); we assign an instance of the view (implements IShell) directly to the Windows.Current.Content which gives us a hook into the process as we can instantiate the bootstrapper and allow it to load/initialize modules and return us a completely hydrated view (populated with its hierarchy of applicable views) before we assign it to Windows.Current.Content and activate it.

Figure 7 Bootstrapper process using Prism
In contrast, the new process used by Windows 8 has us instantiate a new Frame (reference line 50 in figure 8) and assign it to the Windows.Current.Content. Since line 51 expects a type we lost our hook that permitted us to provide an instance of the MainPage view; by line 54 the view will have been instantiated and is available within the Frame instance. Fortunately this challenge was not new to me because this is similar to how the Windows Phone 7 works. So this was a challenge I was forced to solve when I ported Prism and Unity to Windows Phone (Silverlight), my MSDN article on how to “Build Multi-Targeted Apps for the Desktop, Prism and Windows Phone 7” goes into this in more detail. My solution is shown in the sequence diagram in Figure 8. Unlike the rest of the framework, where the Presenters will be responsible for instantiating the views, I will have the main view (also known as the Shell) constructor instantiate the bootstrapper and run it, which in turn will populate the Shell’s regions (figure 2) with the applicable hierarchy of the applications views; a bootstrapping process I will cover in more detail below.

Figure 8 Bootstrapper sequence diagram
With the reusable components available it is now time to plug them into the enterprise solution. Our framework will use Prism concepts, this requires a Bootstrapper class to define the modules and register implementation for applicable interfaces - an excerpt from the Bootstrapper.cs is shown in figure 9. The BootstrapperBase class will iterate through the configured modules, execute the modules Initialize method and once completed will execute each modules ModulesInitialized methods. To understand the following code (which is essentially Prism and Unity) it is important to understand how Inversion of Control (IOC) works. Note: I have a blog on the topic of IOC at http://www.global-webnet.com/Blog/post/2011/10/13/Unity-Dependency-Injection-Primer.aspx if you require more information:


The configured modules in figure 9 start to reveal the power of enterprise composite application development. The Gwn.DataBinding.Demo application, which consists of nothing but reusable components, simply has to register available modules within the enterprise for the application. If Scenario1Module was a User Management module and I required it in another application I would simply add it to that enterprise applications bootstrapper. Perhaps the new application has different business rules for the existing User Management module since it will access the new Cloud data source – but only for the new application (so you can’t affect existing applications that use the module). You would simply have to register the applicable (different) business logic layers and data access layers as applicable, i.e. instead of EmployeeBll and EmployeeDal referenced in Figure 9 you might register the EmployeeCloudBll and EmployeCloudDal classes for the implementation of IEmployeeDll and IEmployeeBll respectively; as long as you implement the interfaces as required for the unit test to pass you can swap these out without touching the reusable modules which means no regression testing of existing applications since they have not been affected – no code was changed for them; only the new BLL, DAL and application have to be tested.


To further clarify the framework bootstrapper process we will cover how each of the modules configured in Figure 9 interact with the main shell so that our components identified in figures 1 and 3 can communicate with each other and function in a decoupled manner (each module can stand on its own and be reused within other applications).
Before continuing this would be an appropriate place to discuss “separation of concerns”. In a real world enterprise application I would not combine my Infrastructure, layers and modules within the same project.
For this demo the Infrastructure folder referenced in figure 10 holds the contents of what would normally reside in the Gwn.DataBinding.Infrastructure project; it contains components that are specific to this application which cannot be easily reused in other enterprise applications.
The layers folder, which contains the BLL and DAL components for the enterprise, would reside in either one or many projects depending on the enterprise, i.e. large enterprises may want to separate them into individual projects so that the smaller applications don’t have to pull in the “kitchen sink” to simply access a user module. The same holds true for the Modules folder and the modules that it contains.
Each of the module folders referenced in figure 10 contain a module component, this class is what the bootstrapper framework instantiates. It is the modules responsibility to instantiate the presenter(s) it will use and identify the module as a menu option if applicable. In figure 11 line 25 we show how “setter injection” can be used to instantiate the Scenario1Presenter (top pane of image) and “constructor injection” is used to instantiate the Scenario2Presenter (lower pane). You’ll find that the MainModule (bottom of figure 10) uses setter injection to instantiate both the Menu and Status bar presenters.

Figure 11 Setter and constructor injection of Presenters
It is then the Presenters responsibility to instantiate the view and ViewModel that it is addressing the concerns for. In Figure 12 we could have used the Presentation Model (MVVM) approach and placed the ModulesInitialized code (on line 36) within the ViewModel but then this would have tightly coupled our ViewModel to the concerns of this particular menu process which is to retrieve the menu options from the ModuleCatalog thus forcing us to violate the “separation of concerns” and “do not overload the functionality of a component” principals defined in the MAAM. Instead we can reuse an existing MenuView (shown in Figure 12) and our implementation for IShellViewModel which in this case was configured in our bootstrapper (figure 9) to use the ShellViewModel, neither of which have any knowledge of the ModuleCatalog or each other. Our MenuPresenter (figure 12) may be the only presenter within any enterprise application that chooses to use the ModuleCatalog for these shared resources. Note how the ModuleCatalog on line 23 of figure 12 has no dependency on any implementation of IModuleCatalog; we are using the frameworks default implementation but could easily replace it at the framework, application or module levels by simply registering our new implementation – our presenter will use the default (or new implementation) as applicable. This feature of IOC composite applications allows us to have full control over our individual modules (using shared components) without impacting or creating dependencies on those shared components.

Figure 12 Menu presenter and view
Scalability and maintainability of enterprise solutions are not the only benefits of composite applications. You also have high velocity extensibility even in the face of inexperienced (new) developers in an environment that is notorious of high learning curves (Prism and IOC). If a new developer was tasked to create “Scenario #5” for our demo application with the following business rules:
· Use data results from team list using shared Team BLL/DAL
· Provide reset capabilities that will deselect list box results (provide date and time stamp)
· Notify status bar when user selects a team
They could do so in minimal time, without understanding any of the complexities of Prism (composite framework) or IOC; they simply need to know how to create a new module (the Template module holds barebones MVPVM components), how to register and instantiate their implementation of interfaces (in bootstrapper), and understand the framework.

Figure 13 Scenario #5
With little to no code in the Module and ViewModel of the MVPVM components their Scenario5Presenter could look as follows:

Figure 14 Scenario 5 Presenter
Since the Reset functionality is core functionality consistent throughout the entire application the ScenarioPresenter<View, Presenter> base class (line 19 of figure 14) will handle that logic for us for free, we only need to perform the following steps (reference figure 14):
· Line 26 - resolve our BLL using constructor injection (configured in the bootstrapper in figure 9)
· Override our Presenters GetViewModelData() method, with the knowledge it will be called at the appropriate time, requesting our data asynchronously using the TeamBll.List() method. We’ll take this opportunity to update our ViewModels LastReset value.
· Override the DataArrivedBllHandler() and assign the results to our ViewModels TeamList property (line 49) while updating our date and time stamp.
· Override the ViewModelPropertyChangedHandler (line 61), prepare message (line 67) and publish the message to the status bar (line 73).
The application framework can be learned without assistance (if well documented) or easily taught by more experienced developers allowing the new developer to be instantly productive (increased velocity) while affording them the opportunity to take on the heavier learning curve at a time that has no impact on critical timelines.
In conclusion, composite Metro applications, as demonstrated by the demo application (using Prism and Unity “like” plumbing), that support the architectural MAAM principles discussed in this article will have the following characteristics:
· Scalable
· Extensible
· Maintainable
· Decoupled
· Reusable components
· Modules with a clear separation of concerns / single responsibility
Which all contribute to increased velocity, stability and the success of existing and new Metro enterprise applications that will be supported by all Windows 8.