# Home

## MVVM and UI Composition quick start

### Windows Presentation Foundation

#### Steps to bootstrap your project in 3 minutes

* Create a new Visual Studio solution with a WPF application project;
* Add, using nuget, a reference to: [Radical.Windows.Presentation.CastleWindsor](https://www.nuget.org/packages/Radical.Windows.Presentation.CastleWindsor);
  * this will give us the full Radical Presentation stack with the default Castle Windsor support as IoC/DI container;
* Delete the default MainWindow\.xaml;
* Edit the app.xaml file to remove the StartupUri attribute;
* Add a “Presentation” folder to the project;
  * Presentation is the default location, based on a convention, where Radical Presentation looks for views and view models;
* Create 2 new items:
  * A WPF window named Main**View**.xaml (\*View is important for the default conventions);
  * A class Main**ViewModel** (<*ViewName*>ViewModel is important for the default conventions);
* In the app.xaml.cs add a single line of code:

```csharp
public partial class App : Application
{
   public App()
   {
      var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
   }
}
```

**Press F5 and you are up & running**: the MainView window will be shown.

The application boots, all the default and required services (for MVVM and UI Composition) are wired into Castle Windsor, the MainView is designed as the main window, at boot time the MainView is resolved and using the conventions engine the MainViewModel is setup and set as the DataContext of the MainView, in the end the MainView is shown.

#### What’s next

The best topic to read now is basic [concepts about the ViewModel](/release-1/presentation/abstract-view-model).

## Release management process

Radical follows a set of rules to prepare and publish releases:

* Define the milestone;
* Define an issue for everything that gets touched:
  * the initial issue comment must be as descriptive as possibile;
  * the first 30 lines of the first issue comment will be included by default in the release description;
  * to include a different amount of lines add a HR (--) to the issue first comment;
  * the issue must be labeled at least with one, and only one, of the following labels: Bug, Feature, Improvement;
* Associate the issue to the milestone;
* Use [GitHub Flow](http://scottchacon.com/2011/08/31/github-flow.html) to commit changes;
* Associate a commit with an issue and close it;
* Publish the release associated to the milestone;

This routines allows us to be able to auto-generate [release notes](https://github.com/RadicalFx/radical/blob/develop/ReleaseNotes.md), trying to be compatible with the [Semantic Release Notes](http://www.semanticreleasenotes.org/) using a [release notes compiler](https://github.com/Particular/GitHubReleaseNotes).

## Contribution guideline

Your contributions to Radical are very welcome.\
If you find a bug, please raise it as an issue.\
Even better fix it and send a pull request.\
If you like to help out with existing bugs and feature requests just check out the list of [issues](https://github.com/RadicalFx/radical/issues) and grab and fix one:

* If you find a bug, please raise it as an issue, even better followed by a pull request.
* If you like to help out with existing bug and feature, just check out the list of [issues](https://github.com/RadicalFx/radical/issues) and grab and fix one.
* This project uses [GitHub flow](http://scottchacon.com/2011/08/31/github-flow.html) for pull requests. So if you want to contribute, fork the repo, create a descriptively named branch off of master (ie: portable-class-library-support), fix an issue, run all the unit tests, and send a PR if all is green.
* Please rebase your code on top of the latest commits. Before working on your fork make sure you pull the latest so you work on top of the latests commits to avoid merge conflicts. Also before sending the PR please rebase your code as there is a chance there have been new commits pushed after you pulled last.
* We will only merge PR that could be automatically merged.

## A note on versioning

Radical follows the following versioning scheme:

major.minor.patch-extensions.version

We use the following [semantic versioning policy](http://semver.org/):

```
major           - version when you make incompatible API changes.
minor           - when you add functionality in a backwards-compatible manner.
patch           - when you make backwards-compatible bug fixes.
extensions      - pre-release extensions
version         - pre-release version
```

Check the [Release pages](https://github.com/RadicalFx/radical/releases) for the version history of all the Radical's packages.

## Samples

The Radical source code includes several samples that are divided per scope and technology, samples are available in the documentation repository: <https://github.com/RadicalFx/documentation/tree/master/samples>

All samples are constantly under heavy development and are also used to test Radical features.

## MyGet unstable feed

Radical uses MyGet to publish unstable releases during development, to use the unstable feed:

* create a `nuget.config` file in the same folder as your solution folder
* add the following content to the configuration file:

```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>
    <clear />
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <packageSources>
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />
    <add key="Radical Unstable" value="https://www.myget.org/F/radical-unstable/api/v2" />
  </packageSources>
  <disabledPackageSources />
  <config>
    <add key="DependencyVersion" value="HighestMinor" />
  </config>
  <activePackageSource>
    <clear />
    <add key="All" value="(Aggregate source)" />
  </activePackageSource>
</configuration>
```

* close and reopen the solution

By going to the Manage Nuget Packages page of your solution, you'll now see a "Radical Unstable" option in the source selection dropdown. Do not forget to check the "prerelease versions" checkbox search setting.


# AbstractViewModel

When dealing with MVVM and ViewModel(s) there are a lot of things that a base class, such as the `AbstractViewModel`, can do for us in order to reduce the friction of the daily work.

The `AbstractViewModel` can (it is not required, even if is highly suggested) be used as a base class for all the application ViewModel(s), defining a view model is as easy as:

```csharp
class MainViewModel : AbstractViewModel
{

}
```

Nothing special, a simple and trivial class that inherits from the base `AbstractViewModel` type.

For the Radical toolkit a `ViewModel` is not required to be an `AbstractViewModel`, but if you do not to use the `AbstractViewModel` class as a base class for all the ViewModels you end up with 2 options:

* implement on your view model the `IViewModel` interface;
* or replace the `AttachViewToViewModel` [convention](/release-1/presentation/conventions/runtime-conventions) that is responsible to reverse link the View to the ViewModel;

As soon as we do that we gain some benefits:

**Property change notification**:

the obvious benefit is that we immediately get `INotifyPropertyChanged` support:

```csharp
private String _text;

public String Text
{
    get { return _text; }
    set 
    {
        _text = value;
        this.OnPropertyChanged( () => this.Text );
    }
}
```

But given that writing properties in such a verbose way is a waste of time we can leverage the power of the Property System.

**Radical Property System**:

The above property can be written in the following manner without altering the behavior:

```csharp
public String Text
{
    get { return this.GetPropertyValue( () => this.Text ); }
    set { this.SetPropertyValue( () => this.Text, value ); }
}
```

But the property system is not limited to changes notification, we can for example do the following:

```csharp
class MainViewModel : AbstractViewModel
{
    public MainViewModel()
    {
        this.GetPropertyMetadata( () => this.Text )
            .AddCascadeChangeNotifications( () => this.Sample );
    }

    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }

    public Int32 Sample
    {
        get { return this.GetPropertyValue( () => this.Sample ); }
        set { this.SetPropertyValue( () => this.Sample, value ); }
    }
}
```

we have defined 2 properties and we are chaining the properties change notification in order to notify a change to the `Sample` property each time the `Text` property changes.


# Conventions

Our first aim is to remove friction, it is not always easy and cannot be done every single time, but one thing that can give a lot of benefits in this area is to move from a configuration based toolkit to a convention based toolkit, we suppose that this concept is widely accepted and is nothing new.

What happens when these lines of code are executed:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<MainView>();
    }
}
```

A lot of things:

1. The application Startup event is wired;
2. When the Startup event is fired:
   1. The Inversion of Control container is created;
   2. The MEF composition container is created;
   3. The composition container is composed against the bootstrapper itself;
   4. The Inversion of Control container is configured using the [bootstrap conventions](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/mvvm/bootstrap-conventions.md);
   5. The main window (the one identified by the TShellView generic parameter) is resolved and shown;


# Bootstrap Conventions

As we have already said the whole bootstrap process is completely based on conventions, especially the IoC container setup. Bootstrap conventions are mainly related to the way components are registered into the container:

* every class that is defined in a namespace ending with `Services (*.Services)` will be considered a service and will be registered as `singleton` using as the service contract the first interface, if any, otherwise using the class type;
* every class that is defined in a namespace ending with `Presentation (*.Presentation)` and whose type name ends with `ViewModel (*ViewModel)` will be considered as a view model and registered as transient;
  * following the same logic every type in the same namespace whose name ends with `View (*View)` will be considered a view, a transient view;
  * if a view or a view model are a shell, type name beginning with `Shell*` or `Main*`, they will be registered as singleton
  * be default views and view models will be registered using as service contract the class type and no interface is searched along the way;
* every type defined in a namespace ending with `Messaging.Handlers (*.Messaging.Handlers)` will be considered a message broker message handler and will be registered as singleton and automatically attached, as an handler, to the broker pipeline;

These are the main conventions used at boot time, there are a few more but less important. Obviously all these behaviors can be replaced or extended to accomplish the end user needs:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<MainView>()
            .OnBeforeInstall( conventions => 
            {
                var original = conventions.IsViewModel;
                conventions.IsViewModel = type => 
                {
                    if ( type.Namespace == "MyViewModelsNamespace" ) 
                    {
                        return true;
                    }

                    return original( type );
                };
            } );
    }
}
```

In the above sample we are integrating the conventions used to determine if a type is a view model.

The following is the list of the used conventions with a brief description of their meaning and usage:

* `IsService`: determines if a type should be considered a service or not;
* `SelectServiceContracts`: given the service type returns the list of contracts that should be used to register the given service;
* `IsMessageHandler`: determines if a type should be considered a message handler or not;
* `SelectMessageHandlerContracts`: given the message handler type returns the list of contracts that should be used to register the given message handler;
* `IsView`: determines if a type should be considered a view or not. The View is registered as transient in the IoC container;
* `IsViewModel`: determines if a type should be considered a view model or not. The ViewModel is registered as transient in the IoC container;
* `IsShellView`: determines if a type should be considered a shell/main view or not. The View is registered as singleton in the IoC container;
* `IsShellViewModel`: determines if a type should be considered a shell/main view model or not. The ViewModel is registered as singleton in the IoC container;
* `SelectViewContracts`: given the view type returns the list of contracts that should be used to register the given view;
* `SelectViewModelContracts`: given the view model type returns the list of contracts that should be used to register the given view model;
* `IsExcluded`: determines if a type should be excluded (ignored) by the registration process;
* `GetInterestedRegionNameIfAny`: this convention requires a deep knowledge of the UI Composition feature and is used to determine if a view is asking to be injected into a region, the conventions is used to retrieve the region name the view would like to be injected into;
* `AssemblyFileScanPatterns`: given the entry assembly returns a list of patterns that should be used by MEF directory catalogs to scan for assemblies at boot time;


# Runtime Conventions

`Radical.Windows.Presentation` has a lot of runtime conventions mainly related to two different areas:

* View – ViewModel relation;
* UI Composition;

Runtime conventions are managed by the `IConventionsHandler` interface, and allows to take full control of the following Radical behaviors:

* **ResolveViewModelType**: The first convention is used internally by the ViewResolver and given the view type returns the ViewModel type for the given view, the default behavior is that the view model is in the same namespace of the view and has the same type name suffixed with “Model” (e.g.: MainView and MainViewModel).
* **ResolveViewType**: The ResolveViewType convention is currently under development and not used, but basically does the opposite stuff, using the same default behavior, as the ResolveViewModelType convention. The toolkit utilizes a view first approach, thus resolving the view type given the view model type is not required, you can use this convention to implement a view model first based approach.
* **ViewReleaseHandler**: the `ViewReleaseHandler` is called each time a `View` should be released, this handler is responsible to release the `View` and its associated `ViewModel` if any. This handler also unsubscribe, if allowed by the `ShouldUnsubscribeViewModelOnRelease` convention, the `ViewModel` from all the subscriptions registered with the `MessageBroker`.
* **ShouldReleaseView**: determines if a `View` should be released when required.
* **ShouldUnsubscribeViewModelOnRelease**: determines if `ViewModel` subscriptions should be unsubscribed at release time.
* **ShouldUnregisterRegionManagerOfView**: internally used by the UI Composition engine to determine if a region manager should be destroyed when the owner `View` is released, the default behavior is to destroy region managers only if the `View` is not a singleton view.
* **FindHostingWindowOf**: This convention is currently used to find the Window that hosts a given view model. It is pretty useful to get a reference to the Window object that hosts, in its visual tree a View Model data bound to a UserControl.

  This task is performed finding the current view of the given view model (using another convention) and then reverse walking the visual tree looking for the first Window object.\
  The convention accomplish two needs:

  1. A view model can implement the IExpectViewClosingCallback and the IExpectViewClosedCallback (and other \*Callback(s)) in order to intercept the fact that the hosting Window is closing or has been closed and since we support UI Composition features a view model can be a view model attached to a UserControl that is runtime “inserted” into the visual tree of an existing Window;
  2. The UI Composition region service, in order to satisfy the above requirement, each time setups a new region need to find the hosting window in order to attach the closing and closed events;
* ViewModels as resources: there are scenarios in which it's handy to have the current `View` `ViewModel` available in the `View` resources. **ShouldExposeViewModelAsStaticResource** and **ExposeViewModelAsStaticResource** control if a `ViewModel` is exposed as a resource (`false` by default) and how it is exposed. The default behavior, when this feature is active, is to register the `ViewModel` in the resources using its `Type` name as the resource key.
* **ViewHasDataContext**, **SetViewDataContext** and **GetViewDataContext**: The ViewHasDataContext convention simply checks if the given view DataContext property is not null, this convention accepts a DependencyObject because in WPF the DataContext property is not defined on a single root object but is defined on FrameworkElement and on FrameworkContentElement.\
  SetViewDataContext and GetViewDataContext respectively sets and gets the DataContext of the given view.

  *Note*:

  > The `ViewDataContextSearchBehavior` has been introduced to overcome an issue encountered due to the way dependency property value inheritance works. When using nested views, for example because one child view is loaded as a content injected into a region, if the nested view does not have a DataContext property (e.g. is a view without a ViewModel) its DataContext property value is inherited from the first element in the logical tree that has a DataContext assigned. This default WPF behavior was causing some subtle bugs in the way the Radical MVVM logic was working. The ViewDataContextSearchBehavior has been introduced to determine the way the MVVM engine will look for the ViewModel on a View, the default behavior, that can be controlled via the `DefaultViewDataContextSearchBehavior` property, is to look only on the View DataContext property ignoring each inherited value.
* **ShouldNotifyViewLoaded** This convention is responsible to determine if a `View` should notify that is loaded broadcasting a `ViewLoaded` message. A view notifies that has been loaded in 2 cases:
  * If the View contains a `Region`;
  * If the View, or the associated ViewModel, is decorated with the `NotifyLoadedAttribute`;

    The same logic applies to the **ShouldNotifyViewModelLoaded** convention for the ViewModel.
* **AttachViewToViewModel** and **GetViewOfViewModel**: Internally the `Radical.Windows.Presentation` MVVM and UI Composition toolkit needs to know the runtime View – ViewModel relations in order to know that given a ViewModel instance the corresponding View instance is certainly a specific instance.

  To achieve that the `ViewResolver` once has resolved both the required instances calls the `AttachViewToViewModel` convention in order to store the view reference in the view model instance (the view model is already stored in view instance using the `DataContext` property).

  By design this works out-of-the-box because the `AbstractViewModel` type implements the `IViewModel` interface that has a `View` property internally used for this tasks. If the user does not like this behavior or cannot inherit from the `AbstractViewModel` type, nor implement the `IViewModel` interface, can replace this convention in order to store somewhere else the required relation (e.g. a statically defined dictionary).

  The same logic is used by the `GetViewOfViewModel` convention that is required to retrieve the stored relation.
* **TryHookClosedEventOfHostOf**: This is internal and is used by the region service engine to attach the closed event of the hosting window, if any, in order to cleanup stuff when the window is closed.
* **IsHostingView**: The `IsHostingView` convention is internally used by the `Region` base class to determine if a given visual element can be considered a View.
* **AttachViewBehaviors**: The AttachViewBehaviors convention can be hooked by the framework user if there is a requirement to attach behaviors (`System.Windows.Interactivity.Behavior<T>`) whenever a view is resolved by the ViewResolver. By default the built-in `ViewResolver` attaches the following behaviors to each view:
  * WindowLifecycleNotificationsBehavior;
  * FrameworkElementLifecycleNotificationsBehavior;
  * DependencyObjectCloseHandlerBehavior;


# Conventions override

Radical is conventions based, we have [runtime conventions](/release-1/presentation/conventions/runtime-conventions) and [bootstrap conventions](/release-1/presentation/conventions/bootstrap-conventions) in order to facilitate the conventions override, to replace or integrate a default behavior we now support the concept of default conventions.

Originally the code to write, still supported, to override a convention was something like the the following:

```csharp
var original = conventions.IsViewModel;
conventions.IsViewModel = type => 
{
    if ( type.Namespace == "MyViewModelsNamespace" ) 
    {
        return true;
    }
    return original( type );
};
```

We now support for both [runtime conventions](/release-1/presentation/conventions/runtime-conventions) and [bootstrap conventions](/release-1/presentation/conventions/bootstrap-conventions) the following syntax:

```csharp
conventions.IsViewModel = type => 
{
    if ( type.Namespace == "MyViewModelsNamespace" ) 
    {
        return true;
    }
    return conventions.DefaultIsViewModel( type );
};
```

For every convention we have there is a convention whose name is the same but prefixed with `Default` so that we are not required anymore to keep track of the original convention we are overriding.


# Commands and DelegateCommand

WPF and Universal Applications have a really handy way to handle the concept of a command: the `ICommand` interface (<http://msdn.microsoft.com/library/system.windows.input.icommand.aspx>).

Radical has its own implementation that allows to easily hook command logic using delegates. The Radical `DelegateCommand` adds a set of features on top of the default .Net `ICommand`.

Creating a command in Radical is as easy as:

```csharp
ICommand command =  DelegateCommand.Create()
    .OnCanExecute( state =>
    {
        //command validation logic.
        return true;
     } )
     .OnExecute( state =>
     {
         //command execution logic.
     } );
```

The command entry point is the `DelegateCommand` class, in the above sample used in a fluent interface manner.


# IViewResolver

As we have already wrote when we spoke about [Runtime Conventions](/release-1/presentation/conventions/runtime-conventions) Radical utilizes by default a view first approach, that even if is completely replaceable with a ViewModel first approach, must be understood.

The main and only entry point used to resolve views is `IViewResolver` interface whose role is to resolve a view instance given a view type:

```
IViewResolver service; //injected by the IoC engine
var viewUsingGenerics = service.GetView<SampleView>();
var viewUsingType = service.GetView( typeof( SampleView ) );
```

At runtime when the `GetView` method is called the default built-in view resolver does the following things:

1. goes to the IoC container and resolves an instance of the requested view type;
2. if the view already has a `DataContext` it assumes that the view is a singleton and has been already resolved once and immediately returns the resolved view;
3. Otherwise, using the conventions:
4. Using the `ResolveViewModelType` convention determines the type of the associated ViewModel;
5. Resolves, via the container, the ViewModel;
6. Set the relation View – ViewModel;
7. Set the ViewModel as the DataContext of the View;
8. Attaches to the View the required behaviors;
9. Returns the view to the caller;

## How to use the IViewResolver in our application

The typical usage of the view resolver in the application is to open/show another view, the easiest way is to declare a dependency on the resolver in our component:

```
class SampleViewModel
{
    readonly IViewResolver service;

    public SampleViewModel( IViewResolver service )
    {
        this.service = service;
    }

    public void ShowAView()
    {
        var myView = this.service.GetView<MyView>();
        myView.Show();
    }
}
```

We are using the simplest possible approach in order to keep the sample complexity really low.

## Notes

* In the above sample we are violating the MVVM pattern because we are dealing with a view within the ViewModel, in the chapter related to the [MessageBroker](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/messaging/message-broker.md) we’ll see how to avoid this mix.
* A view does not require a view model to work properly, the `IViewResolver` can resolve views that don't have view models;


# Default view behaviors

We have seen how Radical Presentation [resolves views instances](/release-1/presentation/iview-resolver) at runtime and we have told that during the resolution process we inject/attach to the resolved view some behaviors using a convention.

The convention attaches the following behaviors to each resolved view:

* to every view (every DependencyObject) attaches the “**DependencyObjectCloseHandlerBehavior**” whose role is to allow the view model to send a close request message to its own view without the need to handle a reference to the view;
* if the **view is a window** attaches the “**WindowLifecycleNotificationsBehavior**” used to notify to the view model the lifecycle state changes of the view (loaded, shown, activated, closing and closed);
* “else if” the **view is a FrameworkElement** attaches the “**FrameworkElementLifecycleNotificationsBehavior**” whose role is notify to the view model when the view is loaded;

The easiest way to handle view lifecycle state changes in the `ViewModel` is to setup a [callback expectation](/release-1/presentation/iview-resolver/view-life-cycle-events/callback-expectations).

## Automatic broker unsubscribe

The `WindowLifecycleNotificationsBehavior` whenever the `view` is closed invokes `ViewReleaseHandler` convention that is responsible to determine if the `ViewModel` associated with the closed `View` should be unsubscribed from all the message broker subscriptions, if any, created.


# view life cycle events

We have seen that the infrastructure has a way, by default based on behaviors, to notify a `ViewModel` that its own `View` state is changing.

## The View is a Window

If the view is a window we have several state that can be handled/intercepted by the coupled `ViewModel`:

* Loaded;
* Activated;
* Shown;
* Closing;
* Closed;

## The View is a FrameworkElement (e.g. a UserControl)

If the view is a user control the only state we can intercept is the `Loaded` event.


# Callback expectations

A view model that needs to intercept state view changes can implement an interface that declares which are the required callback(s), the supported interfaces are:

* IExpectViewLoadedCallback;
* IExpectViewActivatedCallback;
* IExpectViewShownCallback;
* IExpectViewClosingCallback;
* IExpectViewClosedCallback;

All those interfaces are pretty trivial and does not require any further explanation other then the following sample:

```csharp
class SampleViewModel : IExpectViewLoadedCallback
{
    void IExpectViewLoadedCallback.OnViewLoaded()
    {
        //code to handle the View Loaded event
    }
}
```

The only “special” one is the `IExpectViewClosingCallback` that allows the `ViewModel` to ask to the `View` to stop the closing process:

```csharp
class ChildViewModel : AbstractViewModel, IExpectViewClosingCallback
{
    void IExpectViewClosingCallback.OnViewClosing( CancelEventArgs e )
    {
        //blocks the view closing process
        e.Cancel = true;
    }
}
```

Those interfaces are designed to let the `ViewModel` intercept the state changes of **its own** `View` not of other views, the default way to intercept state changes of other views is to use the `MessageBroker`.


# notify messages

It is possible to configure a `ViewModel` to notify, via a broker message, that the state of the associated `View` has changed. The `ViewModel` class can be decorated with one, or more, of the following attributes, depending of the notifications we need:

* `NotifyLoadedAttribute`
* `NotifyShownAttribute`
* `NotifyActivatedAttribute`
* `NotifyClosedAttribute`

All the notifications will be broadcasted asynchronously using the `MessageBroker`, such as in following sample:

```csharp
[NotifyLoaded, NotifyClosed]
class MySampleViewModel : AbstractViewModel
{
}
```


# Message broker MVVM built-in messages

Radical Presentation relies on the [`MessageBroker`](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/messaging/message-broker.md) to broadcast messages that can be used by the application to easily manage a lot of stuff that otherwise can be a bit cumbersome.

The following is the list of the Radical Presentation built-in messages and their meaning/usage.

## Application Messages

These messages are broadcasted or dispatched by the application to notify application level state changes.

* `ApplicationBootCompleted`:
  * **broadcasted** *asynchronously* by application bootstrapper to notify that the boot process is completed.
* `ApplicationShutdownRequest`:
  * can be dispatched or broadcasted by anyone to request programmatically the application to shutdown. it is highly recommended that the message is broadcasted asynchronousl&#x79;*.* When the application shutdown is requested via the `ApplicationShutdownRequest` message, the following events might be dispatched:
    * `ApplicationShutdownRequested`:
      * **dispatched synchronously** by application bootstrapper to notify that the application has started the shutdown process, this event is dispatched synchronously to allow subscribers to easily cancel the shutdown process using a well known approach similar to the one exposed by the .net `CancelEventArgs`.
      * `ApplicationShutdownCanceled`:
        * **broadcasted** *asynchronously* by application bootstrapper to notify that the shutdown process has been canceled.
* `ApplicationShutdown`:
  * **broadcasted** *asynchronously* by application bootstrapper to notify that the shutdown process is in progress, from this point on the process is not cancellable any more.

*Note*:

All the “application shutdown” related events/messages brings with them an enumeration (`ApplicationShutdownReason`) that identifies why the application is shutting down.

## View/ViewModel Messages

The following messages are broadcasted or dispatched by the infrastructure when the state of a view changes or to request a change to the view status.

* `CloseViewRequest`:

  * can be dispatched or broadcasted by anyone to request programmatically to a view to close. it is highly recommended that the message is broadcasted *asynchronously*.

    The message is generally used to close the view of the view model that issues the message, but the shape of the message allows to close a view attached to any view model.

  ```csharp
  class SampleViewModel
  {
      readonly IMessageBroker broker;

      public SampleViewModel( IMessageBroker broker )
      {
          this.broker = broker;
      }

      public void Sample() 
      {
          this.broker.Broadcast( new CloseViewRequest( this ) );
      }
  }
  ```
* `ViewModelClosed`:
  * **broadcasted** asynchronously by the infrastructure to notify that a view and an associated ViewModel has been closed.
* `ViewModelClosing`:
  * **dispatched synchronously** by the infrastructure to notify that the a view and an associated ViewModel is closing, this event is dispatched synchronously to allow subscribers to easily cancel the close process using a well known approach similar to the one exposed by the .net `CancelEventArgs`.
* `ViewLoaded`:
  * **broadcasted** *asynchronously* by the infrastructure to notify that a view has been loaded.
* `ViewModelLoaded`:
  * **broadcasted** *asynchronously* by the infrastructure to notify that a ViewModel has been loaded.

*Note*:

`ViewLoaded` and `ViewModelLoaded` messages are broadcasted only under certain circumstances, depending on the result of the `ShouldNotifyViewLoaded` and `ShouldNotifyViewModelLoaded` [conventions](/release-1/presentation/conventions/runtime-conventions).

* `ViewModelShown`:
  * **broadcasted** *asynchronously* by the infrastructure to notify that a view and an associated ViewModel has been shown for the first time.


# Application boot process demystified

What happens under the hood when we write this really trivial piece of code?

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
    }
}
```

As we have already seen in the [quick start](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/README.md#steps-to-bootstrap-your-project-in-3-minutes) we are doing 2 main choices:

* We boot using Castle Windsor as IoC container;
* We declare that the `MainView` window in the `Presentation` namespace is the main window of our application;

Internally the application boot process is not so trivial as it appears from the outside, when the `Startup` event is raised by the WPF application the bootstrapper:

### Creates the service provider

That, in the end, is the inversion of control container of your choice.

This task is accomplished by the concrete bootstrapper overriding the abstract method `CreateServiceProvider()`, in the above sample by the `WindsorApplicationBootstrapper` that creates an instance of Windsor and returns it to the bootstrapper as a `IServiceProvider`.

### Creates the MEF `AggregateCatalog`

That can be used during the bootstrap process to aggregate application modules.

Accomplished directly by the `ApplicationBootstrapper` class virtual method `CreateAggregateCatalog( IServiceProvider )`, inheritors can override this method to customize the created catalog. By default the `ApplicationBootstrapper` adds to the `AggregateCatalog` 3 different `DirectoryCatalog(s)`:

1. one directory catalog to match all the `Radical*.dll` assemblies;
2. one directory catalog to match all the `{entry assembly name}*.dll` assemblies;
3. one assembly catalog for the `entry assembly` specifically that usually is an exe;

The last 2 catalogs ensures that all the assemblies that starts with the same name of the entry assembly will be analyzed by MEF.

If we need to change the above behavior there are 3 options:

1. Redefine the delegate used by the bootstrapper to identifies catalogs:

   ```csharp
   public partial class App : Application
   {    
       public App()    
       {        
           var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
           bootstrapper.DefineCatalogs = ()=> 
           {
               return new []{ new DirectoryCatalog( "[path]" ) };
           };
       }
   }
   ```

   we are completely redefining the whole content of the `AggregateCatalog`, since the `DefineCatalogs` is a `Func<IEnumerable<ComposablePartCatalog>>` we can partially override the delegate and remove some predefined catalogs, for example, and add some other;
2. On the other hand if we simply need to add some more catalogs to the default ones we can write the following code:

   ```csharp
   public partial class App : Application
   {    
       public App()    
       {        
           var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
           bootstrapper.OnCatalogDefinition( () => 
           {
               //we are adding a new catalog to the default ones.
               return new []{ new DirectoryCatalog( "[path]" ) };
           } );
       }
   }
   ```
3. Finally we can change the [Bootstrap Conventions](/release-1/presentation/conventions/bootstrap-conventions) to determine which are the pattern that the directory catalogs should use to scan for assemblies;

### Creates an instance of the MEF composition container

Once the previously created `AggregateCatalog` is ready the bootstrapper creates an in instance of MEF via the `CreateCompositionContainer( AggregateCatalog, IServiceProvider )`.

#### Compose

As soon as the composition container is created the boot process composes itself against MEF and notifies inheritors that the composition process is completed calling the `OnCompositionContainerComposed( CompositionContainer, IServiceProvider )` virtual method. The default `ApplicationBootstrapper` class does nothing in that method, but, for example, the `WindsorApplicationBootstrapper` performs the Windsor container setup; the same approach is used by all other bootstrappers.

Radical supported containers support installers, or descriptors in Puzzle terminology, we use MEF to compose descriptors at boot time and dramatically simplify the wire-up process required to setup the container. The following is an excerpt of the code used in the `WindsorApplicationBootstrapper` to setup the container:

```csharp
[ImportMany]
IEnumerable<IWindsorInstaller> Installers { get; set; }

protected override void OnCompositionContainerComposed( CompositionContainer container, IServiceProvider serviceProvider )
{
    base.OnCompositionContainerComposed( container, serviceProvider );

    var toInstall = this.Installers.Where( i => this.ShouldInstall( i ) ).ToArray();

    if ( this.onBeforeInstall != null ) 
    {
        var conventions = this.container.Resolve<Boot.BootstrapConventions>();
        this.onBeforeInstall( conventions );
    }

    this.container.Install( toInstall );
}
```

As we can see all we do is to expose a private import-many property, at composition time MEF scans all the catalogs looking for types that export the `IWindsorInstaller` type, in case of Windsor, and populate the import property, leaving us with the only trivial task to call a method on the container.

One important thing to notice is that here we have the ideal hook to change the [Bootstrap Conventions](/release-1/presentation/conventions/bootstrap-conventions), we can write the following piece of code to ensure conventions are changed right before usage:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
        bootstrapper.OnBeforeInstall( conventions => 
        {
            //modify conventions behavior here.
        } );
    }
}
```

## Setup UI Composition Support

After having boot the container the application bootstrapper takes care of configuring the UI Composition system, we’ll discuss what happens in the UI Composition chapter.

## ShutdownMode

WPF applications have the concept of `ShutdownMode`. Application bootstrapper does not change in any way the default value of the `Application.Current.ShutdownMode` unless explicitly requested by user:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
        bootstrapper.OverrideShutdownMode( ShutdownMode.OnLastWindowClose );
    }
}
```

## Principal initialization

Once the application services are setup the bootstrapper takes care of setting up the `Thread.CurrentPrincipal`, the default behavior is to use the current user `Windows identity`. This behavior can be changed in 2 different ways:

1. Inheriting from the bootstrapper and overriding the `InitializeCurrentPrincipal` virtual method;
2. Setting a different principal right after the boot process is completed, using the supplied hook;

## Culture & UICulture

After setting up the principal and finally returning control to the application the boot process has the option to setup the `Culture` and the `UICulture` of the current `Thread`. The default behavior is to use values of the hosting OS. The default behavior can be overwritten in the following way:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
        bootstrapper.UsingAsCurrentCulture( () => 
        {
            return new CultureInfo( "it-IT" );
        } );

        bootstrapper.UsingAsCurrentUICulture( () =>
        {
            return new CultureInfo( "en-US" );
        } );
    }
}
```

## Boot

Once everything is setup the bootstrapper gives us the ability to take part into the boot process before the main window is shown:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
        bootstrapper.OnBoot( container => 
        {
            //the UI is not yet started
        } );
    }
}
```

## BootCompleted

The last event in the process is the one used to show the main window, we have the opportunity to be notified using the exposed handler:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>();
        bootstrapper.OnBootCompleted( container => 
        {
            //the UI is setup
        } );
    }
}
```

Some of the state of the boot process are also [notified to the application using the message broker](/release-1/presentation/built-in-messages).

## Intercepting unhandled exceptions

if we need to be notified whenever an unhandled exception occurs in our application we can use the provided hook:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>()
            .OnUnhandledException( e =>
            {

            } );
    }
}
```

## Handling the application Shutdown

As for the startup we can also handle the shutdown process of the application:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>()
            .OnShutdown( reason =>
            {
                //handle services/components shutdown here
            } );
    }
}
```

When the application shuts down the provided delegate is invoked passing in the reason why the application is shutting down:

```csharp
public enum ApplicationShutdownReason
{
    /// <summary>
    /// The application has been shutdown using the Radical canonical behaviors.
    /// In this case the shutdown process can be canceled.
    /// </summary>
    UserRequest = 0,

    /// <summary>
    /// The application is shutting down because another 
    /// instance is already running and the application 
    /// is marked as singleton.
    /// </summary>
    MultipleInstanceNotAllowed = 1,

    /// <summary>
    /// The application is shutting down because the operating system session is ending.
    /// </summary>
    SessionEnding,

    /// <summary>
    /// The application has been shut down using the App.Current.Shutdown() method.
    /// </summary>
    ApplicationRequest,
}
```

As we can see we can easily determine why the application is shutting down. Currently there is no way from the application bootstrapper to cancel the shutdown process, in order to achieve that we need to subscribe to the `ApplicationShutdownRequested` message via the message broker.

Someone may have noticed that one of the shutdown reasons is `MultipleInstanceNotAllowed`, Radical can handle singleton application for us with minimal effort, take a look at [singleton applications](/release-1/presentation/boot-process-demystified/singleton-applications).

[Application shutdown](/release-1/presentation/boot-process-demystified/application-shutdown) discusses all the details of the shutdown process and how to control/invoke it.


# Application shutdown

In order to shutdown an application built using Radical Presentation there are 3 main options.

**Canonical WPF way: `App.Current.Shutdown();`**

There is no reason to not use the default WPF standard way to shutdown the application, the only thing we cannot do in this case is to prevent the shutdown process to complete, we have no control over it.

When the `App.Current.Shutdown()` method is called the bootstrapper raises, via the message broker, the following events:

* `ApplicationShutdown`: that simply notifies to the application that is shutting down;

**2 way shutdown via `ApplicationBootstrapper.Shutdown();`**

If we need an option to cancel the application shutdown process we should use the `Shutdown()` method exposed by the `ApplicationBootstrapper`. In this way the following events are broadcasted/dispatched by the message broker:

1. `ApplicationShutdownRequested` is dispatched synchronously to the application and has a `Cancel` property that can be set to true to cancel the shutdown process;
2. `ApplicationShutdownCanceled` is broadcasted whenever the shutdown process is cancelled;
3. `ApplicationShutdown` is finally dispatched asynchronously to notify to the application that is shutting down;

**2 way shutdown via `ApplicationShutdownRequest` message**

Exactly the same approach as above can be obtained broadcasting, via the message broker, the `ApplicationShutdownRequest` message, without the need to have a reference to the bootstrapper.


# Singleton applications

There are cases in which we need that our application cannot be started twice by the user, these applications are called singleton applications. We can use the really powerful Radical Presentation application bootstrapper to create a singleton application:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>()
            .RegisterAsSingleton( "my-singleton-key", SingletonApplicationScope.Local );
    }
}
```

Using the `RegisterAsSingleton` method we can set the singleton key (that in the end is the name of the Mutex used to handle “singletoness”) and we can specify if we want our application to be singleton in the current user session (Local) or globally for the running OS independently of the user (Global). If the system determines that the application can run we have the opportunity to change this decision:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>()
            .RegisterAsSingleton( "my-singleton-key", SingletonApplicationScope.Local )
            .OnSingletonApplicationStartup( e =>
            {
                e.AllowStartup = false;
            } );
    }
}
```

We can use the same exact approach as above to handle the case in which the application is starting and another instance is already running, in this case the value of the `AllowStartup` property is false, indicating that another instance is running.


# AbstractMementoViewModel

The [AbstractViewModel](/release-1/presentation/abstract-view-model) base class provides us a way to create `ViewModels` with a set of base features that satisfies most of the basic requirements.

When dealing with complex MVVM based application we sometimes need to deal with the user editing graph of objects, changing property values and/or adding/removing items from and to collections; the end user is generally used to editors, such as Microsoft Word, that provides rich editing features with Undo/Redo support.

Implementing Undo/Redo like features is not as simple as it can appear in the first place, Radical supports a feature called `Memento`, based on the memento pattern, that allows us to easily implement a change tracking system with fine grain control over what is going on and with a rich set of features out of the box.

The first, and easy, step to start using `Memento` is to inherit our `ViewModels` from the `AbstractMementoViewModel` class:

```csharp
class MainViewModel : AbstractMementoViewModel
{

}
```

The above code immediately enrich our `ViewModel` with change tracking capabilities, nothing else needs to be done in order to implement a basic Undo/Redo support in the ViewModel except writing properties using the Radical [Property System](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/entities/property-system.md).

Given that an object graph can be complex and shaped as we like we need a single entry point to achieve at least two goals:

* Access the current state of the graph;
* Control the state of the graph;

The one component to rule both aspects is the [Change Tracking Service](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/memento/change-tracking-service.md). The next step is to create a `ChangeTrackingService` instance to track the state of the model.

```csharp
class MainViewModel : AbstractMementoViewModel
{
    public MainViewModel()
    {
        var memento = new ChangeTrackingService();
        memento.Attach( this );    
    }
}
```

We created a new instance of the memento service and instructed it to keep track of changes that will occur to `this` instance.

Once we setup the memento we can access the state of the graph via its properties such as `IsChanged`, `CanUndo` and `CanRedo`, or we can control the state of the graph via the exposed methods, such as, but not only, `AcceptChanges()`, `RejectChanges()`, `Undo()` or `Redo()`.

As we said in order to allow a transparent tracking we need to leverage the power of the Radical property system, using properties as the following will immediately trigger the memento and will start keeping track of changes:

```csharp
public String Text
{
    get { return this.GetPropertyValue( () => this.Text ); }
    set { this.SetPropertyValue( () => this.Text, value ); }
}
```

One thing to keep in mind is that every time we write to the property, once the graph is attached to the memento, that write operation will be tracked:

```csharp
class MainViewModel : AbstractMementoViewModel
{
    public MainViewModel()
    {
        var memento = new ChangeTrackingService();
        memento.Attach( this );

        this.Text = "text property default value";
    }

    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }
}
```

Setting the `Text` property default/initial value in the above sample will trigger the `ChangeTrackingService` that now reports its state as changed: `IsChanged` equals `true`.

In the above minimalistic sample it is obvious that the easiest solution is to set the property value *before* attaching the graph to the memento, but this is not always possible:

```csharp
class MainViewModel : AbstractMementoViewModel
{
    public MainViewModel()
    {
        var memento = new ChangeTrackingService();
        memento.Attach( this );

        this.SetInitialPropertyValue( () => Text, "text property default value" );
    }

    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }
}
```

The `SetInitialPropertyValue` method is aware of the fact that a memento can listen to changes and it won't trigger any change in the state.

Note: the `SetInitialPropertyValue` is a shortcut to access the metadata of the `Text` property, it is exactly the same as:

```csharp
this.GetPropertyMetadata( () => this.Text )
    .WithDefaultValue( "text property default value" );
```

What's next:

* dive into the [Change Tracking Service](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/memento/change-tracking-service.md) component.
* Understand how to handle change tracking in [simple ViewModels](/release-1/presentation/abstract-memento-view-model/memento-change-tracking-simple-view-model), [complex ones and collections](/release-1/presentation/abstract-memento-view-model/memento-change-tracking-collection-and-complex-view-model-md).

## Frequently Asked Questions

**Q**: Is `AbstractMementoViewModel` required?\
*A*: No, it is not required, it is handy. A memento entity is required to be a `IMemento` instance, the easiest way to implement a memento entity is to inherit from `MementoEntity`, that since it implements `INotifyPropertyChanged` is it enough to partecipate in the MVVM data binding process. Inheriting from `AbstractMementoViewModel` adds more features such as automatic validation support.

**Q**: Why isn't the `AbstractMementoViewModel` providing me a `ChangeTrackingService` instance?\
*A*: Because there is no 1:1 match between an edited entity and a tracking service, most of the time a single tracking service will track more than one entity at a time.


# Simple ViewModel graphs

When dealing with data editing and the MVVM pattern we need to be aware that the shortest path from the model to the UI is not always the best solution.

Imagine a scenario where we want to edit a `Person` instance that is loaded from a persistente storage, such as a database, the `Person` instance can be directly bound to the UI but it requires us to implement the `INotifyPropertyChanged` interface and if we want to enable it for the `ChangeTrackingService` we need to inherit from a base class.\
Both are not an option when dealing with the Single Responsibility Principle and with POCO objects.

In the above scenario we need to introduce at least two more actors, other than the `Person` data model:

1. A `PersonViewModel` that will be responsible to enrich the Person with property change notification support and with change tracking capabilities;
2. An `EditorViewModel` that will allow a clean separation of responsibilities owning all the  relationship with the memento.

The second bullet is especially true when dealing with complex graph and/or with more than one tracked entity at the same time. Given a `Person` class like the following:

```csharp
class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}
```

We can create a `PersonViewModel` such as:

```csharp
class PersonViewModel : MementoEntity
{
    public void Initialize( Person person, Boolean registerAsTransient )
    {
        if( registerAsTransient )
        {
            this.RegisterTransient();
        }

        this.SetInitialPropertyValue( () => this.FirstName, person.FirstName );
        this.SetInitialPropertyValue( () => this.LastName, person.LastName );
    }

    public String FirstName
    {
        get { return this.GetPropertyValue( () => this.FirstName ); }
        set { this.SetPropertyValue( () => this.FirstName, value ); }
    }

    public String LastName
    {
        get { return this.GetPropertyValue( () => this.LastName ); }
        set { this.SetPropertyValue( () => this.LastName, value ); }
    }
}
```

The first thing is to build a memento-enabled facade, that can grow adding feature, to enable change tracking and property change notifications in a Person-like class.\
In the above sample the `PersonViewModel` and the `Person` class are basically the same, we can say that this is corner case, most of the time in real scenarios there will be a huge difference between the model and the editing view model.

We are introducing a `Initialize` method, for the sake of the sample we can do the same thing using a constructor, using a `Initialize` method allows us to easily resolve `PersonViewModel` instances using an inversion of control container without the need to deal with the currently edited `Person` runtime instance. At initialization time we are doing 2 important things:

1. calling the `RegisterTransient()` method of the base class to register the current instance as transient, if required; To dive into the meaning of a transient entity look at the \[\[Change Tracking Service API]];
2. using the `SetInitialPropertyValue()` method to initialize the default value of the `PersonViewModel` properties without affecting its tracking state;

Once we have setup our `ViewModel` we can build the editor:

```csharp
public class EditorViewModel : AbstractViewModel
{
    readonly IChangeTrackingService service = new ChangeTrackingService();

    public EditorViewModel()
    {
        var observer = MementoObserver.Monitor( this.service );

        this.UndoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanUndo )
            .OnExecute( o => this.service.Undo() )
            .AddMonitor( observer );

        this.RedoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanRedo )
            .OnExecute( o => this.service.Redo() )
            .AddMonitor( observer );

        var person = new Person()
        {
            FirstName = "Mauro",
            LastName = "Servienti"
        };

        var entity = new PersonViewModel();
        this.service.Attach( entity );
        entity.Initialize( person, false );

        this.Entity = entity;
    }

    public ICommand UndoCommand { get; private set; }
    public ICommand RedoCommand { get; private set; }

    public PersonViewModel Entity
    {
        get { return this.GetValue( () => this.Entity ); }
        private set { this.SetValue( () => this.Entity, value ); }
    }
}
```

There is a lot going on here we are creating an editor and at first we setup our `ChangeTrackingService` instance, that in this specific sample is bound to the editor itself. In the constructor we are setting up a [MementoObserver](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/observers/memento-observer.md) to watch the memento instance and we are binding that observer to 2 commands whose role is to expose Undo/Redo functionalities to the UI.\
Last we create a `Person` instance, in real scenarios the `Person` instance is expected to arrive from a persistent storage or a remote resource, we create the `PersonViewModel`, attach it to the memento service and finally initialize it with the person data source.

We finally expose both commands and the `PersonViewModel` instance to the `View`.


# Collections and complex ViewModel graphs

We have already discussed how to handle change tracking in [collections](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/memento/collections.md) and in [complex models](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/memento/complex-graph.md) and we have introduced how to handle change tracking in a [MVVM based model](/release-1/presentation/abstract-memento-view-model/memento-change-tracking-simple-view-model).

We want to start where we left adding a collection to the `Person` class and setup the entire editing pipeline for the collection too.

```csharp
class Person
{
    public Person()
    {
        this.Addresses = new List<Address>();
    }

    public String FirstName { get; set; }
    public String LastName { get; set; }
    public IList<Address> Addresses { get; private set; }
}

class Address
{
    public String Street { get; set; }
    public String City { get; set; }
}
```

If we look at the [considerations we did for the simple view model](/release-1/presentation/abstract-memento-view-model/memento-change-tracking-simple-view-model) is obvious that the `Address` class itself needs a `ViewModel` and an editor and also the collection exposed by the `Person` class needs an editor and potentially a `ViewModel` depending on the type of editing that we want to support.

We need to face a couple more issues related to the fact that having one graph coming from a persistent storage and one different graph bound to the UI we need to keep them in sync.

The `AddressViewModel` will be as simple as the `PersonViewModel` we already saw:

```csharp
class AddressViewModel : MementoEntity
{
    public void Initialize( Address address, Boolean registerAsTransient )
    {
        if( registerAsTransient )
        {
            this.RegisterTransient();
        }

        this.SetInitialPropertyValue( () => this.Street, address.With( a => a.Street ).Return( s => s, "" ) );
        this.SetInitialPropertyValue( () => this.City, address.With( a => a.City ).Return( c => c, "" ) );
    }

    public String Street
    {
        get { return this.GetPropertyValue( () => this.Street ); }
        set { this.SetPropertyValue( () => this.Street, value ); }
    }

    public String City
    {
        get { return this.GetPropertyValue( () => this.City ); }
        set { this.SetPropertyValue( () => this.City, value ); }
    }
}
```

Nothing new, except for the `With`/`Return` syntax that is simply a `monad` like way to guard against `null` adding a default value.

Things get much more interesting as we look at the `PersonViewModel`, that revisited, now handle the `Addresses` list:

```csharp
public class PersonViewModel : MementoEntity
{
    MementoEntityCollection<AddressViewModel> addressesDataSource;

    public void Initialize( Person person, Boolean registerAsTransient )
    {
        if( registerAsTransient )
        {
            this.RegisterTransient();
        }

        this.SetInitialPropertyValue( () => this.FirstName, person.FirstName );
        this.SetInitialPropertyValue( () => this.LastName, person.LastName );

        this.addressesDataSource = new MementoEntityCollection<AddressViewModel>();
        this.addressesDataSource.BulkLoad( person.Addresses, a =>
        {
            return this.CreateAddressViewModel( a, registerAsTransient );
        } );

        this.Addresses = this.addressesDataSource.DefaultView;
        this.Addresses.AddingNew += ( s, e ) =>
        {
            e.NewItem = this.CreateAddressViewModel( null, true );
            e.AutoCommit = true;
        };
    }

    AddressViewModel CreateAddressViewModel( Address a, Boolean registerAsTransient )
    {
        var vm = new AddressViewModel();
        vm.Initialize( a, registerAsTransient );
        return vm;
    }

    protected override void OnMementoChanged( IChangeTrackingService newMemento, IChangeTrackingService oldMemento )
    {
        base.OnMementoChanged( newMemento, oldMemento );
        if( oldMemento != null )
        {
            oldMemento.Detach( this.addressesDataSource );
        }
        if( newMemento != null )
        {
            newMemento.Attach( this.addressesDataSource );
        }
    }

    public String FirstName
    {
        get { return this.GetPropertyValue( () => this.FirstName ); }
        set { this.SetPropertyValue( () => this.FirstName, value ); }
    }

    public String LastName
    {
        get { return this.GetPropertyValue( () => this.LastName ); }
        set { this.SetPropertyValue( () => this.LastName, value ); }
    }

    public IEntityView<AddressViewModel> Addresses
    {
        get;
        private set;
    }
}
```

We are using a `MementoEntityCollection<T>` to keep track of changes that occurs to the collection structure, such as add or address removal, we are using the `BulkLoad` API to achieve 2 goals:

1. Add a transformation on load, we are basically iterating over `Address` instances adding to the collection `AddressViewModel` instances, and the transformation is done in the delegate via the `CreateAddressViewModel` that simply wraps the `Address` instance, if any, into the `AddressViewModel` instance initializing it as we saw for the `Person` / `PersonViewModel` relationship;
2. disable at once collection notifications, a `IEntityCollection<T>` has built-in support for changes notification, and a `MementoEntityCollection<T>` for change tracking, the `BulkLoad` API will disable notifications and tracking for the entire load process re-enabling both at the end;

We then expose our `Addresses` list as an `IEntityView`, that is an `IBindingListView` implementation, achieving 2 goals:

1. In the `View` we can now bind the collection to a `DataGrid`, for example, gaining full support for sorting, filtering and column generation;
2. We can have control, very easily, over new items generation even if the request is done by a `DataGrid` control: simply add a `EventHandler` to the `AddingNew` event of the `IEntityView` and create the expected instance;

The last thing to do is to manually propagate the current `ChangeTrackingService` instance to the collection owned by the `PersonViewModel` class, we do that overriding the `OnMementoChanged` method that is called every time the current memento tracking this instance changes.

The last thing is to update the `EditorViewModel` to create a sample data set; we also add a couple of commands to manage the `Addresses` collection and a property to keep track of the currently selected address:

```csharp
class EditorViewModel : AbstractViewModel
{
    readonly IChangeTrackingService service = new ChangeTrackingService();

    public EditorViewModel()
    {
        var observer = MementoObserver.Monitor( this.service );

        this.UndoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanUndo )
            .OnExecute( o => this.service.Undo() )
            .AddMonitor( observer );

        this.RedoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanRedo )
            .OnExecute( o => this.service.Redo() )
            .AddMonitor( observer );

        this.CreateNewAddressCommand = DelegateCommand.Create()
            .OnExecute( o => 
            {
                this.SelectedAddress = this.Entity.Addresses.AddNew();
            } );

        this.DeleteAddressCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.SelectedAddress != null )
            .OnExecute( o => 
            {
                this.SelectedAddress.Delete();
                this.SelectedAddress = this.Entity.Addresses.FirstOrDefault();
            } )
            .AddMonitor( PropertyObserver.For( this ).Observe( v => v.SelectedAddress ) );

        var person = new Person()
        {
            FirstName = "Mauro",
            LastName = "Servienti"
        };

        person.Addresses.Add( new Address( person )
        {
            City = "My town",
            Street = "Where I live"
        } );

        var entity = new PersonViewModel();
        entity.Initialize( person, false );
        this.service.Attach( entity );
        this.Entity = entity;
    }

    public ICommand UndoCommand { get; private set; }
    public ICommand RedoCommand { get; private set; }
    public ICommand CreateNewAddressCommand { get; private set; }
    public ICommand DeleteAddressCommand { get; private set; }

    public PersonViewModel Entity
    {
        get { return this.GetPropertyValue( () => this.Entity ); }
        private set { this.SetPropertyValue( () => this.Entity, value ); }
    }

    public IEntityItemView<AddressViewModel> SelectedAddress
    {
        get { return this.GetPropertyValue( () => this.SelectedAddress ); }
        private set { this.SetPropertyValue( () => this.SelectedAddress, value ); }
    }
}
```


# Validation and Validation Services

## Validation and Validation Services

One of the most common task during the development of a rich client application is the need to handle the validation of the data input by the user running the application. Radical fully supports WPF validation engine and does all what can be done to alleviate the need for the developer to write infrastructure code.

Let’s start from the end of the story, using a view model like the following:

```csharp
class SampleViewModel : AbstractViewModel, ICanBeValidated
{
    public SampleViewModel()
    {

    }

    protected override IValidationService GetValidationService()
    {
        return new DataAnnotationValidationService<SampleViewModel>( this );
    }

    [Required( AllowEmptyStrings = false )]
    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }
}
```

NOTE: If your project is based on .NET framework 4.5, or greater, the `IRequireValidation` interface can be used instead of the `ICanBeValidated` enabling support for multiple errors per property.

and a view as:

```markup
<TextBox Text="{markup:EditorBinding Path=Text}" Grid.Row="0" Margin="33,47,220,0" Height="25" VerticalAlignment="Top" />
<ListBox Grid.Row="1" Grid.IsSharedSizeScope="True" ItemsSource="{Binding Path=ValidationErrors}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition SharedSizeGroup="propertyName" Width="Auto" />
                    <ColumnDefinition SharedSizeGroup="errorText" Width="*" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding Path=Key}" Margin="0,0,5,0" Grid.Column="0" Foreground="Red" />
                <TextBlock Text="{Binding}" Grid.Column="1" Foreground="Brown" />

            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
```

we immediately get full validation support, even with error summary:

![Validation error and error summary](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/images/cab-be-validated-1.png)

## WPF validation support

Obviously we are not reinventing the wheel, we are simply leveraging the power of the built-in validation support that WPF already has using the `IDataErrorInfo` or the `INotifyDataErrorInfo` interfaces; for a detailed explanation of the WPF validation capabilities take a look a the following MSDN Magazine detailed article: <http://msdn.microsoft.com/en-us/magazine/ff714593.aspx>

## How it works

### ICanBeValidated

The first important piece is the `ICanBeValidated` interface that inherits from the `IDataErrorInfo` interface, the `ICanBeValidated` is defined as follows:

```csharp
public interface ICanBeValidated : IDataErrorInfo
{
    Boolean IsValid { get; }

    ObservableCollection<ValidationError> ValidationErrors { get; }

    Boolean Validate();

    Boolean Validate( ValidationBehavior behavior );

    Boolean Validate( String ruleSet, ValidationBehavior behavior );

    event EventHandler Validated;

    void TriggerValidation();
}
```

All the interface methods and properties are already implemented by the base `AbstractViewModel`, the user is only required to inherit from the interface so to tell to the WPF infrastructure that the `DataContext` of the `View` is a class the implements `IDataErrorInfo`. Going deeper the `ICanBeValidated` interface exposes the following features:

* **IsValid**: determines if the current view model validation failed or is valid;
* **ValidationErrors**: Gives access to a list of validation errors occurred during the validation process;
* **Validate()**: the validate method, and its overloads, allows to manually trigger the validation process, by default the validation process is automatically triggered by WPF for each property set during a data binding operation;
  * **Validate( ValidationBehavior behavior )**;
  * **Validate( String ruleSet, ValidationBehavior behavior )**;
* **Validated**: the validated event is raised each time the validation process is completed;
* **TriggerValidation**: the TriggerValidation method allows to programmatically “ask” to WPF to trigger the error status even on properties, valid or invalid, that has never been involved in a binding write operation;

  The typical scenario is a form with a submit button, if the user never fills the form but simply press the submit button we want to show, visually show, invalid properties/fields to the user, the `TriggerValidation` method allows us to achieve this.

### IRequireValidation

As said before if you are using .NET Framework 4.5, or greater, you can use the new `IRequireValidation` interface that inherits from the `INotifyDataErrorInfo` interface, the `IRequireValidation` is defined as follows:

```csharp
public interface IRequireValidation : INotifyDataErrorInfo
{
    Boolean IsValid { get; }

    ObservableCollection<ValidationError> ValidationErrors { get; }

    Boolean Validate();

    Boolean Validate( ValidationBehavior behavior );

    Boolean Validate( String ruleSet, ValidationBehavior behavior );

    event EventHandler Validated;

    void TriggerValidation();

    void ResetValidation();
}
```

All the interface methods and properties are already implemented by the base `AbstractViewModel`, the user is only required to inherit from the interface so to tell to the WPF infrastructure that the `DataContext` of the `View` is a class the implements `INotifyDataErrorInfo`. Going deeper the `IRequireValidation` interface exposes the following features:

* **IsValid**: determines if the current view model validation failed or is valid;
* **ValidationErrors**: Gives access to a list of validation errors occurred during the validation process;
* **Validate()**: the validate method, and its overloads, allows to manually trigger the validation process, by default the validation process is automatically triggered by WPF for each property set during a data binding operation;
  * **Validate( ValidationBehavior behavior )**;
  * **Validate( String ruleSet, ValidationBehavior behavior )**;
* **Validated**: the validated event is raised each time the validation process is completed;
* **TriggerValidation**: the `TriggerValidation` method allows to programmatically “ask” to WPF to trigger the error status even on properties, valid or invalid, that has never been involved in a binding write operation;

  The typical scenario is a form with a submit button, if the user never fills the form but simply press the submit button we want to show, visually show, invalid properties/fields to the user, the `TriggerValidation` method allows us to achieve this.
* **ResetValidation**: Resets the staus of the validation infrastructure to its default value.

### Validation Services

The other step that must be accomplished by the user is to define the engine used to run the validation process, in order to achieve that is enough to override the protected method `GetValidationService()` that is called, by the infrastructure, once and only once the first time the validation process gets executed.

In the above sample we are using the most powerful validation service provided built-in in Radical, we are using the `DataAnnotationValidationService<TViewModel>` that, as the name implies, works against the [Data Annotation services](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx), and add support for custom inline validation rules.

### Editor bindings

As we have seen WPF requires that the view model inherits from the `IDataErrorInfo` interface, or the new `INotifyDataErrorInfo`, in order to run the validation process, the second requirement is that each binding is configured to enable validation, since there are several properties to set to true this operation tends to be tedious and prone to errors; in order drastically simplify the validation setup [Radical](https://github.com/RadicalFx/radical) offers its \[\[own binding extension|Editor Binding]] with everything setup as expected:

```markup
<TextBox Text="{markup:EditorBinding Path=Text}" />
```

The `EditorBinding` is a standard binding with everything already setup for validation, the `EditorBinding` markup extension can be found in the `http://schemas.topics.it/wpf/radical/windows/markup` xml namespace.

### First time property validation

Another issue of the built-in WPF validation that the Radical validation system solves is the first time validation that WPF runs when a binding operation is performed for the first time, at the property get.

In a scenario where we have a form bound to a view model we do not want to display the form the first time as already invalid, since the user cannot understand why the form is invalid since there has not been any interaction.

In order to solve this scenario the Radical validation system discard the first validation request for each bound property, in order to change this behavior it is enough to override the protected method `ValidationCalledOnceFor( String propertyName )` that the infrastructure calls in order to understand if the given property has been validated at least once.

## Custom validation

In order to build your own validation logic is not necessary to create a custom validation service, even if it possible, because we have already added support for custom validation rules and custom advanced validation in the built-in `DataAnnotationValidationService`.

### Custom rules

There are scenarios in which validation attributes are not enough and we do not want to build a new validation attribute from scratch maybe because we already know that it will be used only in that specific scenario, in this case the best approach is to add a custom validation rule on the fly:

```csharp
protected override IValidationService GetValidationService()
{
    return new DataAnnotationValidationService<SampleViewModel>( this )
        .AddRule
        (
            property: () => this.Text,
            error: ctx => "must be equal to 'foo'",
            rule: ctx => ctx.Entity.Text == "foo"
        );
}
```

We can add as much rule as we want for each property, the context (ctx parameter) passed to the rule evaluation lambda and the error generator lambda has the following shape:

```csharp
public class ValidationContext<TViewModel>
{
    public TViewModel Entity { get; private set; }

    public String RuleSet { get; set; }

    public String PropertyName { get; set; }

    public IValidator<TViewModel> Validator { get; private set; }

    public ValidationResults Results { get; private set; }
}
```

and we can use it to access the whole entity to do a broader validation not specifically scoped to the property we are validating.

### Advanced validation

If none of the above options fit our needs we can integrate into the validation process a fully custom validation piece of code just implementing, in our view model, the `IRequireValidationCallback<TViewModel>` interface:

```csharp
class ValidationSampleViewModel : AbstractViewModel,
        ICanBeValidated,
        IRequireValidationCallback<ValidationSampleViewModel>
{
    public Int32 Sample
    {
        get;
        set;
    }

    public void OnValidate( ValidationContext<ValidationSampleViewModel> context )
    {
        context.Results.AddError( () => this.Sample, "This is fully custom." );
    }
}
```

Each time the validation process run, if the validated view model implements the `IRequireValidationCallback<TViewModel>`, the `OnValidate` method is called allowing us to perform a fully custom validation process.


# UI Composition

## UI Composition

Radical offers a fully flagged UI Composition engine based on the concept of regions.

> A `UI Composition` sample is available in the [Radical-Samples repository](https://github.com/RadicalFx/documentation/tree/master/samples).

## Concepts

A `region` is a named injectable portion of the UI where other components can inject their on content. A region is *attached* to a `DependencyObject` on the UI, depending on the type of the object the region is attached to the region behavior changes. Radical has 3 different main region types:

* `IContentRegion<T>`: a content region is thought for a `ContentPresenter` or a `ContentControl` UIElement, it can host one single content at a time and each time a new content is set the previous one will be removed;
* `IElementsRegion<T>`: an elements region can host multiple contents at a time, it is thought for a `Panel` UIElement, so each WPF control that inherits from panel, such as the `StackPanel`, can be used with an `IElementsRegion`; Content from an `IElementsRegion` can be added or removed and will be available depending on the logic implemented by the underlying UIElement;
* `ISwitchingElementsRegion<T>`: a switching elements region is an element region that, other than being able to host multiple elements at a time, has also the concept of an active element that can change over time; a typical sample is a `TabControl` where each `TabItem` can be seen;

*Note*: each time a content is removed from a region its lifecycle is managed as every View/ViewModel:

* View and ViewModel will be released;
* If View or ViewModel implements `IDisposable` they will be disposed;
* If View or ViewModel implements `IExpectViewClosedCallback` they will receive a callback notification;

Each region is characterized by 2 main attributes:

* is owned by a Region Manager, an `IRegionManager` implementation;
* has a unique name in the set of regions owned by the same Region Manager;

A `RegionManager` is automatically created by the UI Composition engine as soon as a region is added to a `View`, a `RegionManager` is bound to a WPF `Window` instance.

### Nesting

Regions can be nested as preferred, a Window can contain a region that at runtime will contain another region and so on without limitations. For example the following is a valid `logical tree`:

```
Window
  -> Grid
     -> ContentPresenter
        -> IContentRegion<ContentPresenter>
          -> UserControl
            -> Grid
              -> StackPanel
                -> IElementsRegion<StackPanel>
```

In the above sample one single RegionManager will be created at runtime.

## Region Setup

### Region markup definition

First define a region in the XAML where is needed and attach it to the `UIElement` that requires injection:

```
<Window x:Class="Samples.Presentation.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:rg="http://schemas.topics.it/wpf/radical/windows/presentation/regions"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <ContentPresenter rg:RegionService.Region="{rg:ContentPresenterRegion Name=MyRegion}" />
    </Grid>
</Window>
```

**Remarks**

* The `rg` namespace declaration pointing to the Radical region namespace `http://schemas.topics.it/wpf/radical/windows/presentation/regions`;
* A region is attached to a `UIElement` via the `Region` attached property of the `RegionService` element;
* A region is declared as a markup extension whose primary role is to define the region type and the region name;

As soon as we define a region the UI Composition engine, at runtime, will create a `RegionManager` to host the region, RegionManager whose lifecycle is **bound** to the lifecycle of the hosting `Window`. If the region is defined in a `UserControl` the RegionManager lifecycle will be **bound** to the lifecycle of the `Window` hosting the UserControl.

### Region Injection

Once a region is defined in the XAML we need to inject some content, we can inject content in a region in 3 different ways: manually, using partial views or using a declarative approach.

#### Manual injection

Once a View contains a region each time the View is loaded a `ViewLoaded` message is broadcasted to notify that the View has been loaded:

```csharp
class MyViewLoadedHandler : MessageHandler<ViewLoaded>, INeedSafeSubscription
{
    public IViewResolver ViewResolver{ get; set; }
    public IConventionsHandler Conventions{ get; set; }
    public IRegionService RegionService{ get; set; }

    protected override bool OnShouldHandle( ViewLoaded message )
    {
        return message.View is Samples.Presentation.MyView;
    }

    public override void Handle( ViewLoaded message )
    {
        if ( this.RegionService.HoldsRegionManager( message.View ) )
        {
            var view = this.viewResolver.GetView<MyRegionView>();

            var region = this.RegionService.GetRegionManager( message.View )
                .GetRegion<IContentRegion>( "MyRegion" );

            region.Content = view;
        }
    }
}
```

In the above sample we are defining a message handler to handle the `ViewLoaded` message, overriding the `OnShouldHandle` method to define a rule to handle only the ViewLoaded event related to the View we are interested in.

In the `Handle` method we utilize:

* the `RegionService` to determine is the View has a `RegionManager`;
* if the View has a region manager
  * we resolve the content to inject;
  * retrieve a reference to the region manager and to the region;
  * inject the content;

Resources:

* [Radical built-in messages](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/mvvm/built-in-messages.md)
* [Runtime conventions](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/mvvm/runtime-conventions.md)

#### Automatic (aka Partial regions)

Radical UI Composition engine has a concept called `partial view`, a partial view is a `View`, and if defined its `ViewModel`, that can be automatically picked up and injected based on a set of conventions:

* Given a region, as in the previous XAML sample named `MyRegion`;
* Given a View, and an optional ViewModel, that lives in a namespace that matches `*.Presentation.Partial.*`;
* Where the last segment of the View/ViewModel namespace is the region name, in our sample MyRegion;

The View will be resolved, as usual, and injected into the expected region. Given the following namespace structure:

```
MySampleApp
  .Presentation
     .Partial
        .MyRegion
            .MySampleView.xaml
            .MySampleViewModel.cs
```

The MySampleView and it ViewModel, MySampleViewModel, will be automatically injected into the MyRegion region.

#### Declarative

The last option, to inject a `View` in a specific `region`, is to decorate the `View` class with the `InjectViewInRegionAttribute`:

```csharp
[InjectViewInRegion( Named = "MyRegion" )]
class MyUserControlView : UserControl
{

}
```

In the above sample, at runtime, the UI Composition engine will inject an instance of the `MyUserControlView` into the region named "MyRegion".

## Region implementations

As previously said Radical has 3 different region types: `IContentRegion<T>`, `IElementsRegion<T>` and `ISwitchingElementsRegion<T>`. Each region type has a default implementation.

### ContentPresenterRegion

A `ContentPresenterRegion` is a `IContentRegion<ContentPresenter>` that can be applied to a `ContentPresenter UIElement`.

### PanelRegion

A `PanelRegion` is a `IElementsRegion<Panel>`, given that a `Panel` is an abstract class, this region can be used with any `UIElement` that inherits from `Panel`, such as a `StackPanel`.

### TabControlRegion

A `TabControlRegion` is an implementation of the `ISwitchingElementsRegion<TabControl>` and can be used with a `TabControl`.


# Region content lifecycle

A `region`, as every other contet in Radical, has a lifecycle. Depending on the type of the region the lifecycle can be different, but the general approach is the following:

* View and ViewModel will be released;
* If View or ViewModel implements `IDisposable` they will be disposed;
* If View or ViewModel implements `IExpectViewClosedCallback` they will receive a callback notification;

Every region can be `Shutdown`, not explicitely, but by shutting down the `RegionManager` that manages the region. A `RegionManager` shutdown can occour, for example, at application shutdown or when the hosting `Window` is closed. At shutdown time every region managed by the shutdown `RegionManager` will be notified and the region content, in our case the `ViewModel`, has the opportunity to intercept and react to this process.

When ever is region content is removed the entire logical tree of the removed content is inspected to ensure that is it contains any other regions their lifecycle is managed as expected sutting down all the nested regions.

## IContentRegion

An `IContentRegion` notifies its own content `ViewModel`, if any, right before removing the content and once it has been removed. The content `ViewModel` has the opportunity, via the `IExpectViewClosingCallback`, to cancel the removal process and to be notified once the removal is comleted via the `IExpectViewClosedCallback`.

## IElementsRegion

An `IElementsRegion` can host multiple contents at a time, it is designed to notify the `ViewModel`, if any, of the content that will be removed right before removing it and once it has been removed. The content `ViewModel` has the opportunity, via the `IExpectViewClosingCallback`, to cancel the removal process and to be notified once the removal is completed via the `IExpectViewClosedCallback`.

## ISwitchingElementsRegion

An `ISwitchingElementsRegion` can host multiple contents at a time as the `IElementsRegion` and add the concept of an active content that can change over time. It is designed to notify the `ViewModel`, if any, of the content that will be removed right before removing it and once it has been removed. The content `ViewModel` has the opportunity, via the `IExpectViewClosingCallback`, to cancel the removal process and to be notified once the removal is completed via the `IExpectViewClosedCallback`. Other than behaving as a `IElementsRegion` the `ISwitchingElementsRegion` notifies each content `ViewModel` whenever is activated if it implements the `IExpectViewActivatedCallback`.


# TabControl region

The `TabControlRegion` is a standard `switching elements region` that implements the adapter pattern in order to allow the user to add as `content` every XAML content.

The XAML `TabControl` element expects its children to be `TabItem` this is, from the user perspective, very uncomfortable.

It is much easier to deal with a standard `DependencyObject` and expect to be able to add that object as a `TabItem`. The `TabControlRegion` allows us to achieve that.

Allowing us to add a `DependencyObject`, such as a `UserControl`, as the content of a `TabControlRegion` solves only one the issues we have when using a `TabControl`. A `TabControl` is what we call a `headered` element meaning that each `TabItem` is composed by 2 different pieces: the `TabItem` content and the `TabItem` header. The `DependencyObject` we can add as content will be used as the `TabItem` content, in order to define the `TabItem` header we can use the `RegionHeaderedElement.Header` attached property, whose content will be used by the `TabControlRegion` as the `TabItem` header, such as in the following sample:

```
<UserControl x:Class="SampleView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:rg="http://schemas.topics.it/wpf/radical/windows/presentation/regions"
             rg:RegionHeaderedElement.Header="This will be used as header">
</UserControl>
```

The header is not constrained to be a string but can be any valid XAML content.


# Create a custom region

Radical out of the box offers a limited set of regions:

* ContentPresenterRegion;
* PanelRegion;
* TabControlRegion;

Building a custom region is a simple task, the first thing is to decide which type of region we need, depending on 3 factors:

* Single content vs multiple contents in a region;
* If we need multiple contents the next decision is if we need to have an active content, such as a `TabItem` in a `TabControl` or not;

## Menu and MenuItem regions

In a plugin based application is quite common to have the requirement to allow plugins to inject menus and menu items into the application main shell. The easiest way to achieve it is to build custom regions capable of hosting Menus and MenuItems. A region is bound the the XAML element where the `Region` attached property is defined. In a menu we have 2 element types the menu that hosts top level items, and menu items that can have children.

In order to host menu items in a menu via region we can simply use the following code:

```csharp
public class MenuRegion : ElementsRegion<Menu>
{
    public MenuRegion()
    {

    }

    public MenuRegion( String name )
    {
        this.Name = name;
    }

    protected override void OnAdd( DependencyObject view )
    {
        this.Element.Items.Add( ( MenuItem )view );
    }

    protected override void OnRemove( DependencyObject view, RemoveReason reason )
    {
        view.As<MenuItem>( e =>
        {
            if ( this.Element.Items.Contains( e ) )
            {
                this.Element.Items.Remove( e );
            }
        } );
    }
}
```

The important pieces are the `OnAdd` and the `OnRemove` protected methods. Since we are inheriting from a region whose element type is a `Menu` we have an`Element` property vailable that exposes to the region the XAML element the region is bound to, in the above sample the `Menu`. `OnAdd` will be called by the infrastructure whenever there is the need to add a content to the region and `OnRemove` whenever there is the need to remove a content. In the above sample we are simply adding and removing the element from the `Menu` that is hosting us. Following the same approach as above we can define a `MenuItemRegion`:

```csharp
public class MenuItemRegion : ElementsRegion<MenuItem>
{
    public MenuItemRegion()
    {

    }

    public MenuItemRegion( String name )
    {
        this.Name = name;
    }

    protected override void OnAdd( DependencyObject view )
    {
        this.Element.Items.Add( ( MenuItem )view );
    }

    protected override void OnRemove( DependencyObject view, RemoveReason reason )
    {
        view.As<MenuItem>( e =>
        {
            if ( this.Element.Items.Contains( e ) )
            {
                this.Element.Items.Remove( e );
            }
        } );
    }
}
```

that follows the exact same approach as the `MenuRegion`.

## Usage

Once a region is defined its usage is very simple:

```
<Menu rg:RegionService.Region="{crg:MenuRegion Name=MainMenuRegion}">
    <MenuItem Header="File">
        <MenuItem Header="Exit">

        </MenuItem>
    </MenuItem>
</Menu>
```

## Adapters

One important thing to underline looking at the above samples is that a region is bound to an element type but not to a content type, this is in line with the overall XAML philosophy. This means that in the region itself we can adapt the incoming content in order to host it in the best possible way. In the above samples we are expecting the incoming content to be a `MenuItem` but nothing prevents us, as the `TabControlRegion` does, to change the behavior of the region based on the incoming content type. In te above sample what we can do is accept as content every `DependencyObject` and if it is not a valid `MenuItem` wrap it n a `MenuItem` before adding it as content.


# Inversion of Control

[Radical](https://github.com/RadicalFx/radical) Presentation toolkit is completely based on Inversion of Control and Dependency Injection principles but does not force the end user to use any predefined IoC toolkit.

Using a IoC framework is not a requirement at all although some default services implementation relies on the IServiceProvider interface (that exists in the .net framework since v1).

Using a IoC framework is, on the other hand, highly suggested since that the benefit and simplification introduced in the application management greatly overlaps the learning curve of the introduction of the IoC container.

We currently provide out-of-the-box 2 different implementation for 2 different IoC containers:

* [Castle Windsor](/release-1/concepts/index/windsor): the [Nuget](http://nuget.org/) package [Radical.Windows.Presentation.CastleWindsor](http://nuget.org/packages/Radical.Windows.Presentation.CastleWindsor) gives you, without any effort, all the infrastructure required to build MVVM applications based on Windsor as IoC container;
* [Puzzle Container](/release-1/concepts/index/puzzle): at the time of this writing there are no IoC containers that supports WinRT (for Windows 8 store apps) so we decided to provide our own IoC container to get, in store apps, the same support that “desktop” IoC containers gives to desktop apps;
* [Unity v2 and Unity v3](/release-1/concepts/index/unity): the Nuget packages [Radical.Windows.Presentation.Unity2](http://nuget.org/packages/Radical.Windows.Presentation.Unity2) and [Radical.Windows.Presentation.Unity3](http://nuget.org/packages/Radical.Windows.Presentation.Unity3) gives you, without any effort, all the infrastructure required to build MVVM applications based on Unity as IoC container;
* [Autofac](/release-1/concepts/index/autofac): the Nuget package [Radical.Windows.Presentation.Autofac](http://nuget.org/packages/Radical.Windows.Presentation.Autofac) gives you, without any effort, all the infrastructure required to build MVVM applications based on Autofac as IoC container;


# Castle Windsor

As we have already seen in the \[\[quick start|Quick Start (WPF)]] we provide a default implementation of the IoC support using Castle Windsor as IoC container, this implementation is pluggable and completely based on conventions meaning that in most cases you do not need to interact directly with Windsor.

In order to setup the applications using Windsor it’s enough to add a reference to `Radical.Windows.Presentation.CastleWindsor` via [nuget](http://nuget.org/) and configure the application like in the following snippet:

```csharp
public partial class App : Application
{
    public App()
    {
        var bootstrapper = new WindsorApplicationBootstrapper<MainView>();
    }
}
```

In the case you need to register your own components in Windsor and the provided Bootstrap conventions does not satisfies your requirements you can leverage the power of Windsor Installers and MEF, drop a class like the following in your assembly:

```csharp
[Export( typeof( IWindsorInstaller ) )]
public class DefaultInstaller : IWindsorInstaller
{
    public void Install( IWindsorContainer container, IConfigurationStore store )
    {
        //register your components here
    }
}
```

your installer will be automatically wired up at boot time by the infrastructure.

if, for some reason, in your components you need a dependency on the container you can add a dependency directly on IWindsorContainer or on the lightweight IServiceProvider, they are both automatically registered as singleton at boot time.


# Autofac

In order to setup your app using Autofac it’s enough to add a reference to `Radical.Windows.Presentation.Autofac` via [nuget](http://nuget.org/) and configure the application like in the following snippet:

```csharp
sealed partial class App : Application
{
    ApplicationBootstrapper bootstrapper;

    public App()
    {
        this.bootstrapper = new AutofacApplicationBootstrapper<Presentation.MainView>();
    }
}
```

for a detailed explanation of what’s going on take look at the Quick Start. In the case you need to register your own components in Autofac and the provided Bootstrap conventions does not satisfies your requirements you can leverage the power of Autofac module installer and MEF, drop a class like the following in your assembly:

```csharp
public class DefaultModule : IAutofacModule
{
    public void Configure( ContainerBuilder builder, BootstrapConventions conventions, IEnumerable<Assembly> assemblies )
    {
        //register your components here.
    }
}
```

your installer will be automatically wired up at boot time by the infrastructure.

if, for some reason, in your components you need a dependency on the container you can add a dependency directly on IContainer or on the lightweight IServiceProvider, they are both automatically registered as singleton at boot time.


# Unity (v2 & v3)

In order to setup your app using Unity it’s enough to add a reference to `Radical.Windows.Presentation.Unity2` (or Unity3) via [nuget](http://nuget.org/) and configure the application like in the following snippet:

```csharp
sealed partial class App : Application
{
    ApplicationBootstrapper bootstrapper;

    public App()
    {
        this.bootstrapper = new UnityApplicationBootstrapper<Presentation.MainView>();
    }
}
```

for a detailed explanation of what’s going on take look at the Quick Start. In the case you need to register your own components in Unity and the provided Bootstrap conventions does not satisfies your requirements you can leverage the power of Unity installers and MEF, drop a class like the following in your assembly:

```csharp
public class DefaultInstaller : IUnityInstaller
{
    public void Install( IUnityContainer container, BootstrapConventions conventions, IEnumerable<Types> allTypes )
    {
        //register your components here.
    }
}
```

your installer will be automatically wired up at boot time by the infrastructure.

if, for some reason, in your components you need a dependency on the container you can add a dependency directly on IUnityContainer or on the lightweight IServiceProvider, they are both automatically registered as singleton at boot time.


# Puzzle Container

If you are building a Windows 8 app, based on WinRT, you can use our own built-in IoC container (Puzzle, originally built a couple of years ago to support Silverllight and Windows Phone).

In order to keep things simple we have tried to mimic the Windsor behavior, so if you are used to Windsor the Puzzle container will give the same familiar environment.

In order to setup your app using Puzzle it’s enough to add a reference to `Radical.Windows.Presentation.Puzzle` via [nuget](http://nuget.org/) and configure the application like in the following snippet:

```csharp
sealed partial class App : Application
{
    ApplicationBootstrapper bootstrapper;

    public App()
    {
        this.InitializeComponent();

        this.bootstrapper = new PuzzleApplicationBootstrapper<Presentation.MainView>();
    }
}
```

for a detailed explanation of what’s going on take look at the WinRT Quick Start. In the case you need to register your own components in Puzzle and the provided Bootstrap conventions does not satisfies your requirements you can leverage the power of Puzzle Descriptors and MEF: drop a class like the following in your assembly:

```csharp
[Export( typeof( IPuzzleSetupDescriptor ) )]
public class DefaultDescriptor : IPuzzleSetupDescriptor
{
    public async Task Setup( IPuzzleContainer container, Func<IEnumerable<TypeInfo>> knownTypesProvider )
    {
        //register your components here.
    }
}
```

your installer will be automatically wired up at boot time by the infrastructure.

if, for some reason, in your components you need a dependency on the container you can add a dependency directly on IPuzzleContainer or on the lightweight IServiceProvider, they are both automatically registered as singleton at boot time.


# Entities


# Property System

## Property System

WPF has a really nice feature called Dependency Property, from the user perspective a dependency property is a standard CLR property that add, on top of CRL properties, a set of really nice and powerful features:

1. Property value inheritance;
2. Property metadata;
3. Property change notification;
4. Support for default value generation;
5. *…and many others strictly related to WPF;*

The [Radical](https://github.com/RadicalFx/radical) assembly where the property system lives is totally non-related to WPF in any way, we have simply decided to bring the power of dependency-like properties in order to give some interesting boost to certain part of the Radical framework.

One really interesting thing of the dependency properties, the WPF ones, is that values and metadata are stored at the root object level, we inherited that concept in our `Entity` base abstract class; lots of Radical stuff inherit from the `Entity` base class so to obtain something really interesting:

```csharp
class MyObject : Entity
{
    public String MyProperty
    {
        get{ return this.GetPropertyValue( () => this.MyProperty ); }
        set{ this.SetPropertyValue( () => this.MyProperty, value ); }
    }
}
```

what we see here is what we call a Radical property (RP), that from the outside is viewed, and behaves, like a standard CLR property but, from the inside, is totally managed by the `Entity` base class, and in our object we only expose a property.

## Property change notification

The first thing we get using a Radical property is property change notification, the base `Entity` class implements `INotifyPropertyChanged` and automatically fires the event whenever the property really changes; really means that subsequently setting the same value more than once fires the event only the first time.

## Property Metadata

Since we have everything managed by the base class, thus the base class holds all the properties and property values we can easily introduce the concept of `csharp` attached to a property without requiring the inheriting class to do nothing:

```csharp
class MyObject : Entity
{
    public MyObject()
    {
        var metadata = this.GetPropertyMetadata( () => this.MyProperty );
    }

    public String MyProperty
    {
        get { return this.GetPropertyValue( () => this.MyProperty ); }
        set { this.SetPropertyValue( () => this.MyProperty, value ); }
    }
}
```

We are retrieving the default property metadata for the given property, using metadata the first thing we can do is to define the property default value.

## Default Value

The property default value is requested the first time a property get is issued, we will use the property metadata to define the default value for a property because we do not want to trigger a PropertyChanged event for the simple fact of defining a default, initial value:

```csharp
public MyObject()
{
    var metadata = this.GetPropertyMetadata( () => this.MyProperty );

    metadata.DefaultValue = "this is the default value";
}
```

but much more interesting is the possibility to intercept the default value request using a lambda:

```csharp
public MyObject()
{
    var metadata = this.GetPropertyMetadata( () => this.MyProperty );

    metadata.DefaultValueInterceptor = () => "this is the default value";
}
```

so to be able to perform some logic when the default value is requested. Both approaches can be used in a fluent manner:

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .WithDefaultValue( "this is the default value" );
}

public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .WithDefaultValue( () => "this is the default value" );
}
```

## Cascade changes

once we have property metadata we can add some interesting features such as cascade change notifications:

```csharp
class MyObject : Entity
{
    public MyObject()
    {
        this.GetPropertyMetadata( () => this.MyProperty )
            .AddCascadeChangeNotifications( () => this.AnotherProperty );
    }

    public String MyProperty
    {
        get { return this.GetPropertyValue( () => this.MyProperty ); }
        set { this.SetPropertyValue( () => this.MyProperty, value ); }
    }

    public Int32 AnotherProperty
    {
        get { return 0 /* e.g. runtime evaluated property */; }
    }
}
```

in this sample each time the MyProperty changes the PropertyChanged event is raised even for the AnotherProperty property. The RemoveCascadeChangeNotifications can be used to remove a cascade change notification previously added.

## Disable change notifications

by default all the radical properties notify of their change, if we want to disable change notifications for a specific property we’ll use once again property metadata:

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .DisableChangesNotifications();
}
```

at a later time changes can be re-enabled using the EnableChangeNotifications method.

## Change detection

In the case we need to detect the change of a property from within the object itself we can use property metadata:

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .OnChanged( pvc => 
        {
            //invoked whenever the property changes
        } );
}
```

or directly interact with the property definition:

```csharp
public String MyProperty
{
    get { return this.GetPropertyValue( () => this.MyProperty ); }
    set { this.SetPropertyValue( () => this.MyProperty, value, pvc => 
    {
        //invoked whenever the property changes
    } ); }
}
```

in both cases we get access to the current property value and to old property value.


# Messaging and Message Broker

The message broker pattern is basically a way to decouple the sender of an event/message and the subscribers of that message, in a standard event-based approach the subscriber needs in order to subscribe to an event:

1. a reference to the publisher;
2. knowledge of the event “shape”;

In lots of cases we need to be able to let 2 different components speak to each other in a more decoupled way since we have no easy way to satisfy the first point, in this cases introducing a third actor, the broker, that both knows is a really simple way to solve the original problem:

![Messaging diagram](/files/-LQVINy9w4fgBgei5X7Y)

Radical has its own built-in broker implementation represented by the `IMessageBroker` interface and by the default MessageBroker implementation found in the Radical assembly.

**Usage**

The first thing we need to do is to create an instance of the broker:

```csharp
var broker = new MessageBroker( new NullDispatcher() );
```

> the broker itself has a dependency on the `IDispatcher` interface, an `IDispatcher` is basically a wrapper of the `SynchronizationContext`. We wrap it in a `IDispatcher` instance in order to simplify the sharing of the codebase of the broker among different technologies, such as WPF, WinRT or Silverlight.
>
> In the above sample we are using a default `NullDispatcher` that does nothing and is ideal in Console or web application where marshaling calls in the main thread is not mandatory. Each Radical specific implementation has its own dispatcher: `WpfDispatcher`, `SilverlightDispatcher`, etc..

Once we have created the broker we can share it among all the components that need it:

```csharp
var sampleSender = new SenderComponent(  broker );
var sampleReceiver = new ReceiverComponent( broker );
```

The third thing we need is something to exchange between components:

```csharp
class SampleMessage : IMessage
{
    public SampleMessage( Object sender )
    {
        this.Sender = sender;
    }

    public Object Sender{ get; private set; }
}
```

> [POCO messages](/release-1/concepts/message-broker/poco-messages) are now fully supported.

Now that we have 2 components, a broker and something that we want to share from one component to the other we can use it in the following manner:

```csharp
class SenderComponent
{
    IMessageBroker broker;

    public SenderComponent( IMessageBroker broker )
    {
        this.broker = broker;
    }

    public void Publish()
    {
        this.broker.Broadcast( new SampleMessage( this ) );

        //the POCO API will be:
        //this.broker.Broadcast( this, new SampleMessage() );
        //without the need for the message to implement the IMessage interface.
    }
}
```

and from the receiver point of view:

```csharp
class ReceiverComponent
{    
    IMessageBroker broker;

    public SenderComponent( IMessageBroker broker )
    {
        this.broker = broker;
        this.broker.Subscribe<SampleMessage>( this, msg => 
        {
            //handle the message here.
        } );
    }
}
```

**Dispatch vs. Broadcast**

In the sample above the “sender” utilizes the Broadcast method, broadcasted messages will be delivered to subscribers asynchronously, and in parallel, thus the subscriber is invoked on a thread that is not the same as the publisher.

If we, for some reason, need to be have events dispatched in a synchronous manner we can use the Dispatch method that guarantees that all the subscribers a re invoked on the same thread of the publisher in a serial way.

**InvocationModel**

In our experience the most frequent usage of the broker is within the management of the UI of an application based on the MVVM pattern, in this case in most cases the subscriber of the event needs to access the UI, thus needs to run on the UI/Main thread.

If we want to reduce the friction and we do not need to have control on the marshaling process we can ask the broker to automatically call the subscriber on the main thread for us:

```csharp
this.broker.Subscribe<SampleMessage>( this, InvocationModel.Safe, msg =>
{
    //this delegate is automatically invoked on the main thread.
} );
```

Using the subscribe overload that accept an InvocationModel enum parameter we can specify that we, as subscribers, need that the given delegate must be invoked in the main thread.

Please note that the broadcast is still asynchronous and the broker only dispatches on the main thread the given delegate only when required.

**Subscriptions using inheritance**

One interesting thing we can do is subscribe to a base class in order to receive all the messages that inherits from the specified type:

```csharp
this.broker.Subscribe<IMessage>( this, msg =>
{
    //all the messages that inherits from IMessage we'll be handled also here.
} );
```

In the above sample we are basically building a catch all handler.


# POCO messages

The Radical [message broker](/release-1/concepts/message-broker) supports also POCO messages, it is not required, anymore, that a class, in order to be a first class message, implements the `IMessage` interface.

> Side note: The `IMessage` interface, and all the `IMessageBroker` operations that depends on it, are now marked as obsolete. It is highly suggested that all the message broker dependent code will be migrated to the new POCO version even if the old one will be fully supported and can safely be used in a mixed environment.

All the features supported by the old version of the message broker are supported even by the new POCO version. The only difference is in the signature of the broadcast, dispatch and subscribe methods.

## Subscribe

the new available signatures are:

```
void Subscribe( object subscriber, object sender, Type messageType, Action<object, object> callback );
void Subscribe( object subscriber, object sender, Type messageType, InvocationModel invocationModel, Action<object, object> callback );
void Subscribe( object subscriber, Type messageType, Action<object, object> callback );
void Subscribe( object subscriber, Type messageType, InvocationModel invocationModel, Action<object, object> callback );
void Subscribe<T>( object subscriber, Action<object, T> callback );
void Subscribe<T>( object subscriber, object sender, Action<object, T> callback );
void Subscribe<T>( object subscriber, object sender, InvocationModel invocationModel, Action<object, T> callback );
void Subscribe<T>( object subscriber, InvocationModel invocationModel, Action<object, T> callback );
```

Where the main differences are:

* The generics constraints have been removed;
* The signature of the action callback delegate now has 2 parameters, instead of the single `IMessage` one, where the first object parameter is the sender of the message and the second is the message itself;

## Broadcast & Dispatch

there is only a new simplified signature for the broadcast method:

```
void Broadcast( Object sender, Object message );
```

And even for the dispatch method things get simpler:

```
void Dispatch( Object sender, Object message );
```


# Standalone message handlers

We have analyzed why we need a [messaging system](/release-1/concepts/message-broker) and how to interact with it at runtime sending and receiving messages.

There are scenarios in which the code that receive the message has nothing to do with the UI so there is no reason to subscribe to that message in a `ViewModel`, in this cases we can use stand alone message handlers to have a class that will be instantiated and executed at runtime each time a new message, in which we are interested, is received:

```csharp
class MyMessageHandler : AbstractMessageHandler<MyMessage>
{
    public override void Handle( object sender, MyMessage message )
    {
        //handle my message here.
    }
}
```

When using [message broker and messages](/release-1/concepts/message-broker) in the context of a MVVM based application Radical [bootstrap conventions](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/mvvm/bootstrap-conventions.md), at boot time, will take care of registering, in the container of choice, all standalone message handlers that match the conventions. That in this case is when classes are defined in a namespace ending with `*.Messaging.Handlers`.


# Observers

In rich client applications user interaction is generally performed via many user interface elements, such as menus, buttons, hyperlinks and mouse clicks/double clicks on UI elements, most of the time multiple different interactions lead to the same action to be performed. In cases like these the way to go in WPF and Universal Applications is to use the `ICommand` interface to build commands, such as the [DelegateCommand](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/mvvm/delegate-command.md).

There are scenarios, although, where the problem we need to face cannot be solved using commands, or using only commands, maybe we need to observe multiple conditions and react each time one of them changes. In this case generally we fall into 2 traps:

* We start polling for changes instead of waiting to be notified that something we are interested in is changed;
* We distribute the polling code near what we want to observe instead of near to where we want to react to the change;

In both cases we are complicating things each time we need to update our logic that is spread all over the places.

Radical observers are there to fix the issue, the provide the same approach provided by the .Net Reactive Extensions in a much simplistic way, we are not expecting to provide anything better than reactive extensions, we are simply providing an easy solution to a well known issue.

Observers are classes the implements the `IMonitor` interface that basically adds a `Changed` event to the observer allowing others to hook the event and be notified when something changes.


# PropertyObserver

The simplest observer, or monitor, in the Radical framework is a `PropertyObserver` the role of a property observer is to monitor property changes of a class implementing the `INotifyPropertyChanged` interface. We can monitor single properties:

```csharp
var monitor = PropertyObserver.For( person )
    .Observe( p => p.FirstName )
    .Observe( p => p.LastName );

monitor.Changed += ( s, e ) => 
{
    //occurs when one of the properties change.
};
```

Or we can monitor the entire entity being notified each time a property changes:

```csharp
var monitor = PropertyObserver.ForAllPropertiesOf( person );
monitor.Changed += ( s, e ) =>
{
    //occurs when one of the properties change.
};
```

We can use a monitor to trigger, for example, the `CanExecuteChanged` event of a `ICommand` interface implementation:

```csharp
var monitor = PropertyObserver.ForAllPropertiesOf( person );
DelegateCommand.Create()
    .OnCanExecute( state =>
    {
        //evaluate if the command can be executed.
        return true;
    } )
    .OnExecute( state =>
    {
        //execute the command
    } )
    .AddMonitor( monitor );
```

In the above sample each time one of the property of the `Person` instance changes the command state will be evaluated for execution allowing the command to change its `CanExecute` state without polling anything but simply waiting to be notified.


# MementoObserver

A memento observer, or monitor, is an instance of the `MementoObserver` class that is capable to observe, and react, to changes that occurs to a `ChangeTrackingService` instance.

```csharp
var memento = new ChangeTrackingService();
var monitor = MementoObserver.Monitor( memento );
```

We can use a monitor to trigger, for example, the `CanExecuteChanged` event of a `ICommand` interface implementation:

```csharp
var memento = new ChangeTrackingService();
var monitor = MementoObserver.Monitor( memento );

DelegateCommand.Create()
    .OnCanExecute( state =>
    {
        //evaluate if the command can be executed.
        return true;
    } )
    .OnExecute( state =>
    {
        //execute the command
    } )
    .AddMonitor( monitor );
```

The above code is not very different from manually attaching the `TrackingStateChanged` event of the `ChangeTrackingService` instance and manually calling the `RaiseCanExecuteChanged` method of the `DelegateCommand` instance, it is simply more concise and easier to maintain.


# BrokerObserver

As for the [PropertyObserver](/release-1/concepts/index-1/property-observer) or the [MementoObserver](/release-1/concepts/index-1/memento-observer) the BrokerObserver is an easy shortcut to react to message arrivals when using [the message broker](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/messaging/message-broker.md).

```csharp
var broker = //instance of a IMessageBroker implementation.
var monitor = BrokerObserver.Using( broker )
    .WaitingFor<MySampleMessage>();
```

We can use a monitor to trigger, for example, the `CanExecuteChanged` event of a `ICommand` interface implementation:

```csharp
var broker = //instance of a IMessageBroker implementation.
var monitor = BrokerObserver.Using( broker )
    .WaitingFor<MySampleMessage>();

DelegateCommand.Create()
    .OnCanExecute( state =>
    {
        //evaluate if the command can be executed.
        return true;
    } )
    .OnExecute( state =>
    {
        //execute the command
    } )
    .AddMonitor( monitor );
```

What the above code does is to trigger the `CanExecuteChanged` logic each time a message of type `MySampleMessage` is delivered via the monitored message broker.


# Change Tracking Service

Dealing with complex graphs of objects can be complicated and can get more complicated as the graph evolve or gets huge.

Let us start from the end of the story, what we want to achieve in our software solutions is something like the following sample code:

```csharp
var person = new Person();
person.FirstName = "first name value";
person.LastName = "last name value";

var address =  new Address();
address.Street = "street address value";

person.Addresses.Add( address );
```

Given the above code snippet we have basically 2 requirements:

* Know the state of the graph:
  * Is it changed?
  * Is there something that can be undone?
  * Is there something that can be redone?
* Change the state of the graph:
  * Accept all changes at once;
  * Reject all changes at once;
  * Undo a single change;
  * Redo a single change;&#x20;

But there is more, from the user perspective a single change can be reflected in more than one action, and thus change, in the code itself:

```csharp
var order = new Order();
order.Customer = ... //reference to a customer object;

// --> begin of "atomic" operation
var item = new OrderItem();
item.ItemId =  123;
item.Quantity = 2;
order.Items.Add( item );
// --> end of "atomic" operation
```

In the above sample the creation of the order item, the set of its properties and the add to the items collection, from the user perspective, are a single operation that matches the `add to cart` operation, given this assumptions an undo operation should rollback the entire change set and only the last operation, the add in this case.

Given these requirements the next step is to rely on something that allows us to transparently handle the entire change tracking process, the first step is to understand what [MementoEntity and MementoEntityCollection](/release-1/memento/change-tracking-service/memento-entities) are.


# MementoEntity and MementoEntityCollection

When we spoke about the [Change Tracking Service](/release-1/memento/change-tracking-service) we introduced a code snippet such as the following:

```csharp
var person = new Person();
person.FirstName = "first name value";
person.LastName = "last name value";
```

In order to leverage the full power of the memento services we can change the above snippet as follows:

```csharp
var memento = new ChangeTrackingService();

var person = new Person();
memento.Attach( person );

person.FirstName = "first name value";
person.LastName = "last name value";

var isChanged = memento.IsChanged; //true
var canUndo = memento.CanUndo; //true
```

Calling `memento.Undo()` will trigger the undo of the last operation, we can call undo until `CanUndo` is `true` rolling back change by change, that in the above sample will revert back the `LastName` property value to its default value.

The requirement to achieve the above is that the `Person` class is a Radical *memento* entity:

```csharp
class Person : MementoEntity
{   
    public String FirstName
    {
        get { return this.GetPropertyValue( () => this.FirstName ); }
        set { this.SetPropertyValue( () => this.FirstName, value ); }
    }

    public String LastName
    {
        get { return this.GetPropertyValue( () => this.LastName ); }
        set { this.SetPropertyValue( () => this.LastName, value ); }
    }
}
```

As we can see from the above snippet all we need to do is to create a class the inherits from the `MementoEntity` base class and declare all the properties we want to track as [Radical properties](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/entities/property-system.md).

A similar approach can be used to keep track of items in a collection:

```csharp
var memento = new ChangeTrackingService();

var list = new MementoEntityCollection<String>();
memento.Attach( list );

list.Add( "a value" );
list.Add( "another value" );

var isChanged = memento.IsChanged; //true
var canUndo = memento.CanUndo; //true
```

Calling `memento.Undo()` will trigger the undo of the last operation that in the above sample will revert the collection status removing the last added value.

We can do more:

* [Handling change tracking in a simple model](/release-1/memento/change-tracking-service/handling-change-tracking/simple-model);
* [Handling change tracking in collections](/release-1/memento/change-tracking-service/handling-change-tracking/collections);
* [Handling change tracking in complex objects graph](/release-1/memento/change-tracking-service/handling-change-tracking/complex-graph);


# Handling change tracking:


# Simple model

We briefly introduced [MementoEntity and MementoEntityCollection](/release-1/memento/change-tracking-service/memento-entities) and seen a code snipped that allows us to attach the memento tracking system to an entity:

```csharp
var memento = new ChangeTrackingService();

var person = new Person();
memento.Attach( person );

person.FirstName = "first name value";
person.LastName = "last name value";

var isChanged = memento.IsChanged; //true
var canUndo = memento.CanUndo; //true
```

What is happening is that each change performed on each tracked entity will be recorded by che `ChangeTrackingService`, on each tracked entity means that the following will work as expected:

```csharp
var memento = new ChangeTrackingService();

var person = new Person();
var customer = new Customer();
memento.Attach( person );
memento.Attach( customer );

person.FirstName = "first name value";
person.LastName = "last name value";
customer.CompanyName = "sample company";

var isChanged = memento.IsChanged; //true
var canUndo = memento.CanUndo; //true
```

Tracking at the same time both the `Person` instance and the `Customer` instance. The following sample highlights how changes are tracked:

```csharp
var memento = new ChangeTrackingService();

var person = new Person();
memento.Attach( person );

person.FirstName = "a name";
person.LastName = "last name";

var isChanged = memento.IsChanged;
var state = memento.GetEntityState( person );

memento.Undo();
var _lastNameAfterUndo = person.LastName; //null

memento.Redo();
var _lastNameAfterRedo = person.LastName; //"last name"
```

The memento keeps tracks of a stack of changes in the exact same order they happened to the tracked models, each time `Undo()` is called the last change in the stack will be reverted and moved into the forward changes stack allowing the caller to call `Redo()` in order to apply it once again.

Calling `AcceptChanges()` on a memento instance will flush all the recorded changes considering the models as unchanged. Calling `RejectChanges()` will revert all the tracked models to their original state, or to the state we called `AcceptChanges()` last time.

The same applies also to collections: [Handling Change Tracking in collections](/release-1/memento/change-tracking-service/handling-change-tracking/collections)


# Collections

We briefly introduced [MementoEntity and MementoEntityCollection](/release-1/memento/change-tracking-service/memento-entities) and seen how to [track changes in a simple graph](/release-1/memento/change-tracking-service/handling-change-tracking/simple-model).

We can go further and introduce collection change tracking:

```csharp
var list = new MementoEntityCollection<String>();
memento.Attach( list );

list.Add( "a" );
list.Add( "b" );
list.Add( "c" );

var count = list.Count; //3

memento.Undo();
var _count = list.Count; //2

memento.Redo();
var __count = list.Count; //3
```

The `MementoEntityCollection<T>` being a memento entity will keep track of changes applied to collection structure. Each change will be tracked, starting from `Add` and `Remove` to `Clear`, `Insert`, `InsertAt`, etc...

```csharp
var list = new MementoEntityCollection<Person>();
memento.Attach( list );

list.Add( new Person() );
```

Adding a `MementoEntity`, such as `Person`, will automatically trigger the memento that will start tracking the `Person` instance:

```csharp
var list = new MementoEntityCollection<Person>();
memento.Attach( list );

var person = new Person();
list.Add( person );

person.FirstName = "name";

memento.Undo(); //the person first name is reverted
memento.Undo(); //the person instance is removed from the collection
memento.Redo(); //the person instance is added once again to the collection
```

As expected the changes stack is handled in the correct order. The next step is to understand how to [handle change tracking in complex objects graph](/release-1/memento/change-tracking-service/handling-change-tracking/complex-graph).


# Complex objects graph

We briefly introduced [MementoEntity and MementoEntityCollection](/release-1/memento/change-tracking-service/memento-entities) and seen how to [track changes in a simple graph](/release-1/memento/change-tracking-service/handling-change-tracking/simple-model) and in [collections](/release-1/memento/change-tracking-service/handling-change-tracking/collections).

The last type of graph we want to be able to track is a complex graph, where at least one of the properties of the root tracked object is a memento entity or a memento collection itself:

```csharp
class Person : MementoEntity
{
    public Person()
    {
        this.Addresses = new MementoEntityCollection<Address>();
    }

    public String FirstName
    {
        get { return this.GetPropertyValue( () => this.FirstName ); }
        set { this.SetPropertyValue( () => this.FirstName, value ); }
    }

    public String LastName
    {
        get { return this.GetPropertyValue( () => this.LastName ); }
        set { this.SetPropertyValue( () => this.LastName, value ); }
    }

    public IList<Address> Addresses { get; private set; }
}

class Address : MementoEntity
{   
    public String Street
    {
        get { return this.GetPropertyValue( () => this.Street ); }
        set { this.SetPropertyValue( () => this.Street, value ); }
    }
}
```

In the above sample the `Person` class has a property, `Addresses`, whose type is itself a memento entity, a `MementoEntityCollection<Address>` in this specific case. Using the following snippet:

```csharp
var memento = new ChangeTrackingService();

var person = new Person();
memento.Attach( person );
```

the `Addresses` collection is not automatically tracked, the memento does not know anything of the structure of the graph. We can update the `Person` class so to instruct the memento that also the `Addresses` collection needs to be tracked:

```csharp
class Person : MementoEntity
{
    protected override void OnMementoChanged( IChangeTrackingService newMemento, IChangeTrackingService oldMemento )
    {
        base.OnMementoChanged( newMemento, oldMemento );
        if( oldMemento != null ) 
        {
            oldMemento.Detach( this.Addresses );
        }
        if( newMemento != null ) 
        {
            newMemento.Attach( this.Addresses );
        }

    //rest of the Person class code
}
```

We are intercepting the moment in which the `Person` instance is tracked by the memento service overriding the `OnMementoChanged` and we are manually propagating the memento to inner instances. It is important to remove, detach, the memento entity from the previous memento instance if any, a memento entity can be tracked by one memento only at a time.

Note: changes to a `MementoEntityCollection<T>` automatically propagates the memento service to list items if they are a memento entity.


# Atomic operations

When dealing with a change tracking system based on the memento pattern one of the complex problem we can face is that the atomicity of the operation as seen by the user does not match the atomicity as seen by the system.

Imagine a scenario where we have a list of items, ordered by some criteria such as a date for example, and the system we are designing needs to allow the user to move items, the issue is that what from the user perspective is a single operation, a move, from the system perspective is a multiple operation, a move plus the update of all the other items to keep dates, for example, in sync.

In the above scenario a `Undo()` operation on the memento won't produce the expected result, unless we instruct the memento itself:

```csharp
var memento = new ChangeTrackingService();

var person = new Person();
memento.Attach( person );

using( var op = memento.BeginAtomicOperation() )
{
    person.FirstName = "a name";
    person.LastName = "last name";

    op.Complete();
}
```

At the end of the atomic operation, when `Complete()` is called, the state of the `Person` instance is changed but the stack contains one single change that, if undone, will revert back both the `FirstName` and `LastName` properties.

One important thing to keep in mind is that an atomic operation is not limited to a single object, multiple tracked instances can partecipate in the same atomic operation.


# Change Tracking Service API

The [memento service](/release-1/memento/change-tracking-service) implement the `IChangeTrackingService` interface, that inherits from the `IRevertibleChangeTracking`, `IDisposable` and `IComponent` interfaces.

All the memento entities implement the `IMemento` interface.

## Basic operations

* `Attach( IMemento item )` / `Detach( IMemento entity )`: attach and detach are the 2 methods to manually control when an instance is attached or detached to and from the memento instance. As soon as an instance is attached it will be tracked for changes and the memento will stop tracking it at detach time.
* `Undo()` / `Redo()`: Undo and Redo controls the state of the tracked entities, calling `Undo` will revert the last tracked operation, if any, calling `Redo` will apply the last operation that has been undone, if any;
* `CanRedo` and `CanUndo` allows the user code to determine if calling Undo and Redo operations something will be done;&#x20;
* `RegisterTransient( Object entity )` and `RegisterTransient( Object entity, Boolean autoRemove )` allows the user to register an entity as a transient, versus persistent, entity. &#x20;

  &#x20; Registering transient entities is not really required for the memento to work properly, it is on the other hand very handy for the user if the code needs at a certain point to deal with a storage trying to understand which operations should be done to align the storage with the current in memory state. if `autoRemove` is set to `true` (*the default value*) and `RejectChanges()`, or an `Undo()` that removes the last `IChange` of the object, is called the object then is automatically removed from the list of the new objects. &#x20;

  &#x20; When it is the case to set `autoRemove` to `false`? The question should be: a transient untouched entity should be considered as changed? Or from the user perspective: a transient untouched entity should trigger a question to the user such as "Do you want to save your changes?", if the answer is yes then set `autoRemove` to `false`;
* `UnregisterTransient( Object entity )` manually remove the given transient entity from the list of transient entities;
* `HasTransientEntities` determines if the the memento is currently tracking transient entities;
* `GetEntityState( Object entity )` return, given a tracked entity, the current entity state as seen by the memento, the returned value is a `EntityTrackingStates` enumeration that can assume one, or more, of the following values:
  * `None`:  The state of the entity is not changed, the entity is not transient or the entity is not tracked;
  * `IsTransient`: The entity is registered as transient;
  * `AutoRemove`: if an entity is marked as `AutoRemove` (the default behavior) and `RejectChanges`, or an `Undo` that removes the last `IChange` of the entity, is called then the entity is  automatically removed from the list of the transient entities;
  * `HasBackwardChanges`: The entity is changed and has changes that can be undone, meaning that `Undo` can n be called;
  * `HasForwardChanges`: The entity has changes that can be reapplied, meaning that `Redo` can be called;
* `BeginAtomicOperation()`: begins an [atomic operation](/release-1/memento/change-tracking-service/atomic-operations) returned as a `IAtomicOperation` instance on which the caller is expected to call `Complete()` to store it in the changes stack;

## Searches

* `GetEntities()` and `GetEntities( EntityTrackingStates sateFilter, Boolean exactMatch )` allows the caller to retrieve the list of the currently tracked entities and/or to search for them based on their current state;

## Suspend and Resume

* Using `Suspend()` and `Resume()` it is possible to momentarily ask the memento service to stop tracking changes to the currently tracked entities;
* `IsSuspended` determines if the memento is currently suspended or not;

## Events

* `TrackingServiceStateChanged`: each time the internal state of the memento changes the `TrackingServiceStateChanged` event is raised;
* `ChangesAccepted` and `ChangesRejected` are called, respectively, when changes are accepted or rejected;
* `AcceptingChanges` and `RejectingChanges` are events raised to inform that the memento is in the process of accepting or rejecting changes, both can be cancelled;

## Bookmarks

* `CreateBookmark()`: allows to create a bookmark, an `IBookmark` instance, that represents a point in the changes stack useful to revert changes to a known point in a single step;
* `Revert( IBookmark bookmark )`: given a bookmark revert all the changes at the given point in time deleting the bookmark once done;
* `Validate( IBookmark bookmark )`: verifies that a bookmark is still valid, it exists in the changes stack;

## ChangeSets and Advisories

* `GetChangeSet()` and `GetChangeSet( IChangeSetFilter builder )` return a `IChangeSet` that is a list of all the currently tracked changes, it is possible to use a `IChangeSetFilter` implementation to filter the list of changes returned;
* `GetAdvisory()` and `GetAdvisory( IAdvisoryBuilder builder )` return a `IAdvisory`, an advisory is a list of proposed actions that the memento thinks should be applied to align the current state in memory with a persistent storage. If a tracked entity is registered as transient and has changes the advisory will suggest to `create` it, on the other hand if it is not registered as transient and has pending changes will suggest to `update` it. One interesting feature is that if a tracked entity is removed from a `MementoEntityCollection<T>` the advisory will suggest to `delete` it. &#x20;

  *Note: It is up to the user to apply the suggested changes to the persistent storage*.


# Property Metadata for the ChangeTrackingService

A `MementoEntity`, being a Radical `Entity`, will benefit of the [Property System](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/entities/property-system.md) and of the properties metadata the the property system adds. A `MementoEntity` enriches the property system basic metadata adding some behaviors directly related to the memento services.

`DisableChangesTracking()` and `EnableChangesTracking()` change tracking is enabled by default on all properties, Radical properties, of a tracked entity, it is possible to control on which properties disable or enable the tracking system via the property metadata or decorating the property with the `MementoPropertyMetadataAttribute` and setting the `TrackChanges` value.


# Handling collection sync

We have seen how to handle change tracking in MVVM based editor loading the editor given a graph of objects coming from a persistent storage.

What we still miss is the ability to correlate changes back to the persistent graph. Radical does not offer any out-of-the-box automatic support to achieve this requirement but if we think about it the only thing not so easy to deal with are collections.

For class model instances, such as a `Person` and its `PersonViewModel` editor it is straightforward at save time simply copy back all the properties from the `ViewModel` to the model.

On the other hand for collection of objects, where the collection is tracked by the `ChangeTrackingService` we need to understand what has happened to the collection structure in order to:

* Items added to the edited collection need to be created in the underlying data store or simply added to the persistent model;
* Items removed from the edited collection should be deleted from the underlying data store or simply removed from the persistent model;
* Items changed in the edited collection needs to be simply synched back to their corresponding counterpart in the persistent model;

We can leverage the power of change tracking `IAdvisory` to understand what has happened during the editing phase:

```csharp
var advisory = service.GetAdvisory();
var items = advisory.Where( a =>
{
    return a.Target.GetType().Is<Address>() 
       && a.Action == ProposedActions.Delete;
} )
.Select( a => a.Target );
```

In the above snippet we are retrieving an advisory that is the list of proposed actions that the memento service think we should do to align the in memory model with a persistent storage. We are expecting that in the list of the tracked entities there is an `Address` class type and we are filtering Address instances looking only for items that should be deleted, that means that have been removed from a memento collection.

Since the above snippet is not really handy we set up a bunch of extension methods for the ChangeTrackingService component to support what we think are the most interesting use cases:

* Extensions are defined in the `Topics.Radical.ChangeTracking` namespace;
* `GetNewItems<T>()` retrieve the list of added items of the given type T;
* `GetChangedItems<T>()` retrieve the list of changed items of the given type T that were already exiting;
* `GetDeletedItems<T>()` retrieve the list of deleted items of the given type T;&#x20;
* `GetRemovedItems<T>()` retrieve the list of removed items of the given type T;

Using extension methods the above snippet can be rewritten as:

```csharp
var items = service.GetDeletedItems<Address>();
```

## Deleted and Removed items

What is the difference between deleted items and removed items?

* `Deleted` items are items that we initially load into the collection, we can call them persistent, that were removed during the editing phase;
* `Removed` items are items that were created during the editing phase, transient items, and then removed from the collections, most of the time this type of items can be safely ignored since their existence do not affect the persistent storage;


# DataGrid Behaviors

With this attached property you can stretch the last column of the WPF DataGrid to fill all the available space.

We can use the following syntax:

```markup
<DataGrid behaviors:DataGridBehavior.LastColumnFill="True" ... />
```

the attached property is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace.


# Password

If we try to data-bind the Password property of a PasswordBox control we end up with an error because the Password property cannot be bound due to the fact that is not a dependency property (mainly for security reasons).

In those cases you can take advantage of the PasswordBoxBehavior in the following manner:

```markup
<PasswordBox>
    <i:Interaction.Behaviors>
        <behaviors:PasswordBoxBehavior Text="{Binding Path=MyPasswordProperty}" />
    </i:Interaction.Behaviors>
</PasswordBox>
```

where the behaviors xml namespace is defined as: `http://schemas.topics.it/wpf/radical/windows/behaviors`. In the same namespace is also defined a `Password` attached property that exposes exactly the same behaviors.

The password behavior, and the attached property too, exposes also a `Command` property useful to bind a command to the “enter” key when the `PasswordBox` is focused.


# Generic routed event handler to command behavior

## Scenario

Imagine that you need to handle from the ViewModel the `SelectedIndexChanged` of a WPF `TreeView`, currently the only way (without using any particular framework) is to build your own behavior to achieve that, or bind, via a style the `IsSelected` property of the node to a property of the view model, but in this second case the side effect is that to find the selected item you need to visit the whole tree.

## Radical “Handle”

```markup
<TreeView Margin="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                     ItemsSource="{Binding Path=MyListOfElements}">
    <i:Interaction.Behaviors>
        <behaviors:Handle RoutedEvent="TreeView.SelectedItemChanged"
                          WithCommand="{Binding Path=MyAmazingCommand}"
                          PassingIn="$args.NewValue" />
    </i:Interaction.Behaviors>
    <TreeView.ItemTemplate>
        <!-- omitted -->
    </TreeView.ItemTemplate>
</TreeView>
```

As you can imagine the value of the `NewValue` property of the event arguments is passed as the command parameter to the command, we currently support as placeholder:

* `$args`: the routed event arguments;
* `$this`: the WPF element the behavior is attached to;
* `$source`: the source of the routed event;
* `$originalSource`: the original source of the routed event;

### Notes:

* the event identified by the `RoutedEvent` property must be a valid WPF `RoutedEvent`.
* the bound command identified by the `WithCommand` property must be a valid `ICommand`, `AutoCommandBinding` is not supported.

The behavior is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace.


# Overlay adorner

Radical offers a rich set of adorners and also a generic purpose adorner to put an arbitrary content on top of another element:

```markup
<Calendar Height="180" 
            HorizontalAlignment="Left" 
            VerticalAlignment="Top" 
            Width="180">
    <i:Interaction.Behaviors>
        <behaviors:OverlayBehavior Background="#99FAFAFA" IsVisible="True" IsHitTestVisible="False">
            <behaviors:OverlayBehavior.Content>
                <Border BorderBrush="Red" BorderThickness="4" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                    <TextBlock Text="I'm on top of the calendar" HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Border>
            </behaviors:OverlayBehavior.Content>
        </behaviors:OverlayBehavior>
    </i:Interaction.Behaviors>            
</Calendar>
```

producing the following effect at runtime:

![Overlay adorner sample](/files/-LA4FujhVxiX8kVK24M_)

The behavior is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace.


# Busy status manager

One of the built-in [overlay adorners](/release-1/behaviors/overlay-adorner) that Radical offers is the `BusyStatusManager` that allows us to put some blocking content on top of another xaml element and control its visibility via the IsBusy attached property:

```markup
<Grid Grid.Row="1" Grid.Column="0" 
        behaviors:BusyStatusManager.Content="Searching..."
        behaviors:BusyStatusManager.Status="{Binding Path=IsBusy, Converter={converters:BooleanBusyStatusConverter}}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <TextBox Text="{markup:EditorBinding Path=Query}" 
            Grid.Row="0"
            Margin="0"
            Height="23"
            VerticalAlignment="Top"
            HorizontalAlignment="Stretch"
            behaviors:CueBannerService.CueBanner="Search..."
            behaviors:TextBoxManager.Command="{markup:AutoCommandBinding Path=Search}">
    </TextBox>
    <ListView Grid.Row="1" ItemsSource="{Binding Path=Persons}" SelectedItem="{Binding Path=SelectedPerson}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=FirstName}" />
                    <TextBlock Margin="5,0,0,0" Text="{Binding Path=LastName}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>
```

In the previous example we are using the BusyStatusManager to put the “searching…” banner on top of a UI element whose role is to provide search capabilities, whenever from the view model we change the value of the IsBusy property to true the content of the Content property is displayed, the underlying element IsEnabled property is set to false and a semi-transparent grey background is drawn.

The important thing is that the Content property type is System.Object, this, inline with the WPF default behavior, allows us to put any content as the busy content of the BusyStatusManager.

The attached property is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace, and the converter is defined in the `http://schemas.topics.it/wpf/radical/windows/converters` xml namespace.


# TextBox behaviors:


# Command

It could be interesting to attach a command to a TextBox if the enter key is pressed while the TextBox is focused so to provide a better UX to the end user, the TextBoxManager Command attached property (or behavior) comes to the rescue in this scenario:

```markup
<TextBox Text="bla bla...">
    <i:Interaction.Behaviors>
        <behaviors:TextBoxCommandBehavior Command="{Binding Path=MyCommand}" />
    </i:Interaction.Behaviors>
</TextBox>
```

```markup
<TextBox Text="bla bla..." behaviors:TextBoxManager.Command="{Binding Path=MyCommand}" />
```

the attached property, and the behavior too, is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace.


# Auto select

One of the default annoying behavior of the WPF TextBox is that when it gets focused if there is some text it is not automatically selected, we can use the TextBoxManager AutoSelectText attached property:

```markup
<TextBox Text="bla bla..." behaviors:TextBoxManager.AutoSelectText="True" />
```

the attached property is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace.


# DisableUndoManager

The WPF `TextBox` that shipped with the .net 3.5 release had a bug, fixed in later versions, that prevents to set the `UndoLimit` property to 0, Radical provides a behavior as a workaround:

```markup
<TextBox Text="bla bla...">
    <i:Interaction.Behaviors>
        <behaviors:DisableUndoManagerBehavior />
    </i:Interaction.Behaviors>
</TextBox>
```

the behavior is defined in the `http://schemas.topics.it/wpf/radical/windows/behaviors` xml namespace.


# Editor binding

One of the most annoying thing when dealing with input forms in WPF is that in order to activate all the required feature to support the basic scenario a user expects you end with a binding defined as the following:

```markup
<TextBox Text="{Binding Path=MyText, 
                        UpdateSourceTrigger=PropertyChanged, 
                        NotifyOnValidationError=True, 
                        ValidatesOnDataErrors=True, 
                        ValidatesOnExceptions=True}" />
```

That leads to a waste of time and to a really hard-to-manage xaml markup. In order to eliminate both problems in Radical we introduced our own binding markup extension that has as default values all the values exposed in the previous sample. Using our EditorBinding markup extension the same behavior can be achieved in the following manner:

```markup
<TextBox Text="{markup:EditorBinding Path=MyText}" />
```

simpler and cleaner. The markup extension is defined in the `http://schemas.topics.it/wpf/radical/windows/markup` xml namespace.


# Auto Command binding

WPF `ICommand` interface is the canonical way to expose commands from a ViewModel that is bound to a View. They come with a few caveats:

* Most of the times commands are simple and the plumbing required to create an `ICommand` implementation is not worth it.
* ViewModels exposing commands that implement the `ICommand` interface reference WPF types with the risk of complicating the required testing infrastructure.

Radical solves the above issues by introducing a handy markup extension that allow to write a ViewModel like the following:

```csharp
class MyViewModel : AbstractViewModel
{
   public void DoSomething()
   {
      //perform work
   }
}
```

The `DoSomething` method can be bound to a `Button` on the View in the following manner:

```markup
<Button Command="{markup:AutoCommandBinding Path=DoSomething}" />
```

The `AutoCommandBinding` markup extension will dynamically build a [DelegateCommand](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/mvvm/delegate-command.md) that wraps at runtime the method invocation.

The `ICommand` interface exposes a `CanExecute(object)` method that the WPF inteface can call to detect if the command is available in the current context and thus decide if the WPF element bound to a command should be enabled or not. Using the same approach as above a ViewModel can expose a `bool` property as following:

```csharp
class MyViewModel : AbstractViewModel
{
   public void DoSomething()
   {
      //perform work
   }

   public bool CanDoSomething
   {
      get{ return true; /* or false */ }
   }
}
```

The convention is to expose a public boolean property whose name is the same as the method, that will be wraped in a command, prefixed with `Can`. No changes to the XAML markup are required.

Given the way commands work in WPF one thing that might be required is to change the command status, and thus the bound control, from the ViewModel implementation. The easiest thing is to ask WPF to reevluate the `Can*` boolean property whenever we decide the command status changes. We can leverage the power of [Radical properties](https://github.com/RadicalFx/documentation/tree/3311fbb6d65f98ece74ce84f7fde9dec2a25a7ee/entities/property-system.md) metadata, and specifically the cascade changes notification feature as following:

```csharp
class MyViewModel : AbstractViewModel
{
   public MyViewModel()
   {
        this.GetPropertyMetadata( () => this.SelectedEntity )
            .AddCascadeChangeNotifications( () => this.CanEdit );
   }

   public MyEntity SelectedEntity
   {
      get { return this.GetPropertyValue( () => this.SelectedEntity ); }
      set { this.SetPropertyValue( () => this.SelectedEntity, value ); }
   }

   public void Edit()
   {
      //perform work
   }

   public bool CanEdit
   {
      get{ return this.SelectedEntity != null; }
   }
}
```

In the above scenario whenever the `SelectedEntity` property changes a `INotifyPropertyChanged.PropertyChanged` event is raised also for the `CanEdit` property, thus WPF reevaluates the property and based on the boolean result the bound command will be enabled or not.

The markup extension is defined in the `http://schemas.topics.it/wpf/radical/windows/markup` xml namespace.


# Get the view of a given view model

There are cases where given a running ViewModel we need to retrieve an instance of the currently associated View, the runtime conventions object exposes a convention to achieve that:

```csharp
class MyViewModel : AbstractViewModel
{
    public MyViewModel(  IConventionsHandler conventions )
    {
        var view = conventions.GetViewOfViewModel( this );
    }
}
```

Since the conventions are handled by the underlying Inversion of Control subsystem we can access the conventions using a dependency, as in the above sample.

## Notes:

if we take a look at the signature (Func) of the above convention we notice that the “in” parameter is an Object and is not constrained to be an AbstractViewModel, this is in line with the fact that for the Radical toolkit a ViewModel is not required to be an AbstractViewModel, but if you need to use the above convention or the UI Composition system be aware that if the ViewModel is not an AbstractViewModel you end up with 2 options:

* implement on your view model the IViewModel interface;
* or replace the AttachViewToViewModel convention that is responsible to reverse link the View to the ViewModel;


# Bi-directional communication between different windows/views

In a MVVM based application if you decide to delegate all the communication to the infrastructure using a broker, so to respect the single responsibility principle, you end up dealing with problems that in a much more coupled environment would never arise.

Imagine the following scenario: As a user when I create e new order I need to choose the customer that owns the order so to successfully associate the order with the given customer.

In “programming” language the above translates to: when the user creates a new order and want to choose a customer we need to **open** a search dialog to let the user search for the customer and then **return** the chosen customer to the calling view.

I have highlighted the keywords in **bold**, we have 2 different contexts that needs to communicate but we do not want to have a direct relation between the 2 contexts, in other words: we do not want to open the dialog from the “create new order view model” but we want to delegate all the communication to the broker.

There are several options to achieve the same behavior but we think that the most important thing to avoid is to try to achieve the same “blocking” behavior that a dialog gives us because this prevents to move to a different UX without changing the implementation.

## 2-way messaging

The first viable approach is to use 2 messages where the first one is to request the start of the selection process and the second one is delivered by the selection process to send back the selection result(s):

```csharp
class SelectCustomer
{
    public object RequestToken{ get; set; }
}
```

```csharp
class CustomerSelected
{
    public object RequestToken{ get; set; }
    public IEnumerable<Customer> Selection{ get; set; }
}
```

We need to introduce the concept of token so that the receiver when receives the response can determine if the response if for its own request or should be discarded because is someone else request:

```csharp
class OrderViewModel
{
    IMessageBroker broker
    object requestToken = null;

    public OrderViewModel( IMessageBroker broker )
    {
        this.broker = broker;
        this.broker.Subscribe<CustomerSelected>( this, ( s, m ) => 
        {
            if( m.RequestToken == this.requestToken )
            {
                //do something with the selection
            }
        } );
    }

    void Select()
    {
        this.requestToken = new object();
        this.broker.Broadcast( this, new SelectCustomer() );
    }
}
```

The benefit of this approach is that someone else can be interested in the selection and we do not have to do anything to plug “that” someone else into the process.

## Message callback

an easier approach is to use one single message:

```csharp
class SelectCustomer
{
    public object RequestToken{ get; set; }
    public Action<IEnumerable<Customer>> Callback{ get; set }
}
```

so that we do not have to deal with tokens to identify responses:

```
class OrderViewModel
{
    IMessageBroker broker

    public OrderViewModel( IMessageBroker broker )
    {
        this.broker = broker;
    }

    void Select()
    {
        var msg = new SelectCustomer()
        {
            Callback = results => 
            {
                //do something interesting with the results
            }
        };
        this.broker.Broadcast( this,  );
    }
}
```

in this case when the selection process is finished the view model that handles the search/selection simply invokes the callback with the selection results.

## Dedicated services

The last approach is to wrap the above logic into a custom component, such as an ISelectionService, that can be something like:

```csharp
interface ISelectionService<T>
{
    Task<IEnumerable<T>> Search();
    Task<IEnumerable<T>> Search( String query );
}
```

where the fact that we return a Task can be handy because can be used in conjunction with the async/await keywords and perfectly fit the async nature of the message broker broadcasting engine.


# Handle the busy status during async/long running operations

Radical provides an [overlay adorner](/release-1/behaviors/overlay-adorner) to handle busy/long running operations, that for simple scenarios just works as expected. Sometimes there are cases when we need to handle a much more complex scenario such as the following:

As a user I want to be able to start a long running operation, and if, after a certain amount of time, the operation is not completed I want to be able to cancel the operation itself.

Let us start drawing the UI for the above requirements:

```markup
<AdornerDecorator>
    <Grid behaviors:BusyStatusManager.Status="{Binding Path=IsBusy, Converter={converters:BooleanBusyStatusConverter}}">
        <behaviors:BusyStatusManager.Content>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Ellipse x:Name="ellipse" StrokeThickness="6" Width="30" Height="30" RenderTransformOrigin="0.5,0.5">
                    <Ellipse.Resources>
                        <Storyboard x:Key="SpinAnimation" RepeatBehavior="Forever">
                            <DoubleAnimation To="359"
                                        Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" />
                        </Storyboard>
                    </Ellipse.Resources>
                    <Ellipse.Triggers>
                        <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                            <BeginStoryboard Storyboard="{StaticResource SpinAnimation}"/>
                        </EventTrigger>
                    </Ellipse.Triggers>
                    <Ellipse.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </Ellipse.RenderTransform>
                    <Ellipse.Stroke>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                            <GradientStop Color="Red" Offset="0"/>
                            <GradientStop Color="#FF1442BF" Offset="1"/>
                        </LinearGradientBrush>
                    </Ellipse.Stroke>
                </Ellipse>
                <Button IsEnabled="{Binding Path=ThresholdElapsed}" HorizontalAlignment="Center" VerticalAlignment="Top" Grid.Row="1" Content="Waited tooooo long, cancel..." Command="{markup:AutoCommandBinding Path=CancelWork}" />
            </Grid>
        </behaviors:BusyStatusManager.Content>
        <Button Content="Click me!" Command="{markup:AutoCommandBinding Path=WorkAsync}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="70" Height="23"/>
    </Grid>
</AdornerDecorator>
```

Seems complex but it is not, we are using an ellipse element to create an animated spinning icon, pretty standard WPF stuff, the ellipse element, and a button is enclosed in a grid that is enclosed in the content of the BusyStatusManager, the button enabled status is bound to a property in the ViewModel. And then we have a simple button that triggers the long running operation in the ViewModel.

Q: Why the outer grid is wrapped in an AdornerDecorator element?

This a pretty complex WPF adorner requirement, the above code is contained in the Radical samples that are structured in the following manner:

* The top most element is a Window;
* Inside the Window there is a grid:
  * the left column contains the sample navigation menu;
  * the right column is a region (a Radical UI Composition region) that hosts the selected sample;
* Attached to the Window there is a MainViewModel;
* The MainViewModel exposes a property, SelectedSample, that is the currently selected sample view model that will be bound to the region content;

So by default the WPF visual tree will be something similar to:

* Window <–> MainViewModel
  * AdornerDecorator (automatically added by WPF)
    * Grid
      * region container
        * Sample UserControl <–> SampleViewModel

At runtime the Radical adorner decorator engine looks for an AdornerDecorator to attach the adorner to, and finds the one child of the Window, now if you look at the ViewModel positions you can immediately notice that the data binding engine will look for properties on the wrong ViewModel, in this case, so we need to constraint the position of the adding another AdornerDecorator:

* Window <–> MainViewModel
  * AdornerDecorator (automatically added by WPF)
    * Grid
      * region container
        * **AdornerDecorator**
          * Sample UserControl <–> SampleViewModel

From the view model point of view things are not so complicated as they appear in at the first look:

```csharp
class BusyBehaviorSampleViewModel : SampleViewModel
{
    readonly IDispatcher dispatcher;

    public BusyBehaviorSampleViewModel( IDispatcher dispatcher )
    {
        this.dispatcher = dispatcher;
    }

    public Boolean ThresholdElapsed
    {
        get { return this.GetPropertyValue( () => this.ThresholdElapsed ); }
        private set { this.SetPropertyValue( () => this.ThresholdElapsed, value ); }
    }

    public Boolean IsBusy
    {
        get { return this.GetPropertyValue( () => this.IsBusy ); }
        private set { this.SetPropertyValue( () => this.IsBusy, value ); }
    }

    public String Status
    {
        get { return this.GetPropertyValue( () => this.Status ); }
        private set { this.SetPropertyValue( () => this.Status, value ); }
    }

    Worker w = null;

    public void CancelWork()
    {
        if ( this.w != null )
        {
            lock ( this )
            {
                if ( this.w != null )
                {
                    this.w.CancelWork();
                }
            }
        }
    }

    public async void WorkAsync()
    {
        this.IsBusy = true;
        this.Status = "running...";

        this.w = new Worker()
        {
            OnThresholdElapsed = () => this.dispatcher.Dispatch( () => this.ThresholdElapsed = true )
        };

        var r = await this.w.Execute( token =>
        {
            var count = 0;
            while ( count < 15 && !token.IsCancellationRequested )
            {
                ++count;
                Thread.Sleep( 1000 );
            }
        } );

        lock ( this )
        {
            this.w = null;
        }

        this.Status = r.Cancelled
            ? "cancelled."
            : "completed.";

        this.IsBusy = false;
    }
}
```

We have a bunch of properties to control the status of the UI and 2 methods to control the async work, the Worker class is just a wrapper around the Task API to simplify the threshold elapsed management that is done using a Timer.

What happens, when the user pushes the “button”, is that:

* A long running job is started (15”);
* The “please wait…” UI adorner is displayed;
* After 5” the “Cancel” button is activated because the threshold to wait for the task to complete is exhausted;
* The long running job continues;
* if the user presses the “cancel” button a cancel request is injected into the worker;
* otherwise the long running task is allowed to complete;

The worker class:

```csharp
class Worker
{
    public class Result
    {
        public Boolean Cancelled { get; set; }
    }

    CancellationTokenSource cs = null;

    public Worker()
    {
        this.OnThresholdElapsed = () => { };
    }

    public Action OnThresholdElapsed { get; set; }

    public async Task<Result> Execute( Action<CancellationToken> action )
    {
        this.cs = new CancellationTokenSource();
        var token = this.cs.Token;

        var r = await Task.Factory.StartNew( () =>
        {
            var threshold = new System.Timers.Timer( 5000 );
            threshold.AutoReset = false;
            threshold.Elapsed += ( s, e ) => this.OnThresholdElapsed();
            threshold.Start();

            action( token );

            threshold.Stop();

            return new Result() { Cancelled = token.IsCancellationRequested };
        }, cs.Token );

        lock ( this )
        {
            this.cs = null;
        }

        return r;
    }

    public void CancelWork()
    {
        if ( this.cs != null )
        {
            lock ( this )
            {
                if ( this.cs != null )
                {
                    cs.Cancel();
                }
            }
        }
    }
}
```

The above worker is for sample purpose and is not intended to be used in production.


# Implement a customer improvement program

From the perspective of an application producer it is really important to know what our end users do with the application they use:

* we plan a feature;
* we invest money in building a feature;
* we deploy a feature;

we know nothing about how the user utilizes the feature we invested on, we do not even know if the user utilizes it at all.

```csharp
AnalyticsServices.UserActionTrackingHandler = evt =>
{
    //every user action will be dispatched here asynchronously    
};

AnalyticsServices.IsEnabled = true;
```

Writing the above code at the application startup enables the Radical AnalyticsServices, what happens is that all the code that in some way invokes a DelegateCommand, in a WPF MVVM based application, will be tracked and we have the opportunity to “save” what the user is doing in order to analyze it later.

What the UserActionTrackingHandler receives is an AnalyticsEvent with the following shape:

```csharp
public class AnalyticsEvent
{
    public AnalyticsEvent()
    {
        this.ExecutedOn = DateTimeOffset.Now;
        this.Identity = Thread.CurrentPrincipal.Identity;
    }

    public DateTimeOffset ExecutedOn { get; set; }

    public String Name { get; set; }

    public Object Data { get; set; }

    public IIdentity Identity { get; set; }
}
```

If we need we can define our own events inheriting from the AnalyticsEvent class and in order to plugin our events we only need to declare a dependency on the IAnalyticsServices service:

```csharp
public interface IAnalyticsServices
{
    Boolean IsEnabled { get; set; }
    void TrackUserActionAsync( Analytics.AnalyticsEvent action );
}
```

And each time we call `TrackUserActionAsync` the `UserActionTrackingHandler` will be invoked.


# Manage focus

## Manage focus

Available in [Radical.Windows.Presentation](http://nuget.org/packages/Radical.Windows.Presentation) from version 1.0.3.0\*

In the Model View ViewModel world there are a lot of things that can be considered borderline, focus management is one of those things. On the other side managing focus in a desktop application based on WPF is other then a trivial task, focus in desktop application has many facets and lots of corner cases that must be taken into account, there is logical focus, keyboard focus and input scopes that determine the focus behavior.

In [Radical](https://github.com/RadicalFx/radical) we support a basic focus management where we completely ignore input scopes and we consider logical focus and keyboard focus to be always related to the same control at the same time.

## The View

In order to manage focus on the view side we need to introduce on each control we want to participate the following behavior:

```markup
<TextBox Margin="10" Text="{markup:EditorBinding Path=SampleText}">
    <i:Interaction.Behaviors>
        <lb:Focus ControlledBy="{Binding Path=FocusedElementKey}" UsingKey="SampleText" />
    </i:Interaction.Behaviors>
</TextBox>
```

where the “lb” xml namespace is defined as follows:

```
xmlns:lb="clr-namespace:Topics.Radical.Windows.Presentation.Behaviors;assembly=Radical.Windows.Presentation"
```

*the definition is currently in preview, when we definitely release the feature the xml namespace will follow the typical Radical conventions.*

The Focus behavior defines which property of the ViewModel controls the focused element (ControlledBy) and which is the key (UsingKey) that uniquely identifies the control among all the others, in this case we are using, as key, exactly the same name name as the property the control is bound to: “SampleText”.

## The ViewModel

On the ViewModel side, if we inherit from the base [AbstractViewModel](/release-1/presentation/abstract-view-model), we just need to decide which should be the “focused” key:

```csharp
class MainViewModel : AbstractViewModel
{
    public void SetFocus() 
    {
        this.MoveFocusTo( () => this.SampleText );
    }

    public String SampleText
    {
        get { return this.GetPropertyValue( () => this.SampleText ); }
        set { this.SetPropertyValue( () => this.SampleText, value ); }
    }
}
```

At runtime each time we call MoveFocusTo, exposed by the base view model we inherit from, the focus is moved to the UI element identified by the given key.


# Create a splash screen

`Radical` utilizes its own internal [UI Composition](/release-1/ui-composition/index) engine to add support to splash screens at application startup:

```csharp
var bootstrapper = new WindsorApplicationBootstrapper<Presentation.MainView>()
    .EnableSplashScreen()
```

Enabling splash screen support is as easy as calling the `EnableSplashScreen` method on the application bootstrapper instance.

## Splash screen content

Since the splash screen content is managed using the `UI Composition` engine in order to add a content to the splash screen is enough to define a [partial view](/release-1/ui-composition/index#automatic-aka-partial-regions) named `SplashScreenContent`:

```
Presentation
  .Partial
     .SplashScreenContent
```

The `View`, along with its `ViewModel` if any, defined in the `Presentation.Partial.SplashScreenContent` namespace will be used to populate the splash screen.

## Splash screen configuration

It is possible to use the `SplashScreenConfiguration` class to define some splash screen settings:

* `SizeToContent`: Determines the way the splash screen hosting window is dimensioned, the default value is `WidthAndHeight`;
* `WindowStartupLocation`: The splash screen startup location, the default value is `CenterScreen`;
* `WindowStyle`: The splash screen window style, the default value is `None`.
* `StartupAsyncWork`: Defines the work that should be executed asynchronously while the splash screen is running;
* `Height`: Defines the Height of the splash screen window if the `SizeToContent` value is `Manual` or `Width`; otherwise is ignored;
* `Width`: Defines the Width of the splash screen window if the `SizeToContent` value is `Manual` or `Height`; otherwise is ignored;
* `MinWidth`: The Minimum Width of the splash screen window. The default value is `585`;
* `MinHeight`: The Minimum Height of the splash screen window. The default value is `335`;
* `MinimumDelay`: Represents the minimum time, in milliseconds, the splash screen will be shown;&#x20;
* `SplashScreenViewType`: Defines the default view that `Radical` uses to host the splash screen content;

Available in `Radical.Windows.Presentation` starting from version `1.10.3`, `Democracy` milestone.


# Access view model after view is closed

Good or not one of the scenario users need to support is to be able to use a `ViewModel` after the hosting `View` is closed. A typical sample is the following:

```csharp
var view = viewResolver.GetView<MySampleView>();
view.ShowDialog();
var viewModel = conventions.GetViewDataContext( view, ViewDataContextSearchBehavior.LocalOnly );
//access here some properties of the viewModel instance
```

The above snippet will fail with a Null Reference Exception due to the fact that the `viewModel` instance will be null. The underlying reason is that as soon as the hosting view is closed:

* the `ViewModel` is detached from its `View`;
* Both components are released through the `IReleaseComponents` service, causing disposition of disposable instances;

Given the above it is by design that `GetViewDataContext` will return a null reference in the above scenario. A first approach, as a workaround, can be the following:

```csharp
var view = viewResolver.GetView<MySampleView>();
var viewModel = conventions.GetViewDataContext( view, ViewDataContextSearchBehavior.LocalOnly );
view.ShowDialog();
//access here some properties of the viewModel instance
```

We simply retrieve a reference to the `ViewModel` before the view is closed and we use it later. What can happen is that accessing one of the ViewModel properties an `ObjectDisposedException` is raised because the `AbstractViewModel` base class knows that the `ViewModel` instance was released and disposed.

The definitive solution is to override the automatic release behavior decorating the `View` class with the `ViewManualReleaseAttribute` and changing our code as follows:

```csharp
var view = viewResolver.GetView<MySampleView>();
view.ShowDialog();
var viewModel = conventions.GetViewDataContext( view, ViewDataContextSearchBehavior.LocalOnly );
//access here some properties of the viewModel instance
conventions.ViewReleaseHandler( view, ViewReleaseBehavior.Force );
```

Once `MySampleView` is decorated with the `ViewManualReleaseAttribute` it won't be released anymore automatically and the `ViewModel` won't be detached, once we have finished using the `ViewModel` instance we ask to the conventions to force the release of the `View` and of its `ViewModel` using the `ViewReleaseHandler` convention and the `Force` enumeration value to override the default behavior.


# Intercept ViewModels before it's used

## Intercept ViewModels before it's used

One of the typical scenario in a desktop application is the requirement to “open” a new view passing to newly created view/view model some data, the ideal solution is also to be able to pass data to the constructor of the new view model in order to be sure that at the end of the construction process everything is correctly setup.

When dealing with Inversion of Control framework this is generally a pain point because each framework out there provide a way to achieve the goal we outlined but generally the solution, in my opinion, is really weak and full of pain point.

In order to solve the above problem the general approach is something like the following:

```csharp
var viewModel = myFavoriteIoC.Resolve();
viewModel.Initialize( someData );
```

In a view first scenario, like the one proposed by default by Radical this is not so easy because you end up with the following code:

```csharp
var view = viewResolver.GetView<MyView>();
var viewModel = conventions.GetViewDataContext( view ) as MyViewModel;
viewModel.Initialize( someData );
```

it works, using the built-in [conventions](/release-1/presentation/conventions/runtime-conventions) we retrieve an instance of the attached view model and set it up, but the problem is that the setup occurs after that the view model has been wired to the view, and in some cases this is not ideal.

## Interceptors

We have so decided to add a new feature to the [view resolver](/release-1/presentation/iview-resolver) to let the user intercept the view model before it is wired up to the view:

```csharp
var view = viewResolver.GetView<MyView>( vm => 
{
  //do what you want with the view model
} );
```

the Action that intercept the view model is called before the view model is attached to the view, in the above sample, since we cannot infer the view model type, the view model is passed to the action as Object, if you know upfront the type of the view model you can explicit tell us what it is:

```csharp
var view = viewResolver.GetView<MyView, MyViewModel>( vm => 
{
  //do what you want with the view model
} );
```

And the delegate will be of type `Action`.


# Home

## MVVM and UI Composition quick start

### Windows Presentation Foundation

#### Steps to bootstrap your project in 3 minutes

* Create a new Visual Studio solution and add a new WPF (.NET Core 3) application project;
* Add, using nuget, a reference to: [Radical.Windows](https://www.nuget.org/packages/Radical.Windows);
* Delete the default MainWindow\.xaml;
* Edit the app.xaml file to remove the `StartupUri` attribute;
* Add a `Presentation` folder to the project;
  * `Presentation` is the default location, based on conventions, where Radical looks for Views and ViewModels;
* Create 2 new items in the `Presentation` folder:
  * A WPF window named Main**View**.xaml (\*View is important for the default conventions);
  * A class Main**ViewModel** (<*ViewName*>ViewModel is important for the default conventions);
* In the app.xaml.cs add a single line of code:

```csharp
public partial class App : Application
{
   public App()
   {
      this.AddRadicalApplication<Presentation.MainView>();
   }
}
```

**Press F5 and you are up & running**: the `MainView` window will be shown. The following things happen:

* The application boots
* All the default and required services (for MVVM and UI Composition) are wired into the IoC container (using `IServiceCollection`)
* The `MainView` is designed as the main window
* At boot time the `MainView` is resolved and using the conventions engine the `MainViewModel` is setup and set as the `DataContext` of the `MainView`
* Finally the `MainView` is shown.

#### What’s next

The best topic to read now is basic [concepts about the ViewModel](/release-2/presentation/abstract-view-model).

## Release management process

Radical follows a set of rules to prepare and publish releases:

* Define the milestone;
* Define an issue for everything that gets touched;
* Associate the issue to the milestone;
* Use [Release Flow](http://releaseflow.org/) to commit changes;
* Associate a commit with an issue and close it;
* Publish the release associated to the milestone;

## Contribution guideline

Your contributions to Radical are very welcome.\
If you find a bug, please raise it as an issue.\
Even better fix it and send a pull request.\
If you like to help out with existing bugs and feature requests just check out the list of [issues](https://github.com/RadicalFx/radical/issues) and grab and fix one:

* If you find a bug, please raise it as an issue, even better followed by a pull request.
* If you like to help out with existing bug and feature, just check out the list of [issues](https://github.com/RadicalFx/radical/issues) and grab and fix one.
* This project uses [Release Flow](http://releaseflow.org/) for pull requests. So if you want to contribute, fork the repo, create a descriptively named branch off of master (ie: portable-class-library-support), fix an issue, run all the unit tests, and send a PR if all is green.
* Please rebase your code on top of the latest commits. Before working on your fork make sure you pull the latest so you work on top of the latests commits to avoid merge conflicts. Also before sending the PR please rebase your code as there is a chance there have been new commits pushed after you pulled last.
* We will only merge PR that could be automatically merged.

## A note on versioning

Radical follows the following versioning scheme:

major.minor.patch-extensions.version

We use the following [semantic versioning policy](http://semver.org/):

```
major           - version when you make incompatible API changes.
minor           - when you add functionality in a backwards-compatible manner.
patch           - when you make backwards-compatible bug fixes.
extensions      - pre-release extensions
version         - pre-release version
```

Check the [Release pages](https://github.com/RadicalFx/radical/releases) for the version history of all the Radical's packages. And the [Radical.Windows release pages](https://github.com/RadicalFx/radical.windows/releases) for Radical.Windows releases.

## Samples

The Radical source code includes several samples that are divided per scope and technology, samples are available in the documentation repository: <https://github.com/RadicalFx/documentation/tree/master/samples>

All samples are constantly under heavy development and are also used to test Radical features.

## MyGet unstable feed

Radical uses MyGet to publish unstable releases during development, to use the unstable feed:

* create a `nuget.config` file in the same folder as your solution folder
* add the following content to the configuration file:

```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="Radical Unstable" value="https://www.myget.org/F/radical-unstable/api/v3/index.json" />
  </packageSources>
</configuration>
```

* close and reopen the solution

By going to the Manage Nuget Packages page of your solution, you'll now see a "Radical Unstable" option in the source selection dropdown. Do not forget to check the "prerelease versions" checkbox search setting.

## Continuous Integration

Radical uses [AppVeyor](https://ci.appveyor.com/account/radical-bot/projects) to host the build infrastructure. All active repositories are mapped to an AppVeyor project. Branches are configured so that Pull Requests require builds to be green to be merged. Each time a new PR is raised and/or each time a new commit is pushed to an existing PR a build is triggered and the build status is reported to GitHub. From AppVeyor build artfacts, such as Nuget packages, can be pushed to Myget or to Nuget, depending on their stability level. Builds are triggered also when a TAG is pushed. Usually a TAG identifies a stable build that will be released to Nuget.


# AbstractViewModel

When dealing with MVVM and ViewModel(s) there are a lot of things that a base class, such as the `AbstractViewModel`, can do for us in order to reduce the friction of the daily work.

The `AbstractViewModel` can (it is not required, even if is highly suggested) be used as a base class for all the application ViewModel(s), defining a view model is as easy as:

```csharp
class MainViewModel : AbstractViewModel
{

}
```

Nothing special, a simple and trivial class that inherits from the base `AbstractViewModel` type.

For the Radical toolkit a `ViewModel` is not required to be an `AbstractViewModel`, but if you do not to use the `AbstractViewModel` class as a base class for all the ViewModels you end up with 2 options:

* implement on your view model the `IViewModel` interface;
* or replace the `AttachViewToViewModel` [convention](/release-2/presentation/conventions/runtime-conventions) that is responsible to reverse link the View to the ViewModel;

As soon as we do that we gain some benefits:

**Property change notification**:

the obvious benefit is that we immediately get `INotifyPropertyChanged` support:

```csharp
private String _text;

public String Text
{
    get { return _text; }
    set 
    {
        _text = value;
        this.OnPropertyChanged( () => this.Text );
    }
}
```

But given that writing properties in such a verbose way is a waste of time we can leverage the power of the Property System.

**Radical Property System**:

The above property can be written in the following manner without altering the behavior:

```csharp
public String Text
{
    get { return this.GetPropertyValue( () => this.Text ); }
    set { this.SetPropertyValue( () => this.Text, value ); }
}
```

But the property system is not limited to changes notification, we can for example do the following:

```csharp
class MainViewModel : AbstractViewModel
{
    public MainViewModel()
    {
        this.GetPropertyMetadata( () => this.Text )
            .AddCascadeChangeNotifications( () => this.Sample );
    }

    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }

    public Int32 Sample
    {
        get { return this.GetPropertyValue( () => this.Sample ); }
        set { this.SetPropertyValue( () => this.Sample, value ); }
    }
}
```

we have defined 2 properties and we are chaining the properties change notification in order to notify a change to the `Sample` property each time the `Text` property changes.


# Conventions

Our first aim is to remove friction, it is not always easy and cannot be done every single time, but one thing that can give a lot of benefits in this area is to move from a configuration based toolkit to a convention based toolkit, we suppose that this concept is widely accepted and is nothing new.

What happens when these lines of code are executed:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>();
    }
}
```

A lot of things:

1. The application `Startup` event is wired;
2. When the `Startup` event is fired:
   1. Assemblies are scanned looking for all types
   2. `ServiceCollection` is configured using the [bootstrap conventions](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/mvvm/bootstrap-conventions.md);
   3. The Inversion of Control container is created;&#x20;
   4. The main window (the one identified by the TShellView generic parameter) is resolved and shown;


# Bootstrap Conventions

As we have already said the whole bootstrap process is completely based on conventions, especially the IoC container setup. Bootstrap conventions are mainly related to the way components are registered into the container:

* every class that is defined in a namespace ending with `Services (*.Services)` will be considered a service and will be registered as `singleton` using as the service contract the first interface, if any, otherwise using the class type;
* every class that is defined in a namespace ending with `Presentation (*.Presentation)` and whose type name ends with `ViewModel (*ViewModel)` will be considered as a view model and registered as transient;
  * following the same logic every type in the same namespace whose name ends with `View (*View)` will be considered a view, a transient view;
  * if a view or a view model are a shell, type name beginning with `Shell*` or `Main*`, they will be registered as singleton
  * be default views and view models will be registered using as service contract the class type and no interface is searched along the way;
* every type defined in a namespace ending with `Messaging.Handlers (*.Messaging.Handlers)` will be considered a message broker message handler and will be registered as singleton and automatically attached, as an handler, to the broker pipeline;

These are the main conventions used at boot time, there are a few more but less important. Obviously all these behaviors can be replaced or extended to accomplish the end user needs:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration => 
        {
           configuration.BootstrapConventions.IsViewModel = type => 
           {
              if (type.Namespace == "MyViewModelsNamespace") 
              {
                 return true;
              }

              return configuration.BootstrapConventions.DefaultIsViewModel(type);
            };
         });
    }
}
```

In the above sample we are integrating the conventions used to determine if a type is a view model.


# Runtime Conventions

`Radical.Windows.Presentation` has a lot of runtime conventions mainly related to two different areas:

* View – ViewModel relation;
* UI Composition;

Runtime conventions are managed by the `IConventionsHandler` interface, and allows to take full control of the following Radical behaviors:

* **ResolveViewModelType**: The first convention is used internally by the ViewResolver and given the view type returns the ViewModel type for the given view, the default behavior is that the view model is in the same namespace of the view and has the same type name suffixed with “Model” (e.g.: MainView and MainViewModel).
* **ResolveViewType**: The ResolveViewType convention is currently under development and not used, but basically does the opposite stuff, using the same default behavior, as the ResolveViewModelType convention. The toolkit utilizes a view first approach, thus resolving the view type given the view model type is not required, you can use this convention to implement a view model first based approach.
* **ViewReleaseHandler**: the `ViewReleaseHandler` is called each time a `View` should be released, this handler is responsible to release the `View` and its associated `ViewModel` if any. This handler also unsubscribe, if allowed by the `ShouldUnsubscribeViewModelOnRelease` convention, the `ViewModel` from all the subscriptions registered with the `MessageBroker`.
* **ShouldReleaseView**: determines if a `View` should be released when required.
* **ShouldUnsubscribeViewModelOnRelease**: determines if `ViewModel` subscriptions should be unsubscribed at release time.
* **ShouldUnregisterRegionManagerOfView**: internally used by the UI Composition engine to determine if a region manager should be destroyed when the owner `View` is released, the default behavior is to destroy region managers only if the `View` is not a singleton view.
* **FindHostingWindowOf**: This convention is currently used to find the Window that hosts a given view model. It is pretty useful to get a reference to the Window object that hosts, in its visual tree a View Model data bound to a UserControl.

  This task is performed finding the current view of the given view model (using another convention) and then reverse walking the visual tree looking for the first Window object.\
  The convention accomplish two needs:

  1. A view model can implement the IExpectViewClosingCallback and the IExpectViewClosedCallback (and other \*Callback(s)) in order to intercept the fact that the hosting Window is closing or has been closed and since we support UI Composition features a view model can be a view model attached to a UserControl that is runtime “inserted” into the visual tree of an existing Window;
  2. The UI Composition region service, in order to satisfy the above requirement, each time setups a new region need to find the hosting window in order to attach the closing and closed events;
* ViewModels as resources: there are scenarios in which it's handy to have the current `View` `ViewModel` available in the `View` resources. **ShouldExposeViewModelAsStaticResource** and **ExposeViewModelAsStaticResource** control if a `ViewModel` is exposed as a resource (`false` by default) and how it is exposed. The default behavior, when this feature is active, is to register the `ViewModel` in the resources using its `Type` name as the resource key.
* **GenerateViewModelStaticResourceKey**: The GenerateViewModelStaticResourceKey conventions is used to determine the resource key used to store ViewModel instances in View resources when exposing ViewModels as resources in Views.
* **ViewHasDataContext**, **SetViewDataContext** and **GetViewDataContext**: The ViewHasDataContext convention simply checks if the given view DataContext property is not null, this convention accepts a DependencyObject because in WPF the DataContext property is not defined on a single root object but is defined on FrameworkElement and on FrameworkContentElement.\
  SetViewDataContext and GetViewDataContext respectively sets and gets the DataContext of the given view.

  *Note*:

  > The `ViewDataContextSearchBehavior` has been introduced to overcome an issue encountered due to the way dependency property value inheritance works. When using nested views, for example because one child view is loaded as a content injected into a region, if the nested view does not have a DataContext property (e.g. is a view without a ViewModel) its DataContext property value is inherited from the first element in the logical tree that has a DataContext assigned. This default WPF behavior was causing some subtle bugs in the way the Radical MVVM logic was working. The ViewDataContextSearchBehavior has been introduced to determine the way the MVVM engine will look for the ViewModel on a View, the default behavior, that can be controlled via the `DefaultViewDataContextSearchBehavior` property, is to look only on the View DataContext property ignoring each inherited value.
* **ShouldNotifyViewLoaded** This convention is responsible to determine if a `View` should notify that is loaded broadcasting a `ViewLoaded` message. A view notifies that has been loaded in 2 cases:
  * If the View contains a `Region`;
  * If the View, or the associated ViewModel, is decorated with the `NotifyLoadedAttribute`;

    The same logic applies to the **ShouldNotifyViewModelLoaded** convention for the ViewModel.
* **AttachViewToViewModel** and **GetViewOfViewModel**: Internally the `Radical.Windows.Presentation` MVVM and UI Composition toolkit needs to know the runtime View – ViewModel relations in order to know that given a ViewModel instance the corresponding View instance is certainly a specific instance.

  To achieve that the `ViewResolver` once has resolved both the required instances calls the `AttachViewToViewModel` convention in order to store the view reference in the view model instance (the view model is already stored in view instance using the `DataContext` property).

  By design this works out-of-the-box because the `AbstractViewModel` type implements the `IViewModel` interface that has a `View` property internally used for this tasks. If the user does not like this behavior or cannot inherit from the `AbstractViewModel` type, nor implement the `IViewModel` interface, can replace this convention in order to store somewhere else the required relation (e.g. a statically defined dictionary).

  The same logic is used by the `GetViewOfViewModel` convention that is required to retrieve the stored relation.
* **TryHookClosedEventOfHostOf**: This is internal and is used by the region service engine to attach the closed event of the hosting window, if any, in order to cleanup stuff when the window is closed.
* **IsHostingView**: The `IsHostingView` convention is internally used by the `Region` base class to determine if a given visual element can be considered a View.
* **AttachViewBehaviors**: The AttachViewBehaviors convention can be hooked by the framework user if there is a requirement to attach behaviors (`System.Windows.Interactivity.Behavior<T>`) whenever a view is resolved by the ViewResolver. By default the built-in `ViewResolver` attaches the following behaviors to each view:
  * WindowLifecycleNotificationsBehavior;
  * FrameworkElementLifecycleNotificationsBehavior;
  * DependencyObjectCloseHandlerBehavior;
* **GenerateServiceStaticResourceKey**: The GenerateServiceStaticResourceKey conventions is used to determine the key used whne registering services as resources, both at the application level or at the View level.


# Conventions override

Radical is conventions based, [runtime conventions](/release-2/presentation/conventions/runtime-conventions) and [bootstrap conventions](/release-2/presentation/conventions/bootstrap-conventions). To facilitate conventions override, to replace or integrate a default behavior the concept of default conventions is supported.

Both [runtime conventions](/release-2/presentation/conventions/runtime-conventions) and [bootstrap conventions](/release-2/presentation/conventions/bootstrap-conventions) support the following syntax:

```csharp
conventions.IsViewModel = type => 
{
    if ( type.Namespace == "MyViewModelsNamespace" ) 
    {
        return true;
    }
    return conventions.DefaultIsViewModel( type );
};
```

For every convention there is a convention whose name is the same but prefixed with `Default*` so that it's not anymore required to keep track of the original convention we are overriding.


# Commands and DelegateCommand

WPF and Universal Applications have a really handy way to handle the concept of a command: the `ICommand` interface (<http://msdn.microsoft.com/library/system.windows.input.icommand.aspx>).

Radical has its own implementation that allows to easily hook command logic using delegates. The Radical `DelegateCommand` adds a set of features on top of the default .Net `ICommand`.

Creating a command in Radical is as easy as:

```csharp
ICommand command =  DelegateCommand.Create()
    .OnCanExecute( state =>
    {
        //command validation logic.
        return true;
     } )
     .OnExecute( state =>
     {
         //command execution logic.
     } );
```

The command entry point is the `DelegateCommand` class, in the above sample used in a fluent interface manner.


# IViewResolver

As we have already wrote when we spoke about [Runtime Conventions](/release-2/presentation/conventions/runtime-conventions) Radical utilizes by default a view first approach, that even if is completely replaceable with a ViewModel first approach, must be understood.

The main and only entry point used to resolve views is `IViewResolver` interface whose role is to resolve a view instance given a view type:

```
IViewResolver service; //injected by the IoC engine
var viewUsingGenerics = service.GetView<SampleView>();
var viewUsingType = service.GetView( typeof( SampleView ) );
```

At runtime when the `GetView` method is called the default built-in view resolver does the following things:

1. goes to the IoC container and resolves an instance of the requested view type;
2. if the view already has a `DataContext` it assumes that the view is a singleton and has been already resolved once and immediately returns the resolved view;
3. Otherwise, using the conventions:
4. Using the `ResolveViewModelType` convention determines the type of the associated ViewModel;
5. Resolves, via the container, the ViewModel;
6. Set the relation View – ViewModel;
7. Set the ViewModel as the DataContext of the View;
8. Attaches to the View the required behaviors;
9. Exposes services registered to be exposed as resources in the View
10. Returns the view to the caller;

## How to use the IViewResolver in our application

The typical usage of the view resolver in the application is to open/show another view, the easiest way is to declare a dependency on the resolver in our component:

```
class SampleViewModel
{
    readonly IViewResolver service;

    public SampleViewModel( IViewResolver service )
    {
        this.service = service;
    }

    public void ShowAView()
    {
        var myView = this.service.GetView<MyView>();
        myView.Show();
    }
}
```

We are using the simplest possible approach in order to keep the sample complexity really low.

## Notes

* In the above sample we are violating the MVVM pattern because we are dealing with a view within the ViewModel, in the chapter related to the [MessageBroker](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/messaging/message-broker.md) we’ll see how to avoid this mix.
* A view does not require a view model to work properly, the `IViewResolver` can resolve views that don't have view models;


# Default view behaviors

We have seen how Radical Presentation [resolves views instances](/release-2/presentation/iview-resolver) at runtime and we have told that during the resolution process we inject/attach to the resolved view some behaviors using a convention.

The convention attaches the following behaviors to each resolved view:

* to every view (every DependencyObject) attaches the “**DependencyObjectCloseHandlerBehavior**” whose role is to allow the view model to send a close request message to its own view without the need to handle a reference to the view;
* if the **view is a window** attaches the “**WindowLifecycleNotificationsBehavior**” used to notify to the view model the lifecycle state changes of the view (loaded, shown, activated, closing and closed);
* “else if” the **view is a FrameworkElement** attaches the “**FrameworkElementLifecycleNotificationsBehavior**” whose role is notify to the view model when the view is loaded;

The easiest way to handle view lifecycle state changes in the `ViewModel` is to setup a [callback expectation](/release-2/presentation/iview-resolver/view-life-cycle-events/callback-expectations).

## Automatic broker unsubscribe

The `WindowLifecycleNotificationsBehavior` whenever the `view` is closed invokes `ViewReleaseHandler` convention that is responsible to determine if the `ViewModel` associated with the closed `View` should be unsubscribed from all the message broker subscriptions, if any, created.


# view life cycle events

We have seen that the infrastructure has a way, by default based on behaviors, to notify a `ViewModel` that its own `View` state is changing.

## The View is a Window

If the view is a window we have several state that can be handled/intercepted by the coupled `ViewModel`:

* Loaded;
* Activated;
* Shown;
* Closing;
* Closed;

## The View is a FrameworkElement (e.g. a UserControl)

If the view is a user control the only state we can intercept is the `Loaded` event.


# Callback expectations

A view model that needs to intercept state view changes can implement an interface that declares which are the required callback(s), the supported interfaces are:

* IExpectViewLoadedCallback;
* IExpectViewActivatedCallback;
* IExpectViewShownCallback;
* IExpectViewClosingCallback;
* IExpectViewClosedCallback;

All those interfaces are pretty trivial and does not require any further explanation other then the following sample:

```csharp
class SampleViewModel : IExpectViewLoadedCallback
{
    void IExpectViewLoadedCallback.OnViewLoaded()
    {
        //code to handle the View Loaded event
    }
}
```

The only “special” one is the `IExpectViewClosingCallback` that allows the `ViewModel` to ask to the `View` to stop the closing process:

```csharp
class ChildViewModel : AbstractViewModel, IExpectViewClosingCallback
{
    void IExpectViewClosingCallback.OnViewClosing( CancelEventArgs e )
    {
        //blocks the view closing process
        e.Cancel = true;
    }
}
```

Those interfaces are designed to let the `ViewModel` intercept the state changes of **its own** `View` not of other views, the default way to intercept state changes of other views is to use the `MessageBroker`.


# notify messages

It is possible to configure a `ViewModel` to notify, via a broker message, that the state of the associated `View` has changed. The `ViewModel` class can be decorated with one, or more, of the following attributes, depending of the notifications we need:

* `NotifyLoadedAttribute`
* `NotifyShownAttribute`
* `NotifyActivatedAttribute`
* `NotifyClosedAttribute`

All the notifications will be broadcasted asynchronously using the `MessageBroker`, such as in following sample:

```csharp
[NotifyLoaded, NotifyClosed]
class MySampleViewModel : AbstractViewModel
{
}
```


# Message broker MVVM built-in messages

Radical Presentation relies on the [`MessageBroker`](/release-2/concepts/message-broker) to broadcast messages that can be used by the application to easily manage a lot of stuff that otherwise can be a bit cumbersome.

The following is the list of the Radical Presentation built-in messages and their meaning/usage.

## Application Messages

These messages are broadcasted or dispatched by the application to notify application level state changes.

* `ApplicationBootCompleted`:
  * **broadcasted** *asynchronously* by application bootstrapper to notify that the boot process is completed.
* `ApplicationShutdownRequest`:
  * can be dispatched or broadcasted by anyone to request programmatically the application to shutdown. it is highly recommended that the message is broadcasted asynchronousl&#x79;*.* When the application shutdown is requested via the `ApplicationShutdownRequest` message, the following events might be dispatched:
    * `ApplicationShutdownRequested`:
      * **dispatched synchronously** by application bootstrapper to notify that the application has started the shutdown process, this event is dispatched synchronously to allow subscribers to easily cancel the shutdown process using a well known approach similar to the one exposed by the .net `CancelEventArgs`.
    * `ApplicationShutdownCanceled`:
      * **broadcasted** *asynchronously* by application bootstrapper to notify that the shutdown process has been canceled.
* `ApplicationShutdown`:
  * **broadcasted** *asynchronously* by application bootstrapper to notify that the shutdown process is in progress, from this point on the process is not cancellable any more.

*Note*:

All the “application shutdown” related events/messages brings with them an enumeration (`ApplicationShutdownReason`) that identifies why the application is shutting down.

## View/ViewModel Messages

The following messages are broadcasted or dispatched by the infrastructure when the state of a view changes or to request a change to the view status.

* `CloseViewRequest`:

  * can be dispatched or broadcasted by anyone to request programmatically to a view to close. it is highly recommended that the message is broadcasted *asynchronously*.

    The message is generally used to close the view of the view model that issues the message, but the shape of the message allows to close a view attached to any view model.

  ```csharp
  class SampleViewModel
  {
      readonly IMessageBroker broker;

      public SampleViewModel( IMessageBroker broker )
      {
          this.broker = broker;
      }

      public void Sample()
      {
          this.broker.Broadcast( this, new CloseViewRequest( this ) );
      }
  }
  ```
* `ViewModelClosed`:
  * **broadcasted** asynchronously by the infrastructure to notify that a view and an associated ViewModel has been closed.
* `ViewModelClosing`:
  * **dispatched synchronously** by the infrastructure to notify that the a view and an associated ViewModel is closing, this event is dispatched synchronously to allow subscribers to easily cancel the close process using a well known approach similar to the one exposed by the .net `CancelEventArgs`.
* `ViewLoaded`:
  * **broadcasted** *asynchronously* by the infrastructure to notify that a view has been loaded.
* `ViewModelLoaded`:
  * **broadcasted** *asynchronously* by the infrastructure to notify that a ViewModel has been loaded.

*Note*:

`ViewLoaded` and `ViewModelLoaded` messages are broadcasted only under certain circumstances, depending on the result of the `ShouldNotifyViewLoaded` and `ShouldNotifyViewModelLoaded` [conventions](/release-2/presentation/conventions/runtime-conventions).

* `ViewModelShown`:
  * **broadcasted** *asynchronously* by the infrastructure to notify that a view and an associated ViewModel has been shown for the first time.


# Application boot process

What happens under the hood when we write this really trivial piece of code?

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>();
    }
}
```

As we have already seen in the [quick start](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/README.md#steps-to-bootstrap-your-project-in-3-minutes) we are doing 2 main choices:

* We boot using the default IoC container provided by `Microsoft.Extensions.DeendencyInjection`;
* We declare that the `MainView` window is the main/shell window of our application;

Internally the application boot process is not so trivial as it appears from the outside, when the `Startup` event is raised by the WPF application the bootstrapper:

## Identifies assemblies to scan

In order to configure the IoC containers assemblies needs to scanned to load types that need to be registered for DI. This is accomplished by the assembly scanner. It's possible to customize some of the assembly scanner behaviors by using the `AssemblyScanner` property of the `BootstrapConfiguration` instance, like in the following snippet:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
        {
            var scanner = configuration.AssemblyScanner;
            scanner.DirectorySearchOptions = SearchOption.TopDirectoryOnly; //default value
        });
    }
}
```

### Register additional types in the IoC container

To register custom types, other than the ones already automatically registered via bootstrap conventions, a dependencies installer is required. Create a class that implements the `IDependenciesInstaller` interface. A class instance will be automatically created at runtime and the `Install` method will be invoked:

```csharp
public class MyCustomInstaller : IDependenciesInstaller
{
   public void Install(BootstrapConventions conventions, IServiceCollection services, IEnumerable<Type> assemblyScanningResults)
   {
      services.AddSingleton<MyCustomSingleton>();
   }
}
```

## Creates the service provider

Once assemblies and types are scanned and identified through bootstrap conventions the default IoC container provided by `Microsoft.Extensions.DeendencyInjection` is created. In case an instance of the created `IServiceProvider` is required outside the scope of the Radical application, it can be retrieved using the following snippet:

```csharp
public partial class App : Application
{
    public App()
    {
        IServiceProvider container = null;
        this.AddRadicalApplication<MainView>(configuration =>
        {
            configuration.OnBootCompleted(serviceProvider => container = serviceProvider);
        });
    }
}
```

## ShutdownMode

WPF applications have the concept of `ShutdownMode`. Application bootstrapper does not change in any way the default value of the `Application.Current.ShutdownMode` unless explicitly requested by user:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
        {
            configuration.OverrideShutdownMode(ShutdownMode.OnLastWindowClose);
        });
    }
}
```

## Principal initialization

Once the application services are setup the bootstrapper takes care of setting up the `Thread.CurrentPrincipal`, the default behavior is to use the current user `Windows identity`. This behavior can be changed by setting a different principal right after the boot process is completed, using the `OnBootCompleted` handler;

## Culture & UICulture

After setting up the principal and finally returning control to the application the boot process has the option to setup the `Culture` and the `UICulture` of the current `Thread`. The default behavior is to use values of the hosting OS. The default behavior can be overwritten in the following way:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
        {
           configuration.UseCulture(container=>new CultureInfo("it-IT"));
           configuration.UseUICulture(container=>new CultureInfo("it-IT"));
        });
    }
}
```

## Boot

Once everything is setup the bootstrapper gives us the ability to take part into the boot process before the main window is shown:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
        {
           configuration.OnBooting(container=>
          {
             //boot is in progress, UI is not visible yet.
          });
        });
    }
}
```

## BootCompleted

The last event in the process is the one used to show the main window, we have the opportunity to be notified using the exposed handler:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
    {
       configuration.OnBootCompleted(container=>
       {
          //UI is fully setup
       });
    });
    }
}
```

Some of the state of the boot process are also [notified to the application using the message broker](/release-2/presentation/built-in-messages).

## Intercepting unhandled exceptions

if we need to be notified whenever an unhandled exception occurs in our application we can use the provided hook:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
        {
        configuration.OnUnhandledException(ex=> { /* deal with exception */ });
        });
    }
}
```

## Handling the application Shutdown

As for the startup we can also handle the shutdown process of the application:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration =>
        {
            configuration.OnShuttingDown(args=> { });
        });
    }
}
```

When the application shuts down the provided delegate is invoked passing in wehter the boot was completed or not, and the reason why the application is shutting down:

```csharp
public enum ApplicationShutdownReason
{
    /// <summary>
    /// The application has been shutdown using the Radical canonical behaviors.
    /// In this case the shutdown process can be canceled.
    /// </summary>
    UserRequest = 0,

    /// <summary>
    /// The application is shutting down because another
    /// instance is already running and the application
    /// is marked as singleton.
    /// </summary>
    MultipleInstanceNotAllowed = 1,

    /// <summary>
    /// The application is shutting down because the operating system session is ending.
    /// </summary>
    SessionEnding,

    /// <summary>
    /// The application has been shut down using the App.Current.Shutdown() method.
    /// </summary>
    ApplicationRequest,
}
```

As we can see we can easily determine why the application is shutting down. Currently there is no way from the application bootstrapper to cancel the shutdown process, in order to achieve that we need to subscribe to the `ApplicationShutdownRequested` message via the message broker.

Someone may have noticed that one of the shutdown reasons is `MultipleInstanceNotAllowed`, Radical can handle singleton application for us with minimal effort, take a look at [singleton applications](/release-2/presentation/boot-process/singleton-applications).

[Application shutdown](/release-2/presentation/boot-process/application-shutdown) discusses all the details of the shutdown process and how to control/invoke it.


# Application configuration

The Radical application behavior, the bootstrap and runtime conventions, and the assembly scanning behavior can be be tweaked by accessing the `BootstrapConfiguration` instance:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<MainView>(configuration=>
        {
           //use the configration instance
        });
    }
}
```

## Conventions

Conventions can be customized during the application setup phase, for more information about convention refer to the [conventions](/release-2/presentation/conventions) section.

### Bootstrap conventions

[Bootstrap conventions](/release-2/presentation/conventions/bootstrap-conventions) are designed to configure the Radical application boostrap phase and the IoC/DI setup. Bootstrap conventions customization happens throughout the `BootstrapConventions` object exposed by the configuration instance.

## Assembly scanning

By default a Radical application scans all the assemblies found in the bin directory and in its subdirectories. It's possible to configure the assembly scanning behavior to customize how types are loaded and used to configure the IoC/DI infrastructure. Refer to the [boot process](/release-2/presentation/boot-process) documentation for more information.

## ExposeServiceAsResource

Radical registers, during the application boot phase, all dependencies as components in the IoC container. Other components can depend on registered dependencies via DI. There are scenarios when DI is not available, for example when using WPF template selectors, and the code needs a dependency that is registered in the IoC container. For these scenarios, it's possible to expose registered components as resources both at the application level or at the view level. For more information refer to the [Services as Resources documentation](/release-2/presentation/resources/services-as-resources).

## Singletons

There are cases in which we need that our application cannot be started twice by the user, these applications are called singleton applications. For more information on how to customize the bootstrapp process to handle such cases, refer to the [singleton applications documentation](/release-2/presentation/boot-process/singleton-applications).

## Spalsh screen

Radical has built-in support for splash screens. Refer to the [splash screen how to](/release-2/how-to/splash-screen), for more details.


# Application shutdown

In order to shutdown an application built using Radical there are 3 main options.

**Canonical WPF way: `App.Current.Shutdown();`**

There is no reason to not use the default WPF standard way to shutdown the application, the only thing we cannot do in this case is to prevent the shutdown process to complete, we have no control over it.

When the `App.Current.Shutdown()` method is called the bootstrapper raises, via the message broker, the following event:

* `ApplicationShutdown`: that simply notifies to the application that is shutting down;

**2 way shutdown via `RadicalApplication.Shutdown();`**

If we need an option to cancel the application shutdown process we should use the `Shutdown()` method exposed by the `RadicalApplication`. In this way the following events are broadcasted/dispatched by the message broker:

1. `ApplicationShutdownRequested` is dispatched synchronously to the application and has a `Cancel` property that can be set to true to cancel the shutdown process;
2. `ApplicationShutdownCanceled` is broadcasted whenever the shutdown process is cancelled;
3. `ApplicationShutdown` is finally dispatched asynchronously to notify to the application that is shutting down;

To get an instance of the current `RadicalApplication` the following snippet can be used:

```
public partial class App : Application
{
    public App()
    {
        var radicalApplication = this.AddRadicalApplication<Presentation.MainView>();
    }
}
```

NOTE: the current `RadicalApplication` is not registered in the IoC container.

**2 way shutdown via `ApplicationShutdownRequest` message**

Exactly the same approach as above can be obtained broadcasting, via the message broker, the `ApplicationShutdownRequest` message, without the need to have a reference to the current radical application.


# Singleton applications

There are cases in which we need that our application cannot be started twice by the user, these applications are called singleton applications. We can use the really powerful Radical Presentation application bootstrapper to create a singleton application:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<Presentation.MainView>(configuration=>
        {
           configuration.RegisterAsLocalSingleton("my-singleton-key");
        });
    }
}
```

Using the `RegisterAsLocalSingleton` method we can set the singleton key (that in the end is the name of the Mutex used to handle “singletoness”) and make so the application is a singleton for the current user session. To make the application singleton globally for the running OS independently of the user (Global) use the `RegisterAsGlobalSingleton` method.

If the system determines that the application can run we have the opportunity to change this decision:

```csharp
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<Presentation.MainView>(configuration=>
        {
           configuration.RegisterAsLocalSingleton("my-singleton-key");
           configuration.OnSingletonApplicationStartup(e =>
           {
               e.AllowStartup = false;
           });
        });
    }
}
```

We can use the same exact approach as above to handle the case in which the application is starting and another instance is already running, in this case the value of the `AllowStartup` property is false, indicating that another instance is running.


# AbstractMementoViewModel

The [AbstractViewModel](/release-2/presentation/abstract-view-model) base class provides us a way to create `ViewModels` with a set of base features that satisfies most of the basic requirements.

When dealing with complex MVVM based application we sometimes need to deal with the user editing graph of objects, changing property values and/or adding/removing items from and to collections; the end user is generally used to editors, such as Microsoft Word, that provides rich editing features with Undo/Redo support.

Implementing Undo/Redo like features is not as simple as it can appear in the first place, Radical supports a feature called `Memento`, based on the memento pattern, that allows us to easily implement a change tracking system with fine grain control over what is going on and with a rich set of features out of the box.

The first, and easy, step to start using `Memento` is to inherit our `ViewModels` from the `AbstractMementoViewModel` class:

```csharp
class MainViewModel : AbstractMementoViewModel
{

}
```

The above code immediately enrich our `ViewModel` with change tracking capabilities, nothing else needs to be done in order to implement a basic Undo/Redo support in the ViewModel except writing properties using the Radical [Property System](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/entities/property-system.md).

Given that an object graph can be complex and shaped as we like we need a single entry point to achieve at least two goals:

* Access the current state of the graph;
* Control the state of the graph;

The one component to rule both aspects is the [Change Tracking Service](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/memento/change-tracking-service.md). The next step is to create a `ChangeTrackingService` instance to track the state of the model.

```csharp
class MainViewModel : AbstractMementoViewModel
{
    public MainViewModel()
    {
        var memento = new ChangeTrackingService();
        memento.Attach( this );
    }
}
```

We created a new instance of the memento service and instructed it to keep track of changes that will occur to `this` instance.

Once we setup the memento we can access the state of the graph via its properties such as `IsChanged`, `CanUndo` and `CanRedo`, or we can control the state of the graph via the exposed methods, such as, but not only, `AcceptChanges()`, `RejectChanges()`, `Undo()` or `Redo()`.

As we said in order to allow a transparent tracking we need to leverage the power of the Radical property system, using properties as the following will immediately trigger the memento and will start keeping track of changes:

```csharp
public String Text
{
    get { return this.GetPropertyValue( () => this.Text ); }
    set { this.SetPropertyValue( () => this.Text, value ); }
}
```

One thing to keep in mind is that every time we write to the property, once the graph is attached to the memento, that write operation will be tracked:

```csharp
class MainViewModel : AbstractMementoViewModel
{
    public MainViewModel()
    {
        var memento = new ChangeTrackingService();
        memento.Attach( this );

        this.Text = "text property default value";
    }

    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }
}
```

Setting the `Text` property default/initial value in the above sample will trigger the `ChangeTrackingService` that now reports its state as changed: `IsChanged` equals `true`.

In the above minimalistic sample it is obvious that the easiest solution is to set the property value *before* attaching the graph to the memento, but this is not always possible:

```csharp
class MainViewModel : AbstractMementoViewModel
{
    public MainViewModel()
    {
        var memento = new ChangeTrackingService();
        memento.Attach( this );

        this.SetInitialPropertyValue( () => Text, "text property default value" );
    }

    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }
}
```

The `SetInitialPropertyValue` method is aware of the fact that a memento can listen to changes and it won't trigger any change in the state.

Note: the `SetInitialPropertyValue` is a shortcut to access the metadata of the `Text` property, it is exactly the same as:

```csharp
this.GetPropertyMetadata( () => this.Text )
    .WithDefaultValue( "text property default value" );
```

What's next:

* dive into the [Change Tracking Service](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/memento/change-tracking-service.md) component.
* Understand how to handle change tracking in [simple ViewModels](/release-2/presentation/abstract-memento-view-model/memento-change-tracking-simple-view-model), [complex ones and collections](/release-2/presentation/abstract-memento-view-model/memento-change-tracking-collection-and-complex-view-model-md).

## Frequently Asked Questions

**Q**: Is `AbstractMementoViewModel` required?\
*A*: No, it is not required, it is handy. A memento entity is required to be a `IMemento` instance, the easiest way to implement a memento entity is to inherit from `MementoEntity`, that since it implements `INotifyPropertyChanged` is it enough to partecipate in the MVVM data binding process. Inheriting from `AbstractMementoViewModel` adds more features such as automatic validation support.

**Q**: Why isn't the `AbstractMementoViewModel` providing me a `ChangeTrackingService` instance?\
*A*: Because there is no 1:1 match between an edited entity and a tracking service, most of the time a single tracking service will track more than one entity at a time.


# Simple ViewModel graphs

When dealing with data editing and the MVVM pattern we need to be aware that the shortest path from the model to the UI is not always the best solution.

Imagine a scenario where we want to edit a `Person` instance that is loaded from a persistente storage, such as a database, the `Person` instance can be directly bound to the UI but it requires us to implement the `INotifyPropertyChanged` interface and if we want to enable it for the `ChangeTrackingService` we need to inherit from a base class.\
Both are not an option when dealing with the Single Responsibility Principle and with POCO objects.

In the above scenario we need to introduce at least two more actors, other than the `Person` data model:

1. A `PersonViewModel` that will be responsible to enrich the Person with property change notification support and with change tracking capabilities;
2. An `EditorViewModel` that will allow a clean separation of responsibilities owning all the  relationship with the memento.

The second bullet is especially true when dealing with complex graph and/or with more than one tracked entity at the same time. Given a `Person` class like the following:

```csharp
class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}
```

We can create a `PersonViewModel` such as:

```csharp
class PersonViewModel : MementoEntity
{
    public void Initialize( Person person, Boolean registerAsTransient )
    {
        if( registerAsTransient )
        {
            this.RegisterTransient();
        }

        this.SetInitialPropertyValue( () => this.FirstName, person.FirstName );
        this.SetInitialPropertyValue( () => this.LastName, person.LastName );
    }

    public String FirstName
    {
        get { return this.GetPropertyValue( () => this.FirstName ); }
        set { this.SetPropertyValue( () => this.FirstName, value ); }
    }

    public String LastName
    {
        get { return this.GetPropertyValue( () => this.LastName ); }
        set { this.SetPropertyValue( () => this.LastName, value ); }
    }
}
```

The first thing is to build a memento-enabled facade, that can grow adding feature, to enable change tracking and property change notifications in a Person-like class.\
In the above sample the `PersonViewModel` and the `Person` class are basically the same, we can say that this is corner case, most of the time in real scenarios there will be a huge difference between the model and the editing view model.

We are introducing a `Initialize` method, for the sake of the sample we can do the same thing using a constructor, using a `Initialize` method allows us to easily resolve `PersonViewModel` instances using an inversion of control container without the need to deal with the currently edited `Person` runtime instance. At initialization time we are doing 2 important things:

1. calling the `RegisterTransient()` method of the base class to register the current instance as transient, if required; To dive into the meaning of a transient entity look at the [Change Tracking Service API](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/memento/change-tracking-service-api.md);
2. using the `SetInitialPropertyValue()` method to initialize the default value of the `PersonViewModel` properties without affecting its tracking state;

Once we have setup our `ViewModel` we can build the editor:

```csharp
public class EditorViewModel : AbstractViewModel
{
    readonly IChangeTrackingService service = new ChangeTrackingService();

    public EditorViewModel()
    {
        var observer = MementoObserver.Monitor( this.service );

        this.UndoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanUndo )
            .OnExecute( o => this.service.Undo() )
            .AddMonitor( observer );

        this.RedoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanRedo )
            .OnExecute( o => this.service.Redo() )
            .AddMonitor( observer );

        var person = new Person()
        {
            FirstName = "Mauro",
            LastName = "Servienti"
        };

        var entity = new PersonViewModel();
        this.service.Attach( entity );
        entity.Initialize( person, false );

        this.Entity = entity;
    }

    public ICommand UndoCommand { get; private set; }
    public ICommand RedoCommand { get; private set; }

    public PersonViewModel Entity
    {
        get { return this.GetValue( () => this.Entity ); }
        private set { this.SetValue( () => this.Entity, value ); }
    }
}
```

There is a lot going on here we are creating an editor and at first we setup our `ChangeTrackingService` instance, that in this specific sample is bound to the editor itself. In the constructor we are setting up a [MementoObserver](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/observers/memento-observer.md) to watch the memento instance and we are binding that observer to 2 commands whose role is to expose Undo/Redo functionalities to the UI.\
Last we create a `Person` instance, in real scenarios the `Person` instance is expected to arrive from a persistent storage or a remote resource, we create the `PersonViewModel`, attach it to the memento service and finally initialize it with the person data source.

We finally expose both commands and the `PersonViewModel` instance to the `View`.


# Collections and complex ViewModel graphs

We have already discussed how to handle change tracking in [collections](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/memento/collections.md) and in [complex models](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/memento/complex-graph.md) and we have introduced how to handle change tracking in a [MVVM based model](/release-2/presentation/abstract-memento-view-model/memento-change-tracking-simple-view-model).

We want to start where we left adding a collection to the `Person` class and setup the entire editing pipeline for the collection too.

```csharp
class Person
{
    public Person()
    {
        this.Addresses = new List<Address>();
    }

    public String FirstName { get; set; }
    public String LastName { get; set; }
    public IList<Address> Addresses { get; private set; }
}

class Address
{
    public String Street { get; set; }
    public String City { get; set; }
}
```

If we look at the [considerations we did for the simple view model](/release-2/presentation/abstract-memento-view-model/memento-change-tracking-simple-view-model) is obvious that the `Address` class itself needs a `ViewModel` and an editor and also the collection exposed by the `Person` class needs an editor and potentially a `ViewModel` depending on the type of editing that we want to support.

We need to face a couple more issues related to the fact that having one graph coming from a persistent storage and one different graph bound to the UI we need to keep them in sync.

The `AddressViewModel` will be as simple as the `PersonViewModel` we already saw:

```csharp
class AddressViewModel : MementoEntity
{
    public void Initialize( Address address, Boolean registerAsTransient )
    {
        if( registerAsTransient )
        {
            this.RegisterTransient();
        }

        this.SetInitialPropertyValue( () => this.Street, address.With( a => a.Street ).Return( s => s, "" ) );
        this.SetInitialPropertyValue( () => this.City, address.With( a => a.City ).Return( c => c, "" ) );
    }

    public String Street
    {
        get { return this.GetPropertyValue( () => this.Street ); }
        set { this.SetPropertyValue( () => this.Street, value ); }
    }

    public String City
    {
        get { return this.GetPropertyValue( () => this.City ); }
        set { this.SetPropertyValue( () => this.City, value ); }
    }
}
```

Nothing new, except for the `With`/`Return` syntax that is simply a `monad` like way to guard against `null` adding a default value.

Things get much more interesting as we look at the `PersonViewModel`, that revisited, now handle the `Addresses` list:

```csharp
public class PersonViewModel : MementoEntity
{
    MementoEntityCollection<AddressViewModel> addressesDataSource;

    public void Initialize( Person person, Boolean registerAsTransient )
    {
        if( registerAsTransient )
        {
            this.RegisterTransient();
        }

        this.SetInitialPropertyValue( () => this.FirstName, person.FirstName );
        this.SetInitialPropertyValue( () => this.LastName, person.LastName );

        this.addressesDataSource = new MementoEntityCollection<AddressViewModel>();
        this.addressesDataSource.BulkLoad( person.Addresses, a =>
        {
            return this.CreateAddressViewModel( a, registerAsTransient );
        } );

        this.Addresses = this.addressesDataSource.DefaultView;
        this.Addresses.AddingNew += ( s, e ) =>
        {
            e.NewItem = this.CreateAddressViewModel( null, true );
            e.AutoCommit = true;
        };
    }

    AddressViewModel CreateAddressViewModel( Address a, Boolean registerAsTransient )
    {
        var vm = new AddressViewModel();
        vm.Initialize( a, registerAsTransient );
        return vm;
    }

    protected override void OnMementoChanged( IChangeTrackingService newMemento, IChangeTrackingService oldMemento )
    {
        base.OnMementoChanged( newMemento, oldMemento );
        if( oldMemento != null )
        {
            oldMemento.Detach( this.addressesDataSource );
        }
        if( newMemento != null )
        {
            newMemento.Attach( this.addressesDataSource );
        }
    }

    public String FirstName
    {
        get { return this.GetPropertyValue( () => this.FirstName ); }
        set { this.SetPropertyValue( () => this.FirstName, value ); }
    }

    public String LastName
    {
        get { return this.GetPropertyValue( () => this.LastName ); }
        set { this.SetPropertyValue( () => this.LastName, value ); }
    }

    public IEntityView<AddressViewModel> Addresses
    {
        get;
        private set;
    }
}
```

We are using a `MementoEntityCollection<T>` to keep track of changes that occurs to the collection structure, such as add or address removal, we are using the `BulkLoad` API to achieve 2 goals:

1. Add a transformation on load, we are basically iterating over `Address` instances adding to the collection `AddressViewModel` instances, and the transformation is done in the delegate via the `CreateAddressViewModel` that simply wraps the `Address` instance, if any, into the `AddressViewModel` instance initializing it as we saw for the `Person` / `PersonViewModel` relationship;
2. disable at once collection notifications, a `IEntityCollection<T>` has built-in support for changes notification, and a `MementoEntityCollection<T>` for change tracking, the `BulkLoad` API will disable notifications and tracking for the entire load process re-enabling both at the end;

We then expose our `Addresses` list as an `IEntityView`, that is an `IBindingListView` implementation, achieving 2 goals:

1. In the `View` we can now bind the collection to a `DataGrid`, for example, gaining full support for sorting, filtering and column generation;
2. We can have control, very easily, over new items generation even if the request is done by a `DataGrid` control: simply add a `EventHandler` to the `AddingNew` event of the `IEntityView` and create the expected instance;

The last thing to do is to manually propagate the current `ChangeTrackingService` instance to the collection owned by the `PersonViewModel` class, we do that overriding the `OnMementoChanged` method that is called every time the current memento tracking this instance changes.

The last thing is to update the `EditorViewModel` to create a sample data set; we also add a couple of commands to manage the `Addresses` collection and a property to keep track of the currently selected address:

```csharp
class EditorViewModel : AbstractViewModel
{
    readonly IChangeTrackingService service = new ChangeTrackingService();

    public EditorViewModel()
    {
        var observer = MementoObserver.Monitor( this.service );

        this.UndoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanUndo )
            .OnExecute( o => this.service.Undo() )
            .AddMonitor( observer );

        this.RedoCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.service.CanRedo )
            .OnExecute( o => this.service.Redo() )
            .AddMonitor( observer );

        this.CreateNewAddressCommand = DelegateCommand.Create()
            .OnExecute( o => 
            {
                this.SelectedAddress = this.Entity.Addresses.AddNew();
            } );

        this.DeleteAddressCommand = DelegateCommand.Create()
            .OnCanExecute( o => this.SelectedAddress != null )
            .OnExecute( o => 
            {
                this.SelectedAddress.Delete();
                this.SelectedAddress = this.Entity.Addresses.FirstOrDefault();
            } )
            .AddMonitor( PropertyObserver.For( this ).Observe( v => v.SelectedAddress ) );

        var person = new Person()
        {
            FirstName = "Mauro",
            LastName = "Servienti"
        };

        person.Addresses.Add( new Address( person )
        {
            City = "My town",
            Street = "Where I live"
        } );

        var entity = new PersonViewModel();
        entity.Initialize( person, false );
        this.service.Attach( entity );
        this.Entity = entity;
    }

    public ICommand UndoCommand { get; private set; }
    public ICommand RedoCommand { get; private set; }
    public ICommand CreateNewAddressCommand { get; private set; }
    public ICommand DeleteAddressCommand { get; private set; }

    public PersonViewModel Entity
    {
        get { return this.GetPropertyValue( () => this.Entity ); }
        private set { this.SetPropertyValue( () => this.Entity, value ); }
    }

    public IEntityItemView<AddressViewModel> SelectedAddress
    {
        get { return this.GetPropertyValue( () => this.SelectedAddress ); }
        private set { this.SetPropertyValue( () => this.SelectedAddress, value ); }
    }
}
```


# Validation and Validation Services

## Validation and Validation Services

One of the most common task during the development of a rich client application is the need to handle the validation of the data input by the user running the application. Radical fully supports WPF validation engine and does all what can be done to alleviate the need for the developer to write infrastructure code.

Let’s start from the end of the story, using a view model like the following:

```csharp
class SampleViewModel : AbstractViewModel, IRequireValidation
{
    public SampleViewModel()
    {
        ValidationService = new DataAnnotationValidationService<SampleViewModel>( this );
    }

    [Required( AllowEmptyStrings = false )]
    public String Text
    {
        get { return this.GetPropertyValue( () => this.Text ); }
        set { this.SetPropertyValue( () => this.Text, value ); }
    }
}
```

and a view as:

```markup
<TextBox Text="{markup:EditorBinding Path=Text}" Grid.Row="0" Margin="33,47,220,0" Height="25" VerticalAlignment="Top" />
<ListBox Grid.Row="1" Grid.IsSharedSizeScope="True" ItemsSource="{Binding Path=ValidationErrors}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition SharedSizeGroup="propertyName" Width="Auto" />
                    <ColumnDefinition SharedSizeGroup="errorText" Width="*" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding Path=Key}" Margin="0,0,5,0" Grid.Column="0" Foreground="Red" />
                <TextBlock Text="{Binding}" Grid.Column="1" Foreground="Brown" />

            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
```

we immediately get full validation support, even with error summary:

![Validation error and error summary](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/images/cab-be-validated-1.png)

## WPF validation support

Obviously we are not reinventing the wheel, we are simply leveraging the power of the built-in validation support that WPF already has using the `INotifyDataErrorInfo` interface; for a detailed explanation of the WPF validation capabilities take a look a the following MSDN Magazine detailed article: <https://docs.microsoft.com/en-us/archive/msdn-magazine/2010/june/msdn-magazine-input-validation-enforcing-complex-business-data-rules-with-wpf>

## How IRequireValidation works

`IRequireValidation` interface inherits from the built-in `INotifyDataErrorInfo` interface, `IRequireValidation` is defined as follows:

```csharp
public interface IRequireValidation : INotifyDataErrorInfo
{
    Boolean IsValid { get; }

    ObservableCollection<ValidationError> ValidationErrors { get; }

    Boolean Validate();

    Boolean Validate( ValidationBehavior behavior );

    Boolean Validate( String ruleSet, ValidationBehavior behavior );

    event EventHandler Validated;

    void TriggerValidation();

    void ResetValidation();
}
```

All the interface methods and properties are already implemented by the base `AbstractViewModel`, the user is only required to inherit from the interface so to tell to the WPF infrastructure that the `DataContext` of the `View` is a class the implements `INotifyDataErrorInfo`. Going deeper the `IRequireValidation` interface exposes the following features:

* **IsValid**: determines if the current view model validation failed or is valid;
* **ValidationErrors**: Gives access to a list of validation errors occurred during the validation process;
* **Validate()**: the validate method, and its overloads, allows to manually trigger the validation process, by default the validation process is automatically triggered by WPF for each property set during a data binding operation; The `ValidationBehavior` enumeration allows to customize the validation engine behavior;
* **Validated**: the validated event is raised each time the validation process is completed;
* **TriggerValidation**: the `TriggerValidation` method allows to programmatically “ask” to WPF to trigger the error status even on properties, valid or invalid, that has never been involved in a binding write operation;

  The typical scenario is a form with a submit button, if the user never fills the form but simply presses the submit button we want to visually show invalid properties and fields, the `TriggerValidation` method is designed to achieve this.
* **ResetValidation**: Resets the staus of the validation infrastructure to its default value, that is no errors and valid.

### Validation Services

The other step that must be accomplished by the user is to define the engine used to run the validation process, in order to achieve that is enough to set the `VaidationService` protected property.

In the above sample we are using the most powerful validation service provided built-in in Radical, we are using the `DataAnnotationValidationService<TViewModel>` that, as the name implies, works against the [Data Annotation services](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx), and add support for custom inline validation rules.

### Editor bindings

As we have seen WPF requires that the view model inherits the `INotifyDataErrorInfo` interface, in order to run the validation process, the second requirement is that each binding is configured to enable validation, since there are several properties to set to true this operation tends to be tedious and prone to errors; in order drastically simplify the validation setup [Radical](https://github.com/RadicalFx/radical) offers its [own binding extension](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/markup/editor-binding.md) with everything setup as expected:

```markup
<TextBox Text="{markup:EditorBinding Path=Text}" />
```

The `EditorBinding` is a standard binding with everything already setup for validation, the `EditorBinding` markup extension can be found in the `http://schemas.radicalframework.com/windows/markup` xml namespace.

### First time property validation

Another issue of the built-in WPF validation that the Radical validation system solves is the first time validation that WPF runs when a binding operation is performed for the first time, at the first property get.

In a scenario where we have a form bound to a view model we do not want to display the form the first time as already invalid, since the user cannot understand why the form is invalid since there has not been any interaction.

In order to solve this scenario the Radical validation system discard the first validation request for each bound property, in order to change this behavior it is enough to override the protected method `ValidationCalledOnceFor( String propertyName )` that the infrastructure calls in order to understand if the given property has been validated at least once.

## Custom validation

In order to build your own validation logic is not necessary to create a custom validation service, even if it possible, because we have already added support for custom validation rules and custom advanced validation in the built-in `DataAnnotationValidationService`.

### Custom rules

There are scenarios in which validation attributes are not enough and we do not want to build a new validation attribute from scratch maybe because we already know that it will be used only in that specific scenario, in this case the best approach is to add a custom validation rule on the fly:

```csharp
class SampleViewModel : AbstractViewModel, IRequireValidation
{
    public SampleViewModel()
    {
        ValidationService = new DataAnnotationValidationService<SampleViewModel>( this )
        .AddRule
            (
                property: () => this.Text,
                rule: ctx => ctx.Failed("This is the error message.")
            );
    }
}
```

We can add as much rule as we want for each property, the context (`ctx` parameter in the above sample) passed to the rule evaluation lambda and the error generator lambda has the following signature:

```csharp
public class ValidationContext<TViewModel>
{
    public TViewModel Entity { get; private set; }

    public String RuleSet { get; set; }

    public String PropertyName { get; set; }

    public IValidator<TViewModel> Validator { get; private set; }

    public ValidationResults Results { get; private set; }
}
```

and we can use it to access the whole entity to do a broader validation not specifically scoped to the property we are validating.

### Advanced validation

If none of the above options fit our needs we can integrate into the validation process a fully custom validation piece of code just implementing, in our view model, the `IRequireValidationCallback<TViewModel>` interface:

```csharp
class ValidationSampleViewModel : AbstractViewModel,
        ICanBeValidated,
        IRequireValidationCallback<ValidationSampleViewModel>
{
    public Int32 Sample
    {
        get;
        set;
    }

    public void OnValidate( ValidationContext<ValidationSampleViewModel> context )
    {
        context.Results.AddError( () => this.Sample, "This is fully custom." );
    }
}
```

Each time the validation process run, if the validated view model implements the `IRequireValidationCallback<TViewModel>`, the `OnValidate` method is called allowing us to perform a fully custom validation process.


# Resources


# Services as resources

Radical registers, during the application boot phase, all dependencies as components in the IoC container. Other components can depend on registered dependencies via DI. There are scenarios when DI is not available, for example when using WPF template selectors, and the code needs a dependency that is registered in the IoC container. For these scenarios, it's possible to expose registered components as resources both at the application level or at the view level. To expose a service at the application level, the following API can be used:

```
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<Presentation.MainView>(configuration => 
        {
            configuration.ExposeServiceAsResource<MyServiceType>();
        });
    }
}
```

If a service needs to be exposed only in the resources of a specific View, this other API can be used:

```
public partial class App : Application
{
    public App()
    {
        this.AddRadicalApplication<Presentation.MainView>(configuration => 
        {
            configuration.ExposeServiceAsResource<MyServiceType, MyView>();
        });
    }
}
```

It's possible to change the way resource keys are generated for exposed services via the `GenerateServiceStaticResourceKey` [convention](/release-2/presentation/conventions/runtime-conventions)

NOTE: Be sure to not expose transient components as this might change their expected life-cycle.


# ViewModels as resources

There scenarios in which it could be handly to have the current View ViewModel being registered also as a View resource. ViewModels can be exposed as a View resource via the `ExposeViewModelAsStaticResource` [runtime convention](/release-2/presentation/conventions/runtime-conventions). The default behavior is that ViewModels are never exposed as resources.

It's possible to change the way resource keys are generated for exposed ViewModels via the `GenerateViewModelStaticResourceKey` [convention](/release-2/presentation/conventions/runtime-conventions)


# UI Composition

## UI Composition

Radical offers a fully flagged UI Composition engine based on the concept of regions.

> A `UI Composition` sample is available in the [Radical-Samples repository](https://github.com/RadicalFx/documentation/tree/master/samples).

## Concepts

A `region` is a named injectable portion of the UI where other components can inject their on content. A region is *attached* to a `DependencyObject` on the UI, depending on the type of the object the region is attached to the region behavior changes. Radical has 3 different main region types:

* `IContentRegion<T>`: a content region is thought for a `ContentPresenter` or a `ContentControl` UIElement, it can host one single content at a time and each time a new content is set the previous one will be removed;
* `IElementsRegion<T>`: an elements region can host multiple contents at a time, it is thought for a `Panel` UIElement, so each WPF control that inherits from panel, such as the `StackPanel`, can be used with an `IElementsRegion`; Content from an `IElementsRegion` can be added or removed and will be available depending on the logic implemented by the underlying UIElement;
* `ISwitchingElementsRegion<T>`: a switching elements region is an element region that, other than being able to host multiple elements at a time, has also the concept of an active element that can change over time; a typical sample is a `TabControl` where each `TabItem` can be seen;

*Note*: each time a content is removed from a region its lifecycle is managed as every View/ViewModel:

* View and ViewModel will be released;
* If View or ViewModel implements `IDisposable` they will be disposed;
* If View or ViewModel implements `IExpectViewClosedCallback` they will receive a callback notification;

Each region is characterized by 2 main attributes:

* is owned by a Region Manager, an `IRegionManager` implementation;
* has a unique name in the set of regions owned by the same Region Manager;

A `RegionManager` is automatically created by the UI Composition engine as soon as a region is added to a `View`, a `RegionManager` is bound to a WPF `Window` instance.

### Nesting

Regions can be nested as preferred, a Window can contain a region that at runtime will contain another region and so on without limitations. For example the following is a valid `logical tree`:

```
Window
  -> Grid
     -> ContentPresenter
        -> IContentRegion<ContentPresenter>
          -> UserControl
            -> Grid
              -> StackPanel
                -> IElementsRegion<StackPanel>
```

In the above sample one single RegionManager will be created at runtime.

## Region Setup

### Region markup definition

First define a region in the XAML where is needed and attach it to the `UIElement` that requires injection:

```
<Window x:Class="Samples.Presentation.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:rg="http://schemas.radicalframework.com/windows/presentation/regions"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <ContentPresenter rg:RegionService.Region="{rg:ContentPresenterRegion Name=MyRegion}" />
    </Grid>
</Window>
```

**Remarks**

* The `rg` namespace declaration pointing to the Radical region namespace `http://schemas.radicalframework.com/windows/presentation/regions`;
* A region is attached to a `UIElement` via the `Region` attached property of the `RegionService` element;
* A region is declared as a markup extension whose primary role is to define the region type and the region name;

As soon as we define a region the UI Composition engine, at runtime, will create a `RegionManager` to host the region, RegionManager whose lifecycle is **bound** to the lifecycle of the hosting `Window`. If the region is defined in a `UserControl` the RegionManager lifecycle will be **bound** to the lifecycle of the `Window` hosting the UserControl.

### Region Injection

Once a region is defined in the XAML we need to inject some content, we can inject content in a region in 3 different ways: manually, using partial views or using a declarative approach.

#### Manual injection

Once a View contains a region each time the View is loaded a `ViewLoaded` message is broadcasted to notify that the View has been loaded:

```csharp
class MyViewLoadedHandler : MessageHandler<ViewLoaded>, INeedSafeSubscription
{
    public IViewResolver ViewResolver{ get; set; }
    public IConventionsHandler Conventions{ get; set; }
    public IRegionService RegionService{ get; set; }

    protected override bool OnShouldHandle( ViewLoaded message )
    {
        return message.View is Samples.Presentation.MyView;
    }

    public override void Handle( ViewLoaded message )
    {
        if ( this.RegionService.HoldsRegionManager( message.View ) )
        {
            var view = this.viewResolver.GetView<MyRegionView>();

            var region = this.RegionService.GetRegionManager( message.View )
                .GetRegion<IContentRegion>( "MyRegion" );

            region.Content = view;
        }
    }
}
```

In the above sample we are defining a message handler to handle the `ViewLoaded` message, overriding the `OnShouldHandle` method to define a rule to handle only the ViewLoaded event related to the View we are interested in.

In the `Handle` method we utilize:

* the `RegionService` to determine is the View has a `RegionManager`;
* if the View has a region manager
  * we resolve the content to inject;
  * retrieve a reference to the region manager and to the region;
  * inject the content;

Resources:

* [Radical built-in messages](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/mvvm/built-in-messages.md)
* [Runtime conventions](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/mvvm/runtime-conventions.md)

#### Automatic (aka Partial regions)

Radical UI Composition engine has a concept called `partial view`, a partial view is a `View`, and if defined its `ViewModel`, that can be automatically picked up and injected based on a set of conventions:

* Given a region, as in the previous XAML sample named `MyRegion`;
* Given a View, and an optional ViewModel, that lives in a namespace that matches `*.Presentation.Partial.*`;
* Where the last segment of the View/ViewModel namespace is the region name, in our sample MyRegion;

The View will be resolved, as usual, and injected into the expected region. Given the following namespace structure:

```
MySampleApp
  .Presentation
     .Partial
        .MyRegion
            .MySampleView.xaml
            .MySampleViewModel.cs
```

The MySampleView and it ViewModel, MySampleViewModel, will be automatically injected into the MyRegion region.

#### Declarative

The last option, to inject a `View` in a specific `region`, is to decorate the `View` class with the `InjectViewInRegionAttribute`:

```csharp
[InjectViewInRegion( Named = "MyRegion" )]
class MyUserControlView : UserControl
{

}
```

In the above sample, at runtime, the UI Composition engine will inject an instance of the `MyUserControlView` into the region named "MyRegion".

## Region implementations

As previously said Radical has 3 different region types: `IContentRegion<T>`, `IElementsRegion<T>` and `ISwitchingElementsRegion<T>`. Each region type has a default implementation.

### ContentPresenterRegion

A `ContentPresenterRegion` is a `IContentRegion<ContentPresenter>` that can be applied to a `ContentPresenter UIElement`.

### PanelRegion

A `PanelRegion` is a `IElementsRegion<Panel>`, given that a `Panel` is an abstract class, this region can be used with any `UIElement` that inherits from `Panel`, such as a `StackPanel`.

### TabControlRegion

A `TabControlRegion` is an implementation of the `ISwitchingElementsRegion<TabControl>` and can be used with a `TabControl`.


# Region content lifecycle

A `region`, as every other contet in Radical, has a lifecycle. Depending on the type of the region the lifecycle can be different, but the general approach is the following:

* View and ViewModel will be released;
* If View or ViewModel implements `IDisposable` they will be disposed;
* If View or ViewModel implements `IExpectViewClosedCallback` they will receive a callback notification;

Every region can be `Shutdown`, not explicitely, but by shutting down the `RegionManager` that manages the region. A `RegionManager` shutdown can occour, for example, at application shutdown or when the hosting `Window` is closed. At shutdown time every region managed by the shutdown `RegionManager` will be notified and the region content, in our case the `ViewModel`, has the opportunity to intercept and react to this process.

When ever is region content is removed the entire logical tree of the removed content is inspected to ensure that is it contains any other regions their lifecycle is managed as expected sutting down all the nested regions.

## IContentRegion

An `IContentRegion` notifies its own content `ViewModel`, if any, right before removing the content and once it has been removed. The content `ViewModel` has the opportunity, via the `IExpectViewClosingCallback`, to cancel the removal process and to be notified once the removal is comleted via the `IExpectViewClosedCallback`.

## IElementsRegion

An `IElementsRegion` can host multiple contents at a time, it is designed to notify the `ViewModel`, if any, of the content that will be removed right before removing it and once it has been removed. The content `ViewModel` has the opportunity, via the `IExpectViewClosingCallback`, to cancel the removal process and to be notified once the removal is completed via the `IExpectViewClosedCallback`.

## ISwitchingElementsRegion

An `ISwitchingElementsRegion` can host multiple contents at a time as the `IElementsRegion` and add the concept of an active content that can change over time. It is designed to notify the `ViewModel`, if any, of the content that will be removed right before removing it and once it has been removed. The content `ViewModel` has the opportunity, via the `IExpectViewClosingCallback`, to cancel the removal process and to be notified once the removal is completed via the `IExpectViewClosedCallback`. Other than behaving as a `IElementsRegion` the `ISwitchingElementsRegion` notifies each content `ViewModel` whenever is activated if it implements the `IExpectViewActivatedCallback`.


# TabControl region

The `TabControlRegion` is a standard `switching elements region` that implements the adapter pattern in order to allow the user to add as `content` every XAML content.

The XAML `TabControl` element expects its children to be `TabItem` this is, from the user perspective, very uncomfortable.

It is much easier to deal with a standard `DependencyObject` and expect to be able to add that object as a `TabItem`. The `TabControlRegion` allows us to achieve that.

Allowing us to add a `DependencyObject`, such as a `UserControl`, as the content of a `TabControlRegion` solves only one the issues we have when using a `TabControl`. A `TabControl` is what we call a `headered` element meaning that each `TabItem` is composed by 2 different pieces: the `TabItem` content and the `TabItem` header. The `DependencyObject` we can add as content will be used as the `TabItem` content, in order to define the `TabItem` header we can use the `RegionHeaderedElement.Header` attached property, whose content will be used by the `TabControlRegion` as the `TabItem` header, such as in the following sample:

```
<UserControl x:Class="SampleView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:rg="http://schemas.radicalframework.com/windows/presentation/regions"
             rg:RegionHeaderedElement.Header="This will be used as header">
</UserControl>
```

The header is not constrained to be a string but can be any valid XAML content.


# Create a custom region

Radical out of the box offers a limited set of regions:

* ContentPresenterRegion;
* PanelRegion;
* TabControlRegion;

Building a custom region is a simple task, the first thing is to decide which type of region we need, depending multiple factors:

* Single content vs multiple contents in a region;
* If we need multiple contents the next decision is if we need to have an active content, such as a `TabItem` in a `TabControl` or not;

## Menu and MenuItem regions

In a plugin based application is quite common to have the requirement to allow plugins to inject menus and menu items into the application main shell. The easiest way to achieve it is to build custom regions capable of hosting Menus and MenuItems. A region is bound the the XAML element where the `Region` attached property is defined. In a menu we have 2 element types the menu that hosts top level items, and menu items that can have children.

In order to host menu items in a menu via region we can simply use the following code:

```csharp
public class MenuRegion : ElementsRegion<Menu>
{
    public MenuRegion()
    {

    }

    public MenuRegion( String name )
    {
        this.Name = name;
    }

    protected override void OnAdd( DependencyObject view )
    {
        this.Element.Items.Add( ( MenuItem )view );
    }

    protected override void OnRemove( DependencyObject view, RemoveReason reason )
    {
        view.As<MenuItem>( e =>
        {
            if ( this.Element.Items.Contains( e ) )
            {
                this.Element.Items.Remove( e );
            }
        } );
    }
}
```

The important pieces are the `OnAdd` and the `OnRemove` protected methods. Since we are inheriting from a region whose element type is a `Menu` we have an`Element` property vailable that exposes to the region the XAML element the region is bound to, in the above sample the `Menu`. `OnAdd` will be called by the infrastructure whenever there is the need to add a content to the region and `OnRemove` whenever there is the need to remove a content. In the above sample we are simply adding and removing the element from the `Menu` that is hosting us. Following the same approach as above we can define a `MenuItemRegion`:

```csharp
public class MenuItemRegion : ElementsRegion<MenuItem>
{
    public MenuItemRegion()
    {

    }

    public MenuItemRegion( String name )
    {
        this.Name = name;
    }

    protected override void OnAdd( DependencyObject view )
    {
        this.Element.Items.Add( ( MenuItem )view );
    }

    protected override void OnRemove( DependencyObject view, RemoveReason reason )
    {
        view.As<MenuItem>( e =>
        {
            if ( this.Element.Items.Contains( e ) )
            {
                this.Element.Items.Remove( e );
            }
        } );
    }
}
```

that follows the exact same approach as the `MenuRegion`.

## Usage

Once a region is defined its usage is very simple:

```
<Menu rg:RegionService.Region="{crg:MenuRegion Name=MainMenuRegion}">
    <MenuItem Header="File">
        <MenuItem Header="Exit">

        </MenuItem>
    </MenuItem>
</Menu>
```

## Adapters

One important thing to underline looking at the above samples is that a region is bound to an element type but not to a content type, this is in line with the overall XAML philosophy. This means that in the region itself we can adapt the incoming content in order to host it in the best possible way. In the above samples we are expecting the incoming content to be a `MenuItem` but nothing prevents us, as the `TabControlRegion` does, to change the behavior of the region based on the incoming content type. In te above sample what we can do is accept as content every `DependencyObject` and if it is not a valid `MenuItem` wrap it n a `MenuItem` before adding it as content.


# Inversion of Control

[Radical](https://github.com/RadicalFx/radical) Presentation toolkit depends on Inversion of Control and Dependency Injection principles but does not force the end user to use any predefined IoC toolkit.

By default Radical uses the Microsoft dependency injection seam, exposed to users by the `IServiceCollection` and `IServiceProvider` interfaces.

Support for [third party containers](/release-2/concepts/ioc/third-party) is provided throught generic host support, all containers supported by the Microsoft extensions infrastructure can be used with Radical.

## Registering custom dependencies

To register custom dependencies into the IoC conatiner a dependency installer is required:

* Create a class that implements the `IDependenciesInstaller` interface. The class can be created in any assembly that is deployed in the application bin folder, the assembly scanning process will find it during the application startup pahse
* At startup the class `Install` method will be invoked and custom registrations can be performed against the provided `IServiceCollection` instance.

The following is a custom installer sample class:

```csharp
class DefaultInstaller : IDependenciesInstaller
{
   public void Install(BootstrapConventions conventions, IServiceCollection services, IEnumerable<Type> assemblyScanningResults)
   {
      services.AddSingleton<MyType>();
   }
}
```


# Third party DI containers

To enable third party containers support it is necessary to bootstrap the Radical application using the generic host support. To enable generic host support:

* Add a reference to the `Microsoft.Extensions.Hosting` nuget package
* Change the app boostrapping code as follows:

```csharp
class App
{
   public App()
   {
      var host = new HostBuilder()
         .AddRadicalApplication<Presentation.MainView>()
         .Build();

      Startup += async (s, e) => 
      {
         await host.StartAsync();
      };

      Exit += async (s, e) =>
      {
         using (host)
         {
            await host?.StopAsync();
         }
      };
   }
}
```

Using the above code sample the application boostrapping process is now delegated to the generic host. To add support for a different IoC container, for example Autofac, do the following:

* Add a reference to the `Autofac.Extensions.DependencyInjection` nuget package
* Change the `HostBuilder` creation section to add Autofac support as follows:

```csharp
var host = new HostBuilder()
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .AddRadicalApplication<Presentation.MainView>()
    .Build();
```

Refer to the documentation of you container of choice to get an overview of the steps required to integrate with the generic host. A full sample is available in the documentation repository at <https://github.com/RadicalFx/documentation/tree/master/samples/ThirdPartyContainer>


# Entities


# Property System

## Property System

WPF has a really nice feature called Dependency Property, from the user perspective a dependency property is a standard CLR property that add, on top of CRL properties, a set of really nice and powerful features:

1. Property value inheritance;
2. Property metadata;
3. Property change notification;
4. Support for default value generation;
5. *…and many others strictly related to WPF;*

The [Radical](https://github.com/RadicalFx/radical) assembly where the property system lives is totally non-related to WPF in any way, we have simply decided to bring the power of dependency-like properties in order to give some interesting boost to certain part of the Radical framework.

One really interesting thing of the dependency properties, the WPF ones, is that values and metadata are stored at the root object level, we inherited that concept in our `Entity` base abstract class; lots of Radical stuff inherit from the `Entity` base class so to obtain something really interesting:

```csharp
class MyObject : Entity
{
    public String MyProperty
    {
        get{ return this.GetPropertyValue( () => this.MyProperty ); }
        set{ this.SetPropertyValue( () => this.MyProperty, value ); }
    }
}
```

what we see here is what we call a Radical property (RP), that from the outside is viewed, and behaves, like a standard CLR property but, from the inside, is totally managed by the `Entity` base class, and in our object we only expose a property.

## Property change notification

The first thing we get using a Radical property is property change notification, the base `Entity` class implements `INotifyPropertyChanged` and automatically fires the event whenever the property really changes; really means that subsequently setting the same value more than once fires the event only the first time.

## Property Metadata

Since we have everything managed by the base class, thus the base class holds all the properties and property values we can easily introduce interesting behaviors without requiring the inheriting class to do anything special:

```csharp
class MyObject : Entity
{
    public MyObject()
    {
        var metadata = this.GetPropertyMetadata( () => this.MyProperty );
    }

    public String MyProperty
    {
        get { return this.GetPropertyValue( () => this.MyProperty ); }
        set { this.SetPropertyValue( () => this.MyProperty, value ); }
    }
}
```

We are retrieving the default property metadata for the given property, using metadata the first thing we can do is to define the property default value.

## Default Value

The property default value is requested the first time a property `get` is performed. We will use the property metadata to define the default value for a property because we do not want to trigger a `PropertyChanged` event for the simple fact of defining a default, initial value:

```csharp
public MyObject()
{
    var metadata = this.GetPropertyMetadata( () => this.MyProperty );

    metadata.DefaultValue = "this is the default value";
}
```

It's also possible to dynamically define the default value using a lambda:

```csharp
public MyObject()
{
    var metadata = this.GetPropertyMetadata( () => this.MyProperty );

    metadata.DefaultValueInterceptor = () => "this is the default value";
}
```

so to be able to perform some logic when the default value is requested. Both approaches can be used in a fluent manner:

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .WithDefaultValue( "this is the default value" );
}
```

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .WithDefaultValue( () => "this is the default value" );
}
```

## Cascade changes notifications

Another interesting feature are cascade change notifications:

```csharp
class MyObject : Entity
{
    public MyObject()
    {
        this.GetPropertyMetadata( () => this.MyProperty )
            .AddCascadeChangeNotifications( () => this.AnotherProperty );
    }

    public String MyProperty
    {
        get { return this.GetPropertyValue( () => this.MyProperty ); }
        set { this.SetPropertyValue( () => this.MyProperty, value ); }
    }

    public Int32 AnotherProperty
    {
        get { return 0 /* e.g. runtime evaluated property */; }
    }
}
```

in this sample each time `MyProperty` changes the `PropertyChanged` event is raised even for `AnotherProperty` property. The `RemoveCascadeChangeNotifications` can be used to remove a cascade change notification previously added.

## Disable change notifications

by default all the radical properties notify of their change, if we want to disable change notifications for a specific property we’ll use once again property metadata:

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .DisableChangesNotifications();
}
```

at a later time changes can be re-enabled using the `EnableChangeNotifications` method.

## Change detection

In the case we need to detect the change of a property from within the object itself we can use property metadata:

```csharp
public MyObject()
{
    this.GetPropertyMetadata( () => this.MyProperty )
        .OnChanged( pvc => 
        {
            //invoked whenever the property changes
        } );
}
```

or directly interact with the property definition:

```csharp
public String MyProperty
{
    get { return this.GetPropertyValue( () => this.MyProperty ); }
    set { this.SetPropertyValue( () => this.MyProperty, value, pvc => 
    {
        //invoked whenever the property changes
    } ); }
}
```

in both cases we get access to the current property value and to old property value.


# Messaging and Message Broker

The message broker pattern is a way to decouple the sender of a message and the subscribers of that message. In a standard event-based approach the subscriber needs in order to subscribe to an event:

1. a reference to the publisher;
2. knowledge of the event signature;

In lots of cases we need to be able to let 2 different components talk to each other in a more decoupled way since we have no easy way to satisfy the first point, in this cases introducing a third actor, the broker, that both knows is a really simple way to solve the original problem:

![Messaging diagram](/files/-LQVINy9w4fgBgei5X7Y)

Radical has its own built-in broker implementation represented by the `IMessageBroker` interface and by the default `MessageBroker` implementation found in the Radical assembly.

## Usage

The first thing we need to do is to create an instance of the broker:

```csharp
var broker = new MessageBroker(new NullDispatcher());
```

> The broker itself has a dependency on the `IDispatcher` interface, an `IDispatcher` can be seen as a wrapper of the current `SynchronizationContext`. We wrap it in a `IDispatcher` instance to avoid coupling the broker to a specific implementation.
>
> In the above sample we are using a default `NullDispatcher` that does nothing and is a good choice for console or web applications where marshaling calls in the main thread is not mandatory. Radical.Windows comes with a built-in `WpfDispatcher`.

Once we have created the broker we can share it among all the components that need it:

```csharp
var sampleSender = new SenderComponent(broker);
var sampleReceiver = new ReceiverComponent(broker);
```

The third thing we need is something to exchange between components:

```csharp
class SampleMessage
{
}
```

> [POCO messages](https://github.com/RadicalFx/documentation/tree/3593d0c5b04875dd1fb6be74908fc5cea4ac1a8d/docs/messaging/poco-messages.md) are fully supported.

NOTE: It's also important to notice that all messages are shared in memory between publishers and subscribers, which means that there won't be any serialization happening and messages don't need to be serializable.

Now that we have 2 components, a broker and something that we want to share from one component to the other we can use it in the following manner:

```csharp
class SenderComponent
{
    IMessageBroker broker;

    public SenderComponent(IMessageBroker broker)
    {
        this.broker = broker;
    }

    public void Publish()
    {
        this.broker.Broadcast(sender: this, message: new SampleMessage());
    }
}
```

and from the receiver point of view:

```csharp
class ReceiverComponent
{    
    IMessageBroker broker;

    public SenderComponent( IMessageBroker broker )
    {
        this.broker = broker;
        this.broker.Subscribe<SampleMessage>(subscriber: this, (sender, message) => 
        {
            //handle the message here.
        } );
    }
}
```

## Dispatch vs. Broadcast

In the sample above the “sender” utilizes the `Broadcast` method, broadcasted messages will be delivered to subscribers asynchronously, and in parallel, thus the subscriber is invoked on a thread that is not the same as the publisher.

If, for some reason, we need to be have events dispatched in a synchronous manner we can use the `Dispatch` method that guarantees that all the subscribers are invoked on the same thread of the publisher in a serial manner.

### Invocation Model

In our experience the most frequent usage of the broker is within the management of the UI of an application based on the MVVM pattern, which means that in most cases the subscriber of the event needs to access the UI, thus needs to run on the UI/main thread.

If we want to reduce the friction and we do not need to have control on the marshaling process we can ask the broker to automatically call the subscriber on the main thread for us:

```csharp
broker.Subscribe<SampleMessage>(this, InvocationModel.Safe, (sender, message) =>
{
    //this delegate is automatically invoked on the main thread.
});
```

Using the subscribe overload that accept an `InvocationModel` enumeration we can specify that we, as subscribers, need the subscription to be invoked on the main UI thread.

NOTE: The broadcast operation is still asynchronous and the broker only dispatches on the main thread the given delegate only when required.

## Inheritance support

One interesting thing we can do is subscribe to a base class in order to receive all the messages that inherits from the specified type:

```csharp
broker.Subscribe<IMessage>(this, (sender, msg) =>
{
    //all the messages that inherits from IMessage we'll be handled here.
});
```

In the above sample we are basically building a sort of catch all handler.




---

[Next Page](/llms-full.txt/1)

