Showing posts with label Catel. Show all posts
Showing posts with label Catel. Show all posts

Monday, August 11, 2014

What about Catel.Fody and computed read-only properties change notifications?


In my last post, I covered the implementation of INotifyPropertyChanged interface when using SheepAspect as an AOP library. In the end, I also implemented an approach to notify changes of computed read-only properties. This approach has a downside, the dependent properties discovering process must be done in run-time.

Such a journey recalls us that Catel.Fody didn’t have support for notifying property changes of computed read-only properties. How could such a thing ever be possible? Obvious, “the shoemaker's son always goes barefoot” ;). But don’t worry: the feature is here, moving the dependent properties discovering process to build-time, thanks to Fody.

As you probably know by now, Catel.Fody will rewrite all properties on the DataObjectBase and ViewModelBase. So, if a property is written like this:

public string FirstName { get; set; }

will be weaved into

public string FirstName
{
    get { return GetValue<string>(FirstNameProperty); }
    set { SetValue(FirstNameProperty, value); }
}

public static readonly PropertyData FirstNameProperty = RegisterProperty("FirstName", typeof(string));


But now we added a new feature to Catel.Fody. If a read-only computed property like this one exists:

public string FullName
{
    get { return string.Format("{0} {1}", FirstName, LastName).Trim(); }
}

the OnPropertyChanged method will be also weaved into

protected override void OnPropertyChanged(AdvancedPropertyChangedEventArgs e)
{
    base.OnPropertyChanged(e);
    if (e.PropertyName.Equals("FirstName"))
    {
        base.RaisePropertyChanged("FullName");
    }
    if (e.PropertyName.Equals("LastName"))
    {
        base.RaisePropertyChanged("FullName");
    }
}


This feature is already available in the latest beta package of Catel.Fody.

Try yourself and let us know.

Tuesday, October 22, 2013

Catel extends Prism modularity options through NuGet

Introduction


Prism provides a lot of options regarding modularity by default. Fact is that most of the stuff  you need to build a modularized application is available on Prism. Prism contains several modularity options including ways to retrieve modules from a directory, set them up through the configuration file, and even options to create modularized Silverlight applications.

On the other hand, Catel provides support for module catalog composition in order to enable more than one modularity options into a single application.

Nowadays, initiatives around NuGet come from everywhere, such as Shimmer with the same goal of ClickOnce (but works), OctopusDeploy for release promotion and application deployment or even the recently released extension manager of ReSharper 8.0.

So, the Catel team comes with a new one and the fact is that we wondered why no one told about this before: 

What if you would be able to distribute your application's modules through NuGet?

If you want to know how, take a look.


Enabling NuGet based modularity option


With the forthcoming 3.8 version of Catel you will be able to install and load modules from a NuGet repository. The only thing you have to do is:
  1. Write a module as you know with Prism (or better in combination with Catel).
  2. Create a NuGet package for the module and publish it into your favorite gallery.
  3. Use and configure the NuGetBasedModuleCatalog in the application’s bootstrapper.
The first two steps are well documented. For details see creating and publishing a package and declaring modules from NuGet and Catel documentation.


So, now we can focus on the third one.

Use and configure the NuGetBasedModuleCatalog in the application’s bootstrapper


In order to simplify the following explanation we published a package into the official NuGet Gallery named Catel.Examples.WPF.Prism.Modules.NuGetBasedModuleA. Such package contains an assembly with a single class like this one:
 
public class NuGetBasedModuleA : ModuleBase
{
    public NuGetBasedModuleA(IServiceLocator container):base("NuGetBasedModuleA", null, container)
    {
    }

    protected virtual void OnInitialized()
    {
      var messageService = this.Container.ResolveType<IMessageService>();
      messageService.Show("NuGetBasedModuleA Loaded!!");
    }
}

Let’s start writing an  application that will use this public packaged module. Indeed, the main point of interest here is about the usage and configuration of the NuGetBasedModuleCatalog. Therefore just write the bootstrapper as follow:

public class Boot : BootstrapperBase<MainWindow, NuGetBaseModuleCatalog>
{
  protected override void ConfigureModuleCatalog()
  {
    base.ConfigureModuleCatalog();
    this.ModuleCatalog.AddModule(new ModuleInfo 
          { 
               ModuleName = "NuGetBasedModuleA", 
               ModuleType = "Catel.Examples.WPF.Prism.Modules.NuGetBasedModuleA.NuGetBasedModuleA, Catel.Examples.WPF.Prism.Modules.NuGetBasedModuleA", 
               Ref = "Catel.Examples.WPF.Prism.Modules.NuGetBasedModuleA, 1.0.0-BETA", 
               InitializationMode = InitializationMode.OnDemand
          });
  }
}

Notice how the Ref property of ModuleInfo is used to specify the package id and optionally the version number. If the version number is not specified then the application always will try to download the latest version keeping the modules up to date.

Finally, to make this demo work, just put in the XAML of the main window the ModuleManagerView control, run


and click the check box.

Conclusions


Yes, we did it again. Catel keeps working alongside Prism. Now, we extended Prism’s modularity options through NuGet in order to provide a powerful mechanism of application module distribution. 

If you want to try, just get the latest beta package of Catel.Extensions.Prism and discover by yourself all scenarios that you can handle with this Catel exclusive feature.

Saturday, September 28, 2013

Keep updated CatelR# with ReSharper 8.0



CatelR# is now compatible with the latest version of ReSharper (R#).

We also keep the compatibility with the most recent R# versions including 6.0, 7.0 and 7.1. The full installer, that also includes the R# 8.0 assemblies, of the latest beta of CatelR# is available to download here.

R# 8.0 includes a NuGet based Extension Manager and the Catel Team started to publish the CatelR# extension in the Extension Gallery.

Yes, CatelR# is alive. We keep working in more features and also are waiting for your ideas. You got one? Let us know!

So, ensure yourself to install the latest version of R# and you will no miss any of the forthcoming CatelR#'s cool features.

Thursday, January 17, 2013

Cache storage explained

Introduction 

Caching is about improving applications performance. The most expensive performance costs of the applications are related to the data retrieving, typically when this data requires to be moved across the network or loaded from disk. But some data have a slow changing behavior (a.k.a nonvolatile) and don't require to be re-read with the same frequency of the volatile data.

So, to improve your application performance and handle this "nonvolatile" data from a pretty clean approach, Catel comes with a CacheStorage<TKey, TValue> class. Notice that the first generic parameter is the type of the key and the second the type of the value that will be stored, just like a Dictionary<TKey, TValue> but CacheStorage isn't it just a Dictionary. 

This class allows you to retrieve data and store it into the cache with a single statement and also helps you to handle the expiration policy if you need it.

Let’s take a look into these features:

Initializing a cache storage

To initialize a cache storage field into your class use the following code:

/*...*/
private readonly CacheStorage<string, Person> _personCache = new CacheStorageCacheStorage<string, Person>(allowNullValues: true);

Retrieve data and store it into the cache with a single statement

To retrieve data and storing into a cache with a single statement use the following code:

/*...*/
var person = _personCache.GetFromCacheOrFetch(Id, () => service.FindPersonById(Id));

When this statement is executed more than once with the same key, the value will be retrieved from the cache storage instead of from the service call (notice the usage of a lambda expression). The service call will be executed just the first time or if the item is removed from the cache manually or automatically due to the expiration policy.

Using cache expiration policies

The cache expiration policies add a removal behavior to the cache storage items. A policy signals that an item is expired to make that cache storage remove the item automatically.

A default cache expiration policy initialization code can be specified during cache storage initialization constructor:

/*...*/
private readonly CacheStorage<string, Person> _personCache = new CacheStorageCacheStorage<string, Person>(() => ExpirationPolicy.Duration(TimeSpan.FromMinutes(5)), true);

You can specify a specific expiration policy for an item when it's stored:

/*...*/
var person = _personCache.GetFromCacheOrFetch(id, () => service.GetPersonById(id), ExpirationPolicy.Duration(TimeSpan.FromMinutes(10)));

The default cache policy specified at cache storage initialization will be used if during item storing the expiration policy is not specified.

Build-in expiration policies

Catel comes with build-in expiration policies. They are listed in the following table:

Expiration policy Type Description Initialization code sample
AbsoluteExpirationPolicy Time-base The cache item will expire on the absolute expiration DateTime
ExpirationPolicy.
Absolute(new DateTime(21, 12, 2012))
DurationExpirationPolicy Time-base The cache item will expire using the duration TimeSpan to calculate the absolute expiration from DateTime.Now
ExpirationPolicy.
Duration(TimeSpan.FromMinutes(5))
SlidingExpirationPolicy Time-base The cache item will expire using the duration TimeSpan to calculate the absolute expiration from DateTime.Now, but every time the item is requested, it is expanded again with the specified TimeSpan
ExpirationPolicy.
Sliding(TimeSpan.FromMinutes(5))
CustomExpirationPolicy Custom The cache item will expire using the expire function and execute the reset action if is specified. The example shows how to create a sliding expiration policy with a custom expiration policy.
var startDateTime = DateTime.Now;
var duration = TimeSpan.FromMinutes(5);
ExpirationPolicy.
Custom(() => DateTime.Now >
startDateTime.Add(duration), 
() => startDateTime = DateTime.Now); 
CompositeExpirationPolicy Custom Combines several expiration policies into a single one. It can be configured to expire when any or all policies expire.
new CompositeExpirationPolicy().
Add(ExpirationPolicy.
Sliding(TimeSpan.FromMinutes(5))).
Add(ExpirationPolicy.
Custom(()=>...))

Implementing your own expiration cache policy

If the CustomExpirationPolicy is not enough, you can implement your own expiration policy to makes that cache item expires triggered from a custom event. You are also able to add some code to reset the expiration policy if the item is read from the cache before it expires (just like SlidingExpirationPolicy does).

To implement an expiration cache policy use the following code template:

public class MyExpirationPolicy : ExpirationCachePolicy
{
   public MyExpirationPolicy():base(true)
   {
   }

   public override bool IsExpired
   {
      get
      {
         // Add your custom expiration code to detect if the item expires
      }
   }

   public override void OnReset()
   {
      // Add your custom code to reset the policy if the item is read.
   }
}

Notice that the base constructor has a parameter to indicate if the policy can be reset. Therefore, if you call the base constructor false then the OnReset method will never be called.

Conclusion

If you are using caching in your current projects, you are probably using a different caching strategy. Now you have learned about the caching possibilities in Catel, you should definitely try it out and be amazed at the possibilities :)

Friday, November 2, 2012

More about Catel and Prism in combination

Introduction

Since Catel 3.2 the support of Prism was enhanced. The fact is that several classes were introduced into Catel.Extensions.Prism to simplify the modules and bootstrapper implementation, and thanks to dependency injection support of the ServiceLocator everything can be done with Catel without the usage of third party containers.

But  now, with 3.4, a lot of improvements were introduced and the Prism extension is working like charm.

Lets take a look to a couple of scenarios.
 

Modularity with Catel explained

Probably you actually noticed the close resemblance of the UI with the Prism's Quick Start examples (with MEF or Unity). Actually this example is an adaptation of the original sources in order to show how use the Prism features in combination with Catel.

   

Here are some implementation details:

1) Catel comes with two versions of  generic classes, named BootstrapperBase, that helps to initialize with ease the shell and the module catalog. There are several methods that you are able to override, such as ConfigureContainer or ConfigureModuleCatalog, in order to setup the IoC container (a.k.a ServiceLocator) and the module catalog respectively, just like this:

    /// <summary>
    /// Initializes Prism to start this quickstart Prism application to use Catel.
    /// </summary>
    public class QuickStartBootstrapper : BootstrapperBase<Shell, CompositeModuleCatalog>
    {
        #region Fields

        /// <summary>
        /// The callback logger.
        /// </summary>
        private readonly CallbackLogger callbackLogger = new CallbackLogger();

        #endregion

        #region Methods

        /// <summary>
        /// Configures the <see cref="IServiceLocator"/>. May be overwritten in a derived class to add specific
        /// type mappings required by the application.
        /// </summary>
        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            Container.RegisterTypeIfNotYetRegistered<IModuleTracker, ModuleTracker>();

            LogManager.AddListener(callbackLogger);

            Container.RegisterInstance<CallbackLogger>(callbackLogger);
        }

        /// <summary>
        /// Configures the <see cref="IModuleCatalog"/> used by Prism.
        /// </summary>
        protected override void ConfigureModuleCatalog()
        {
            ModuleCatalog.Add(Catel.Modules.ModuleCatalog.CreateFromXaml(new Uri("/ModularityWithCatel.Silverlight;component/ModulesCatalog.xaml", UriKind.Relative)));

            var moduleCatalog = new ModuleCatalog();
            // Module A is defined in the code.
            Type moduleAType = typeof(ModuleA.ModuleA);
            moduleCatalog.AddModule(new ModuleInfo(moduleAType.Name, moduleAType.AssemblyQualifiedName, "ModuleD"));

            // Module C is defined in the code.
            Type moduleCType = typeof(ModuleC.ModuleC);
            moduleCatalog.AddModule(new ModuleInfo { ModuleName = moduleCType.Name, ModuleType = moduleCType.AssemblyQualifiedName, InitializationMode = InitializationMode.OnDemand });

            ModuleCatalog.Add(moduleCatalog);
        }

        #endregion
    }

2) Catel also comes with the CompositeModuleCatalog class to deal with many catalog as one. The current implementation actually "allow" cross module catalog's module dependencies.

3) For a module implementation the common approach is  inherit from ModuleBase just like this:


    /// <summary>
    /// A module for the quickstart.
    /// </summary>
    public class ModuleA : ModuleBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ModuleA"/> class.
        /// </summary>
        /// </param name="moduleTracker">The module tracker.</param>        
        public ModuleA(IModuleTracker moduleTracker) : base("ModuleA", moduleTracker)
        {
        }
    }

4) The common implementation of the application class is about the instantiation of the Bootstrapper and making a call to the Run method.

var bootstrapper = new QuickStartBootstrapper();
bootstrapper.Run();

But, what will happend if you call RunWithSplashScreen instead? Try with the latest beta and discover the feature by your self or just take a look into orchesta.

Enhanced working with regions

Some time ago, I wrote about a feature where your were able to inject a view from a view model from it's view model:
 
 
	var employeeViewModel = new EmployeeViewModel();
	var uiVisualizerService = GetService<IUIVisualizerService>();
	uiVisualizerService.Activate(viewModel, "MainRegion");

1) But now you can deal with more than one shell and do this:

	uiVisualizerService.Activate(employeeViewModel, this, "MainRegion");

Where the second parameter is the parent view-model.

2) Actually you are able to inject views (referencing it's view models) in any window. Just like the previous example but in combination with the experimental extension method Show:

	var uiVisualizerService = GetService<IUIVisualizerService>();
	var windowViewModel = new WindowWithRegionViewModel();
	uiVisualizerService.Show(windowViewModel, () => { uiVisualizerService.Activate(new EmployeeViewModel(),  windowViewModel, "WindowMainRegion") });

Conclusions

1) The usage of third party Prism Extensions like MEF or Unity is no longer required. Catel Service Locator support dependency injection and is actually configured to work just as Prism expect, the fact is that the ServiceLocatorAdapter do this job.
 
2) Now, you are able to have a nice programming session with Prism & Catel.

Thursday, August 23, 2012

Creating a view model with a model and mappings with CatelR#

There are tons of yarns based on MVVM developer’s experiences behind Catel framework. Some of them are well documented on Catel docs and one of my favorites is the named "Creating a view model with a model and mappings".

When I started to read it I identified myself as one of those developers that map all the view model properties back to the model.

I will remember you how it started:

"During the use of the MVVM pattern, we noticed that lots and lots of developers have a model, and map the values of the model to all properties of the view model. When the UI closes, the developers map all the properties back to the model. All this redundant code is not necessary when using the view models of Catel." More...

This only feature makes that my interest about Catel grown until I became one of the members of the development team. But this is part of the other history.

Let’s go back to the Catel feature again. If you don’t remember how it works, here is a summary.

Basically if you want to create a model the only thing that you have to do is decorate a view model property with the ModelAttribute. So if you want to expose the model property as view model one, and don’t write the mapping back code you must decorate the exposed property with the ViewModelToModelAttribute just like this:

    /// 
    /// The person view model.
    /// 
    public class PersonViewModel : ViewModelBase
    {
        #region Static Fields

        /// Register the FirstName property so it is known in the class.
        public static readonly PropertyData FirstNameProperty = RegisterProperty("FirstName", typeof(string));

        /// Register the Person property so it is known in the class.
        public static readonly PropertyData PersonProperty = RegisterProperty("Person", typeof(Person));

        #endregion

        #region Public Properties

        /// 
        /// Gets or sets the first name.
        /// 
        [ViewModelToModel("Person")]
        public string FirstName
        {
            get { return GetValue<string>(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }

        /// 
        /// Gets or sets the person.
        /// 
        [Model]
        public Person Person
        {
            get { return GetValue<Person>(PersonProperty); }
            set { SetValue(PersonProperty, value); }
        }

        #endregion
    }
 
This example will automatically create a mapping between Person.FirstName and PersonViewModel.FirstName.

This feature is amazing and Catel distributes some code snippets to accelerate writing such code:
  • vm - declare a view model
  • vmpropmodel - declare a property as model on a view model
  • vmpropviewmodeltomodel - declare a property as a pass-through property on a view model

But could you imagine to yourself writing this code (and more) as fast as is possible (near to the speed of light). Don't you believe me?

Watch the movie, and believe me, it is in slow motion ;)


This is a forthcoming feature of CateR#, now powered by Catel itself.

You got more ideas? Let us know!

Tuesday, August 14, 2012

When use the "View Model First" approach?

Introduction

I have been waiting for Catel 3.2 to write about some features, especially about the all new modularity stuff (a.k.a. the Prism extension) and how it works in the second part of "Catel creates a perfect combination with Prism". But, always there is an excuse, we are still working on some Prism features and improvements, therefore the second part will have to wait.

So, this post will be about an interesting approach and how transform "untestable" code, from the code-behind, as "testable" view model code. The name is "View Model First". I will try to illustrate it transforming a "View First" implementation into a "View Model First" one.

The problem

"Digesting" the sample codes of Telerik components (WPF/SL) I noticed that some of them, as part of its name, contain the tag "MVVM". The fact is that most of these components have MVVM support but several examples of this suite are written in code-behind. I know it is a demo application but some of the Telerik components are actually written to be used in code-behind, therefore some logic that could be easy to test becomes hard to test.


Let's take a look into the "Tree to Grid Drag" drag and drop example. I will remove some part of the code for simplification.

public partial class Example : System.Windows.Controls.UserControl
{
  public Example()
  {
    // Allow dropping into the ListBox and GridView only if the
    // dragged items are all products:
    RadDragAndDropManager.AddDropQueryHandler(wishlistView, OnDropQuery); 
    RadDragAndDropManager.AddDropQueryHandler(orderView, OnDropQuery); 

    // Change the drag cue and choose an action for the sucessful drop
    // in the Wishlist:
    RadDragAndDropManager.AddDropInfoHandler(wishlistView, OnWishlistDropInfo);

    // Change the drag cue and choose an action for the sucessful drop
    // in the Order GridView:
    RadDragAndDropManager.AddDropInfoHandler(orderView, OnGridViewDropInfo);

    // Allow dragging of the Wishlist and Order items:
    RadDragAndDropManager.AddDragQueryHandler(wishlistView, OnWishListDragQuery);
    RadDragAndDropManager.AddDragQueryHandler(orderView, OnOrderDragQuery);

    // Handle the case when items are dragged away from  the ListBox
    // and the Order:
    RadDragAndDropManager.AddDragInfoHandler(wishlistView, OnWishListDragInfo); 
    RadDragAndDropManager.AddDragInfoHandler(orderView, OnOrderDragInfo);
  }
}

You should notice that everything is about the RadDragAndDropManager. This static class needs a control reference to setup the drag and drop stuff.  This operation forces us to write code that could be part of the VM code on the code-behind. At least the highlighted code could be part of the logic of the view model of Example control removing the access to the list of elements via ListBox control reference.

private void OnWishlistDropInfo(object sender, DragDropEventArgs e)
{
  System.Windows.Controls.ItemsControl wishlist = e.Options.Destination as System.Windows.Controls.ItemsControl;
  ICollection draggedItems = e.Options.Payload as ICollection;

  // Get the drag cu that the TreeView or we have created
  TreeViewDragCue cue = e.Options.DragCue as TreeViewDragCue;

  if (e.Options.Status == DragStatus.DropPossible)
  {
    // Set a suitable text:
    cue.DragActionContent = String.Format("Add {0} item{1} to Wishlist", draggedItems.Count, draggedItems.Count > 1 ? "s" : String.Empty);
    cue.IsDropPossible = true;
    wishlist.Background = this.Resources["DropPossibleBackground"] as Brush;
  }
  else if (e.Options.Status == DragStatus.DropImpossible)
  {
    cue.DragActionContent = null;
    cue.IsDropPossible = false;
  }
  else if (e.Options.Status == DragStatus.DropComplete)
  {
    IList items = wishlist.ItemsSource as IList;
    foreach (object draggedItem in draggedItems)
    {
      items.Add(draggedItem);
    }
  }

  if (e.Options.Status != DragStatus.DropPossible)
  {
    wishlist.Background = new SolidColorBrush(Colors.White);
  }
}


So how to transform the code above into MVVM "compatible" code? That is the problem that I will try to solve in this post.


The solution

The approach to solve this problem is quite simple and has a name "View Model First". The only thing we have to do is visualize the solution from the view model point of view.

The very first steps to re-write the drag and drop example with view model support is to install the Catel.MVVM nuget package, at least for me ;).

Using the Catel naming conventions the Example control will be renamed as ExampleView (now it inherits from Catel.Windows.Controls.UserControl)  and  the ExampleViewModel will be introduced (inheriting from Catel.MVVM.ViewModelBase).

I will also rename the ProductViewModel and CategoryViewModel as Product and Category and now inherits from DataObjectBase. They are actually model classes instead view model ones.

The ExampleViewModel class looks like this:

public class ExampleViewModel : ViewModelBase
{
  public static readonly PropertyData OrdersProperty = RegisterProperty("Orders", typeof(ObservableCollection<Product>));

  public static readonly PropertyData SelectedOrdersProperty = RegisterProperty("SelectedOrders", typeof(ObservableCollection<Product>));

  public static readonly PropertyData SelectedWishesProperty = RegisterProperty("SelectedWishes", typeof(ObservableCollection<Product>));

  public static readonly PropertyData WishesProperty = RegisterProperty("Wishes", typeof(ObservableCollection<Product>));

  public ObservableCollection<Product> Wishes
  {
    get  { return this.GetValue<ObservableCollection<Product>>(WishesProperty); }
    set {  this.SetValue(WishesProperty, value); }
  }

  public ObservableCollection<Product> SelectedWishes
  {
    get  { return this.GetValue<ObservableCollection<Product>>(SelectedWishesProperty); }
    set {  this.SetValue(SelectedWishesProperty, value); }
  }

  public ObservableCollection<Product> Orders
  {
    get  { return this.GetValue<ObservableCollection<Product>>(OrdersProperty); }
    set {  this.SetValue(OrdersProperty, value); }
  }

  public ObservableCollection<Product> SelectedOrders
  {
    get  { return this.GetValue<ObservableCollection<Product>>(SelectedOrdersProperty); }
    set {  this.SetValue(SelectedOrders, value); }
  }
}


With this transformation we are able to attach or bind the ItemsSource property of  the wishlistView (ListBox) and orderView (RadGridView) to Wishes and Orders view model properties respectively. I will also add some logic to fill the SelectedWishes and SelectedOrders properties with an event to command approach to be synchronized with the selected elements on the UI.

At this point I will introduce a service named IDragAndDropService, in order to "map" a property of the view model with a control that have it attached to the ItemsSource property. The interface of this service will be defined as follow:

public interface IDragAndDropService
{
  void AddDragInfoHandler(IViewModel viewModel, Expression<Func<IList>> propertyExpression, EventHandler<DragDropEventArgs> eventHandler, string dependencyPropertyName = "ItemsSourceProperty");

  void AddDragQueryHandler(IViewModel viewModel, Expression<Func<IList>> propertyExpression, EventHandler<DragDropQueryEventArgs> eventHandler, string dependencyPropertyName = "ItemsSourceProperty");

  void AddDropInfoHandler(IViewModel viewModel, Expression<Func<IList>> propertyExpression, EventHandler<DragDropEventArgs> eventHandler, string dependencyPropertyName = "ItemsSourceProperty");

  void AddDropQueryHandler(IViewModel viewModel, Expression<Func<IList>> propertyExpression, EventHandler<DragDropQueryEventArgs> eventHandler, string dependencyPropertyName = "ItemsSourceProperty");
} 


The code above was the first thing that came to my mind with the more pure style of the Catel developers ;)

Now during the initialization of the example view model we can use it, resolving it instance from the ServiceLocator, to setup the drag and drop operations.

protected override void Initialize()
{
  var dragAndDropService = this.GetService<IDragAndDropService>();
 
  // Allow dropping into the Wishlist and Order only if the dragged items are all products:
  dragAndDropService.AddDropQueryHandler(this, () => this.Wishes, this.OnDropQuery);
  dragAndDropService.AddDropQueryHandler(this, () => this.Orders, this.OnDropQuery);
 
  // Choose an action for the sucessful drop in the Wishlist via Wishes property:
  dragAndDropService.AddDropInfoHandler(this, () => this.Wishes, this.OnWishesDropInfo);
 
  // Choose an action for the sucessful drop in the Order GridView via Orders property:
  dragAndDropService.AddDropInfoHandler(this, () => this.Orders, this.OnOrdersDropInfo);
 
  // Allow dragging of the Wishlist and Order items:
  dragAndDropService.AddDragQueryHandler(this, () => this.Wishes, this.OnWishesDragQuery);
  dragAndDropService.AddDragQueryHandler(this, () => this.Orders, this.OnOrdersDragQuery);
 
  // Handle the case when items are dragged away from  the Wishlist and the Order:
  dragAndDropService.AddDragInfoHandler(this, () => this.Wishes, this.OnWishesDragInfo);
  dragAndDropService.AddDragInfoHandler(this, () => this.Orders, this.OnOrdersDragInfo);
}


Then we are able to move some code from code-behind to our view model just like this:

private void OnWishesDragQuery(object sender, DragDropQueryEventArgs e)
{
  List<ProductModel> productModels = this.SelectedWishes.ToList();
  e.QueryResult = productModels.Count > 0;
  if ((bool)e.QueryResult)
  {
    e.Options.Payload = productModels;
  }
}

private void OnWishesDragInfo(object sender, DragDropEventArgs e)
{
  if (e.Options.Status == DragStatus.DragComplete)
  {
    IEnumerable<ProductModel> productModels = (e.Options.Payload as IEnumerable).Cast<ProductModel>();
    foreach (ProductModel draggedItem in productModels)
    {
      this.Wishes.Remove(draggedItem);
      this.SelectedWishes.Remove(draggedItem);
    }
  }
}

private void OnOrdersDropInfo(object sender, DragDropEventArgs e)
{
  if (e.Options.Status == DragStatus.DropComplete)
  {
    IEnumerable<ProductModel> productModels = (e.Options.Payload as IEnumerable).Cast<ProductModel>();
    foreach (ProductModel draggedItem in productModels)
    {
      this.Orders.Add(draggedItem);
    }
  }
}


The code that we moved from the code-behind is quite ease to test using any mock library, mocking the IDragAndDropService interface.

But we have to implement the RadDragAndDropService to make the UI controls works as we expected.

Implementing the RadDragAndDropService

The only issue here is about get the active view(s) from the view model instance. Here is where Catel 3.3 comes to save us with the introduction of the ViewManager. The logic inside the MVVM logic of Catel carries with the auto-registration of the control and its association with its view models. So the only thing that we have to do is get the active view(s) using the GetViewsOfViewModel method and lookup the first control.

Basically the search is a wide search through the visual tree a returns the first one dependency object that commits the condition (the dependencyProperty is attached to the view model property) and call the RadDragAndDropManager as usual, just like this:

public void AddDragInfoHandler(IViewModel viewModel, Expression<Func<IList>> propertyExpression, EventHandler<DragDropEventArgs> eventHandler, string dependencyPropertyName = "ItemsSourceProperty")
{
  Argument.IsNotNull("viewModel", viewModel);
  Argument.IsNotNull("propertyExpression", propertyExpression);
  Argument.IsNotNull("eventHandler", eventHandler);
  Argument.IsNotNullOrWhitespace("dependencyPropertyName", dependencyPropertyName);
  Argument.IsOfType("propertyExpression.Body", propertyExpression.Body, typeof(MemberExpression));

  var memberExpression = (MemberExpression)propertyExpression.Body;
  if (memberExpression.Member.MemberType != MemberTypes.Property)
  {
    throw new ArgumentException(MemberExpressionShouldBeAPropertyErrorMessage);
  }

  IView[] activeViews = this.ServiceLocator.ResolveType<IViewManager>().GetViewsOfViewModel(viewModel);
  foreach (IView activeView in activeViews)
  {
    DependencyObject dependencyObject = FindChildDependencyObjectAttachedToProperty(activeView, propertyExpression, dependencyPropertyName);
    RadDragAndDropManager.AddDragInfoHandler(dependencyObject, eventHandler);
  }
}


The highlighted code shows you the usage of the ViewManager and the RadDragAndDropManager.

To review the details of the implementation grab the code sample here.

Conclusions

1) There is "always" a way to re-write a "View First" approach as "View Model First" one. Sometimes could be hard but is a win-win situation when you invest time to write custom services because you will gain testability and control of your code. So use the "View Model First" as much as you can.

2) Now with the Catel ViewManager is almost possible write any services that allow you to "interact" with "untestable" components without referencing it directly from your view model code.

3) An update of  Prism extension of Catel using the ViewManager will come as soon as possible, planned for Catel 3.4.

4) Writing about code testability remembered me that I have to start to write about my experience using NCover 4, but this will part of my next blog post, I think, at least for now ;).

Monday, May 14, 2012

Catel creates a perfect combination with PRISM

Introduction


I have been very "busy" watching the final of the baseball season. The past week, my team was eliminated on quarterfinals, so now I have  time to write.

Talking about competitions, I just remembered the history about how Catel.Extensions.Prism was born.

You may think that Catel and PRISM are competitors. The fact is that most people think that they are competitors. Actually I had the same idea when I discovered Catel, some time after I have been written LoB systems with PRISM. If you read the highlights, is not hard to notice the "isolated" features, mainly if you are looking for guidance or a stating point for the MVVM pattern implementation.

Catel has an out of the box view model base implementation, plus services, with full support for validation, property change notification and commanding. From my point of view Catel beats PRISM as MVVM pattern implementation guidance, with a cleaner approach on separation of views and view models and better testability. The fact is that PRISM has no a ViewModelBase implementation.

So, at some point, I considered removing all the PRISM references from my projects. But then I would loose many PRISM features, that allow you manage the modularity and view composition, that are hard to leave behind when you actually used it. I heard some people talking about the PRISM approach saying that it is a bit complex or strange. They provide example terms like bootstrapper, shell, module catalog, modules, region manager, etc. But the truth is that PRISM provides a good scaffold for modular application development.

That was the moment when we thought that they should be work together and that was the reason for we wrote Catel.Extensions.Prism and it is now available via NuGet.

User Interface Composition with Catel.Extensions.Prism


Starting with Catel 3.1 the Prism extension is available. PRISM includes a feature named "User Interface Composition". Basically it allows building a mosaic like application by loading multiple views that comes from different modules into an active region exposed by a control, also know as the shell.



The PRISM UI composition approach requires that you reference the view or the view type in order to associate it with one region. That is correct if you are coding a module class for instance, but all this is about view models.

In order to understand the code samples you need to read more about UIVisualizerService, and the way it can resolve a view from an instance of a view model. Now you are able to create a composite user interface without actually referencing any view from a view model class.

Making the region manager available

First of all, you must make available the region manager on the instance of ServiceLocator (IoC container of Catel). A PRISM based application uses MEF or Unity as primary IoC container. Therefore, you must synchronize this container with the Catel one, overriding the ConfigureContainer method of the application bootstrapper class, using the following code:

protected override void ConfigureContainer()
{
 base.ConfigureContainer();
 if (ServiceLocator.Instance.IsExternalContainerSupported(this.Container))
 {
  ServiceLocator.Instance.RegisterExternalContainer(this.Container);
 }
}

Activating a view into a specific region

To activate a view into a specific region from inside a view model, use the following code:
 var viewModel = new EmployeeViewModel();
 var uiVisualizerService = GetService<IUIVisualizerService>();
 uiVisualizerService.Activate(viewModel, "MainRegion");

Deactivating a view

To deactivate a view, use the following code:
uiVisualizerService.Deactivate(viewModel);

If you keep your view model alive (see: Keeping view models alive), you can reactivate a deactivated the view using Activate method without specify the region name. 

Deactivating a view automatically

If you close the view model using SaveAndCloseViewModel or CancelAndCloseViewModel or CloseViewModel methods, the view that belongs to this view model will be automatically deactivated from the region where it was activated.

Conclusions   

Nowadays, I enjoy write applications with Catel and PRISM, or with PRISM and Catel, the order doesn't matter. I will just give you one advice, try out this extension and like a host of a popular TV show that I know say, "draw your own conclusions by yourself" ;)

Wednesday, April 25, 2012

Accelerating Catel coding workflow with CatelR#

Overview


The  first release  of ReSharper  (R#)  provoked a  commotion, at  least between my programming  fellowships. Expressions like  "Visual Studio is a great development  tool, but with ReSharper is  awesome" were commonly repeated.

The main reason  of R# success was that the JetBrains team identified a weak point of the Visual Studio coding editor.

Visual Studio, at least in it's firsts versions (.NET versions, 2003, 2005), had no refactoring features,  just like other Java IDEs already had, such as Eclipse or IntelliJ. Also note that  the last two versions of Visual  Studio  improved it's refactoring  features but nothing come close with the power of the R#.

But I will not to talk about R# history, actually the preceding paragraph could be not totally accurate.  I don't  really know how R# was born. (If you know it, don't doubt, just comment it here, allow me to be in the know)

R# as coding workflow guidance


The R#  quick fix  and/or context  action is  very simple  and powerful workflow.  Basically  you can  locate  the  caret  position near  to  an element that  you want to alter, press  Alt + Enter,  and all available suggestions will be displayed. For instance, if you  press Alt + Enter in a  range  corresponding  to  a  "public" modifier  of  a  property,  the suggestions  "To internal", "To  protected" or "To private" would be available, only the options that do not provoke a broken usage are displayed.
 
 {caret}public string FirstName { get; set; }

But all  scenarios are not covered by R#,  there are tons of frameworks and/or toolkit that have it own coding workflows.

Catel coding workflow


If  you are  writing  a WPF  or Silverlight  application  and don't  use Catel, it is  probably that you are not using the right library. See the comparison sheet, for detailed libraries comparison.

But Catel has a "down side". If you want to convert a simple class into a data  or model class in order to  support property changed  notifications and validations, you need re-coding a class like this one:

public class Person
{
 public string FirstName { get; set; }

 public string MiddleName { get; set; }

 public string LastName { get; set; }
}

into this one:

public class Person
{
 public static readonly PropertyData FirstNameProperty = RegisterProperty("FirstName", typeof(string));
 
 public static readonly PropertyData LastNameProperty = RegisterProperty("LastName", typeof(string));
 
 public static readonly PropertyData MiddleNameProperty = RegisterProperty("MiddleName", typeof(string));
 
 public string FirstName
 {
            get { return  this.GetValue<string>(FirstNameProperty); }
            set { this.SetValue(FirstNameProperty, value);  }
 }
 
 public string LastName
 {
            get { return this.GetValue<string>LastNameProperty); }
            set { this.SetValue(LastNameProperty, value); }
 }
 
 public string MiddleName
 {
            get { return this.GetValue<string>(MiddleNameProperty); }
            set { this.SetValue(MiddleNameProperty, value); }
 }
}

As you could be noticed, there is an implementation pattern that should be fully automated. In fact, every Catel version comes with a code snippets package that assist you to write down this class from scratch.

But now, Catel team comes with a new tool. Using the R# SDK, we implement a R# extension that cover the Catel coding workflow and we named CatelR# (obviously).

Now you can do this




You can also do it faster with the R# generation options (Alt + Ins)



The   beta  version,  of CatelR#,  is  released. You can read more about CatelR# and download the beta. We are expecting for your feedback and new features request.

Enjoy it, and have nice coding experience with CatelR#.

X-ray StoneAssemblies.MassAuth with NDepend

Introduction A long time ago, I wrote this post  Why should you start using NDepend?  which I consider as the best post I have ever...