Thursday, 28 August 2008

Dependency Injection in xaml

I want to describe a solution I've found to inject dependencies of my objects right in Xaml. This solution is special because it is coupled with CAB that I use as a platform for my smartclient applications, but I sincerely hope that you will see the idea behind particular implementation that will let you abstract this solution away from particular IoC framework.

Quite often I create objects in Xaml, and I'd like to follow the main principles of my development. As a part of this I'd like to inject dependencies in objects, being created by WPF, like I
do it in code-behind.



So I need a solution that will fit following requirements:

  • ability to be used in Binding;
  • ability to be used with POCO.
My solution consists of the same number of parts as abovementioned requirements:
  • IoCProvider - custom DataSourceProvider (Binding "knows" about DataSourceProvider and works with it perfectly);
  • a set of MarkupExtensions to be used with POCO;
IoCProvider

IoCProvider is the core of my solution. It is the part that infers dependencies by means of standard CAB IoC container - WorkItem.



Since
this object is created mostly by WPF engine, there is no way to inject a container into IoCProvider, but here we can use a well-known registry object, such as an Application object in WPF. Considering that my Application always implements IRootApplication interface, that is bound to publish root WorkItem, this task is no more a matter of interest (see IoCProvider constructor).

Main job in inferring of dependencies is done in BeginQuery method. One can initiate a query by calling a base
DataSourceProvider class Refresh() method manually, or it will be done automatically by means of Binding system.



Now we can use this provider as a source of data in Binding, but
attempts to bind POCO's property or field to requested dependency will cause an InvalidOperationException to be thrown, informing us that binding can be used only with Dependency Property. How do we escape this?

Markup Extension.

This is the solution for the second part - markup extension. Markup extensions can be used
almost everywhere in xaml. ServiceDependencyMarkupExtension is my example implementation, which infers WorkItem's service dependencies.



Below follows the result - we
inject our dependencies right in Xaml! Isn't it awesome?



I hope now you see how simple the dependency injection in xaml is, and I also hope you'd be able to make a step further and abstract the whole solution away from concrete IoC framework. You can see an example of such solution in Prism - its IContainerFacade interface.

Here is a couple of articles that will help you in process:
creating-a-custom-datasourceprovider
Injecting Xaml with Unity Application Block using Markup Extensions

Good luck!

Wednesday, 6 August 2008

Kodama - a spirit of tree.

Some of you have probably read my post about Josh Smith and ViewModel coming to rescue people (WPF-addicted people, to be precise), just joking don't mind. In brief words, I wrote how ViewModel helped working with ComboBox or another Selector control to manage state of underlying CollectionView. After that I've generalized my thoughts, and there came a SelectorCollectionPresenter class, which made my sleep quiet. =) I'll publish code in the end as a bonus.


But now I want to write about the TreeView control, and how it can be united and simplified with ViewModel pattern. I was inspired a long time ago, when I read this article by Josh Smith, but had no time to work with WPF, solving other infrastructural problems, but I've got the idea stuck in my head.
And finally I got time to think about it and put it together in a reusable manner. As a result I've got a tree control with a spirit living in it. I named it Kodama, because kodama is a spirit from Japanese folklore, which is believed to live in trees. And the control itself was called KodamaView. As you might have already guessed, this spirit, which lives in my tree control, is nothing more than a ViewModel!

- he said ViewModel?

I want to warn everybody – I've just put together my thoughts on DM-V-VM pattern and Josh's fantastic ideas, so most of honors should go right to Josh!

KodamaView


KodamaView - is a UserControl, hosting a TreeView inside itself. In order to simulate TreeView's behavior, it inherits ITreeView interface, based on my IWPFView interface, and delegates all incoming calls to internal TreeView control.


TreeView simulating interface.


KodamaView control.


Control's xaml.

Kodama.

And now here are some words about Kodama.


Toriyama Sekien's illustration of a kodama appearing as an old man.

My Kodama (if it is allowed to say so) is an inheritor of ViewModel class, parameterized with ITreeView and IDataModelBase interfaces. The last one is made basic to be able to create Kodama with any derived DataModel class, because all of them embody this interface. DM is the source of data for the tree.



Every TreeViewItem gets its own ViewModel - a TreeViewItemViewModel.



TreeView is able to load child nodes "lazily", only when their parent node is expanded (I've borrowed the code from Josh's article, I hope he doesn't mind). All work on loading children is done in a LoadChildren method.



There is another one class in hierarchy - TreeViewItemViewModel`1. It has only one purpose to exist - to populate a typed Entity into the visual tree.



StructureTreeKodama is my example demonstrating this philosophy.




I remember, when I started the post, I've promised you a bonus. So here it is - SelectorCollectionPresenter class code. You can read some on details of it here.



Good luck!

Tuesday, 24 June 2008

WPF Presentation layer

I am about to stop blogging for next three weeks.

I'd like you to spend this time with pleasure and use so here is the candy: Presentation Layer.
This is a small framework to help develop desktop WPF applications. Mostly it is a DM-V-VM implementation with some other stuff I've blogged about.

And, finally, I am going to make a candy more yummy. I've included source codes for my WPF Wizard control as I've promissed some time ago.

Enjoy!

Friday, 6 June 2008

How Josh saved my day or the power of the Model side

May be I missed something but it was a challenge for me to maintain a following situation.

Imagine, for example, that you have an object with some property that can be chosen from some external list of values. How would you solve it? You'll, probably, put in UI some Selector control, say it would be a ComboBox, bound with list of available values. You would bind its SelectedItem property with underlying object's target property by means of OneWayToSource binding. Quite easy so far, isn't it? Just write ViewModel for this view that will publish this object and will keep all logic. Now let's make this example a little trickier. Imagine that you have to edit a list of said objects and you have to choose a unique value for every particular object. You see now that it is not so easy anymore? And to puzzle you completely picture yourself a Configuration Dialog that hosts your editing UI. This dialog has OK and cancel button and your objects' state must stay sync with what you do. Something like the following:

Don't be scared this UI is just for tests =).

I've written a number of posts about M-V-VM pattern, but in spite of was completely cumbered with this scenario. I do have an infrastructure to edit objects (I've written about it here), but in this case I was baffled. The problem was with this list of available values. To make it easier for understanding I'll introduce some classes.

The scenario is as follows: I have a number of visual addins (powered by Managed Add-Ins Framework) (I really should write about it, but I'll do it later) that I want to host in my UI. But they can be hosted only in the named Workspaces (a CAB's notion, it is not a WPF restriction it is my decision). You can see the model now. I've got AddInDescriptor objects that keep a name of containing workspace and addin token. This name can be set in Configuration Dialog by browsing and selecting one from available list. This dialog can commit or rollback changes and at next start it must show appropriate content.


descriptor class. just a DTO.


descriptor data template.


listbox item style.

The problem
looks like this: when I first set the name of containing workspace and then rollback and start again, combobox updates current item binding (AddInDescriptor.ContainingWorkspaceName property) with a valid empty workspace name and then explicitly sets the first item as current without update. This strange behavior violates all the logic written in a style's triggers. I tried to fix this broken behavior in a whole bunch of ways but neither of them worked.

And this is whe
n an idea dawned at me! I remembered a beautiful article written by WPF-rock star (of course it was Josh, who else?) about the simplest way to manage a TreeView in WPF. Here it is: http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx. I say this article is a MUST read.

And then I thought: "What is the difference? I have to do the same with ComboBox in my case.", and everything became clear.

I've created a AddInDescriptorPresenter class that held all the UI related logic. It is nothing more then a UI-proxy to the object and is intended to publish object- and UI-related properties. This class accepts a CollectionView (a built-in VM for collection) which a Combo is bound with.

AddIn descriptor presenter.

A list of these proxies is created and exposed by UI ViewModel that keeps a list of AddInDescriptors.

You might be interested what the TransactionalTune is.
TransactionalTune is a special data container, a volatile transaction manager based on Juval Lowy's fantastic article. You can read more here.
All this UI-proxy does is controlling the state of CollectionView that is synchronized with ComboBox.


AddInDescriptorPresenter code.

Template to render this presenter became a little bit easier.


AddInDescriptorPresenter data template.

I've spent a couple of days trying to solve this problem writing tons of different xamls and code-behinds, and it took me about an hour to make everything work correctly with the ViewModel!
You see now that it is powerful?

Good luck!

Friday, 30 May 2008

Business Objects validation in WPF wizard

Oh dear! Is it really me writing? Well, yeah, it is me!


I had a lot of fun in Mediterranean yachting and now I am full of strength to manage with my thoughts' flow. =)

While writing this post I understood that I chose the very interesting theme to my mind - WPF wizard component development that I've done for my projects. But then I realized that it would take a year to highlight all the process with my speed of posting, so I came back to the original title and focused on the particular theme. I'll try to write on WPF wizard later on, but to keep your interested I'm going to include wizard's sources.

As I've mentioned in my previuos posts on DM-V-VM pattern I don't edit objects in most of UIs. The reason is simple - ViewModel doesn't track edited object state. I do it in wizards. WPF doesn't contain such a useful component as a wizard by default so you have 2 ways out: 1st - pay someone for ready custom component and the 2nd one - write your own. I chose 2nd one =) as I often did. It was a very big work that brought tons of difficulties and challenges but was a lot of fun to solve. Propably the biggest challenge was UI integration in validation process where UI could track underlying objects' state and react respectively avoiding user from saving objects in an inconsistent state. I knew about validation in WPF binding, but it was not quite the thing I needed. (In WPF that goes with .Net 3.5 business objects validation can be plugged in validation process easily by using ValidatesOnError binding property and IDataErrorInfo interface in object, but still it is not quite one I needed). Karl Shifflet wrote a wonderful article on validation and WPF business applications developement generally, here it is: http://www.codeproject.com/KB/WPF/WPFBusinessAppsPartThree.aspx .

As an alternative to editing objects in wizard you can use this approach, which I've mentioned earlier.
So what do I need and what do I want?
I want:

  • UI to track underlying objects' state automatically and react respectively - buttons Next, Save should be disabled in case an underlying object is in invalid state; in other words wizard should not let you make a mistake;
  • developer writing wizard code to avoid taking part in validation process, in other words validation must start automatically in a transparent way, no code-behind with validation code;
I have:
  • Validation in WPF binding engine already exists. One can plug in by writing his own ValidationRule descendant. There also is a static class Validation that provide means to set ErrorTemplate for UI control and get errors collection. So why doesn't it fit our needs? The reason is simple - it validates the UI data - not underlying objects, but we need a unified process that will validate business objects decoupled from UI technology. Therefore we won't use WPF validation as a main engine, but only as an extensibility point;
  • Validation Application Block (VAB), that was developed to validate objects, can be found in Enterprise library (EL);
  • There is command notion in WPF that can control UI state. I wrote about'em in previous posts.
Well, it seems that we have all we need! So let's go on.

First of all let's check out this scenario: we've got a wizard that edits a human/visitor (whatever) entity.

  1. you fill in first name, last name and other fields at wizard's first page, and the first name field is mandatory.
  2. you provide an entity with the access data such as login, password and password confirmation in the second page;
  3. you fill all the blahblahblah fields in the rest of a wizard's pages... =)


Entity you edit in my wizard is applied to DataContext property, thus enabling all the visual tree (pages with controls in it) to inherit the last one.

Every UI control, which triggers some action, is bounded with a command. Every command is wrapped in alreasy
familiar CommandModel class. Said models are holding command's state and execution logic. And what I intend to do is to delegate them validation.

First I used to delegate validation logic to my domain objects (you can read about this approach here) but it made my wizard control tightly coupled with my domain model, which is ugly! So I've changed a direction and made my commands validating edited entities. I use Validation Application Block from Enterprise Library. David Hayden has a tons of tutorials on p'n'p's products, including this set of articles on VAB, so I won't write on how VAB is working because you can read everything there.

Wizard edit process is divided into pages that holds some logical associated data, and this logical association correlates with ValidationRuleSet notion, so every WizardPage carries a RuleSet property, that must be set on developement stage.

When it comes to validation I simply call VAB's facade to do the work.

Here is what our visitor class might look like:


You see it has a property Name that is marked with StringLengthValidator attribute [1;200) with the CommanRuleSet ruleset name, and wizard page that edit this property must have the same ruleset name.

Now, when we finished with validation we can start writing our commands logic.
I have the following commands in wizard:
  • NextPage - a command that transfers you to the next page;
  • PrevPage - a command that transfers you to the previous page;
  • GoToPage - a command that performs a gap to the specified number of pages;
  • Save - a command that triggers Finish event;
  • Cancel - a command that triggers Cancel event;
  • Help - a command that shows a user manual;
I'll make an example with the NextPage Command. Command checks whether an entity is valid with corresponding ruleSet, and whether the current page is not last and whether this page is not marked as invalid by WPF Validation manager (it is the extensibility point):



This logic will be called automatically by WPF CommandManager and will reflect state of edited object on NextButton button.

Extensibility point.

Imagine a following scenario:

you edit a credential object that is formed by a Login and Password properties. You have 1 TextBox - Login, and 2 PasswordBoxes - for Password and PasswordConfirmation. This credential object (lets call it LoginCredential) is in DataContext property of wizardpage. You have binded TextBox's Text property to a Login property of credential, text from first PasswordBox use assing to Password property of credential in code-behind. However, in order to validate a password you need user to confirm it and a LoginCrredential class doesn't have such a property (PasswordConfirmation) and never have to! How we will keep our Buttons' state syncronized wth data, when they should be inactive unless user has confirmed his password?


Well, here is the place where I plug in a WPF validation process. In this case I don't need to validate business object's data and should validate only that part of data, which is located in UI.

I've written a ValidationHelper class to streamline my validation code.


There is an attachable property Bag, which can be attached to any DependencyObject and bound with some data (it is useful when you have no properties to bind).
Back to our scenario you'll have to bind ValidationHelper.Bag on first PasswordBox to Password property of underlying credential. You have to do this because in PasswordBox a Password property is not a dependency property (I know that there is a security issue with my attached property take it as an example).


The key element in integration is the PasswordValidationRule that can be seen in the picture above. It is a custom descendant of WPF ValidationRule class. I had to do some code-behind here because, as I've mentioned earlier, Password is not a dependecy property. In this code-behind I obtain binding expression for ValidationHelper.Bag property and force it to update source, thus forcing validation.



I need to send PasswordCopy and WizardPage objects from UI into my ValidationRule object that is not a DependencyObject and even isn't in Logical or VisualTree. What we need to do is to attach virtual branch to the LogicalTree and this problem was perfectly solved by Josh Smith. You can read about this approach in his article. Here’s a brief description. ValidationRule is not a descendant of DependencyObject class so you can't bind its properties, but you can write a surrogate DependencyObject descendant class that will keep one dependency property that can be bound with data. This data is being sent into the dummy holder in resources (DataContextBridge) by means of OneWayToSource binding. After that you can bind a surrogate object Value property to DataContextBridge.

The only thing that left is to write code for ValidationRule. It compares original password string with its copy and mark a wizard page as invalid in case passwords are not identical:



There are two methods in ValidationHelper - MarkInvalid and ClearInvalid that are simply wrappers around WPF Validation class. All that is required to make UI element compatible with ValidationHelper is to attach ValidationHelper.Bag property and bind it with itself (as it is done in WizardPage's default style).

Well, here we are - our validation process in wizard is ready.

In a simple scenario all that developer will have to do is to mark entities with validation attributes, or even configure 'em in enterprise library configuration tool and nothing else. All the rest work will be done by wizard automatically absolutly in an absolutely transparent manner.

Good luck!

P.S. sources are coming on a little bit later.

Monday, 14 April 2008

WPF command & CAB command - run into one another

My previous post was dedicated to the set of classes that constitutes my DM-V-VM pattern implementation being an extension to the smart client software factory (SCSF - CAB based factory) & Kent Boogaart's SCSFContrib (WPF CAB extensions project).

An interesting point was ActionViewModel class that contains and binds all view's commands. But there is another implementation of command pattern in CAB. Which of them a smart programmer should use? What are the pros and cons of each variant?

In CAB's command implementation you have access to an IoС-container and a whole lot of CAB's infrastructure (local services, resources, views). At the same time WPF command is tightly integrated in UI engine, and UI control is the WPF engine's problem. Is there a way to gain united advantages?

The answer is yes and it follows below.

Honestly speaking there is an implementation of merged CAB and WPF commands in Kent Boogaart's SCSFContrib project (WPF integration in CAB). It is a WrappedCabCommand, but I see a huge disadvantage in this implementation - it lacks ability to pass a parameter to a command. I solved this problem by extending Kent's approach.

IActionCatalogService
My main enhancement to WrappedCabCommand is the use of CAB's local service IActionCatalogService as main command executor and state controller. Here you can find a good description of this SCSF part. This service links named actions with methods, marked with [Action(ActionName)] attribute,


registrers conditions - a code that controls action state (whether it can be executed or not),


and allows executing named action (invokes a pipe of subscribed methods).


Method marked with [Action(ActionName)] attribute should be public and match an ActionDelegate delegate signature. Subscribing process is controlled by ActionStrategy from SCSF, that is plugged into the ObjectBuilder strategy chain.


Action conditions are classes that implement IActionCondition interface. Their respective method is automatically invoked by IActionCatalogService before executing, or it could be invoked externally by a client code through the same IActionCatalogService service. The service builds an action pipeline, and results an integral decision of all IActionCondition classes registered for concrete action.

СAB Command.

Commands in CAB are a collection of Command objects stored in WorkItem and indexed by unique string identifier. CAB itself works with commands by means of CommandAdapter class, controling subscribers, command invokers etc. Commands are created by a CommandStrategy that is plugged in the ObjectBuilder strategies chain. Command is created when the strategy meets in created object public methods marked with [CommandHandler(CommandName)] attribute and matching the EventHandler delegate signature. CommandAdapter keeps internal invokers and subscribers tables for the named commands. And when it catches the specified event in invoker, WorkItem invokes all methods subscribed by means of [CommandHandler(CommandName)] attribute.

Adding list view item as a ActivateOverview command invoker with Selected event
ActivateOverview command's subscriber method.
WPF Command.
In WPF commands are presented by classe implementing ICommand interface. There are 2 built-in command classes in WPF library - RoutedCommand and RoutedUICommand. They routes their CanExecute and Executed events in a visual-tree as it follows from their name. The built-in commands doesn't contains any predefined logic and simply allows to handle it by any object from VisualTree that is subbscribed to this command via CommandBinding. UI elements, that can be binded to a command, should implement ICommandSource interface. This interface contains the following properties: Command - the command itself (ICommand), CommandParameter - parameter being passed to the command handler (optional property) and CommandTarget - target - an object particular command will be executed on (optional property).

Come together!

I've chosen a CommandModel class invented by Dan Crevier as a foundation for merged CAB and WPF commands entity.

The ModuleCommand is the idea.

ModuleCommand class interface. IActionCatalogService is injected by CAB's IoC-container while created.
This class finds a CAB command object by name - CommandName.
I've made a convention in unique command naming, it is identifies by the following way - CommandName identifies Command and IActionCatalog Service action, CommandName with prefixes Before[CommandName] and After[CommandName] identifies command-triggers being executed before and after actual command execution respectively.


WPF invokes the ModuleCommand's object overrided OnQueryEnabled method automatically. It queries CAB command and ActionConditions if the command can be executed, promoting all the specific logic into the external infrastructure code (IActionCatalogService CanExecute call), and WPF reflects the command state in UI automatically - the UI element will be enabled or disabled.

There is an ActionTarget property in a class - it is an optional parameter, that the command will pass to the subscribed method automatically by means of IActionCatalogService.

WPF invokes the ModuleCommand's object overrided OnExecute method automatically when it catches event that triggers the command execution and delegates the execution to my ModuleCommand object that in turn delegates it to the Command and Action subscribers.
Thus the problem of merging WPF and CAB commands is being solved by means of IActionCatalogService. UI element is binded with ModuleCommand by CommandBinding in a visual tree, and IActionCatalogService links ModuleCommand with the CAB infrastructure and allows to pass a target and parameter objects to a command handler.
CAB command is still can be used when the logic is simple.
I said work!
Let's assemble an example now. We will modify the code from the previous post. Main changes will happen with FooViewModel class. There is only one type of command objects in it's collection now. There will be no more command classes with hardcoded logic.

but we'll need a command handler class and an action codition class. Here they are:


+ unique strings list.

Code for download: here.
Good luck!

PS: A very interseting approach was demonstrated by wpf-rockstar Josh Smith in this article. He suggests to make RoutedCommand "smarter", by adding it an ability to keep logic itself. Josh inherits his class from RoutedCommand and introduces an attachable-property, marking UI element as a command handler, and also he introduces 2 abstract methods OnCanExecuteCore and OnExecuteCore to be overriden in descendant classes. Other words we could replace our CommandModel class with SmartRoutedCommand, but it would involve xaml complexity.
PPS: remembered that I saw another approach that was built on CAB's EventBroker. But I don't like it though it is easier as it mixes the entities.

Tuesday, 8 April 2008

DataModel-View-ViewModel in WPF. Part 3 Example.

This is the last part on DM-V-VM pattern overview. In this part we'll write a simple WPF application built on this pattern.

DM-V-VM

Let's suppose that we have an object of class Foo that is provided by the SEModel class (parameterized with Foo and FooProvider types). It will be a demonstration of simplicity that SEModel gives - we don't have to write datamodel class, only provider class will be written.




All the logic is contained in a FooViewModel class. It is derived from ActionsViewModel as we'll have some actions triggers in UI (buttons). The actions are represented by two CommandModels - IncCommandModel and DecCommandModel. IncCommandModel increments Foo.Bar property when executed and DecCommandModel decrements it respectively. The DataModel is asked to refresh on View's Load event. DataModel will fetch data asyncronously and throw an event on UI thread as described in a first post
.

CommandModel classes implements logic for editing underlying data (Foo object) that is referenced in CommandParameter property of UI command triggers (objects that implement ICommandSource interface - Buttons in our example).


Now it is a view's turn.

In this example we won't use an IoC-container and will hardcode all dependecies in our classes. View creates ViewModel on it's Initialized event.



And keeping in mind that ViewModel sets itself to the DataContext property of View (window in our case) we know that all visual tree of our view will inherit VM in DataContext property. So just put a ContentControl in a view, bind it's Content property to VM and write a template to render VM.



The only evil SEModel can bring - is lack of ability to bind to it's Entity property. DataBinding just can't fetch the object even if all paths are accurate in 2 or more level templates. But this issue can be avoided easily - just put your object in View's resources in DataModelLoaded event in ViewModel and reference it in Binding via Source property.



This is how our application looks like:



Source for download: here.

Good luck!

PS: PnP group will finish their new project called - Prism, soon. It is intended to become CAB's replacement in developing LOB applications with WPF. Check for weekly drops here.