Tuesday, November 24, 2009

MEF Contrib for Silverlight 3 (Unofficial)

I’m happy to announce that I’ve completed porting the most recent MEF Contrib (0.7) project to SL3. The project has also been updated to use the most recent MEF release which is beta 2 (Preview 8) as of this writing. All the unit tests from the project pass in the SL environment, here are the screenshots:

image image image

Before I dig into the changes I had to make in order to make it work on SL3, I will focus on NUnit for SL.

As all of you probably know, it is possible to run NUnit tests in SL environment. Microsoft has released a library called Microsoft.Silverlight.Testing which enables developers to execute tests on SL’s CLR. This library ships out of the box with the implementation of MS Tests. However, its extensibility allows to write custom providers for other testing frameworks. Jeff Wilcox wrote a post about running NUnit tests in the SL environment here. He did two things: ported a subset of NUnit to SL, and wrote a provider which enables running NUnit tests using Microsoft.Silverlight.Testing framework. However, his NUnit implementation is very limited, so I googled a little and found a guy who ported NUnit 2.5.1 to SL (you can find his post here). So, for the testing purposes I used mentioned NUnit 2.5.1 SL port together with a provider developed by Jeff. I must admit here, that I’m not sure whether all the features from NU 2.5.1 work correctly in the SL environment. Hopefully, it seems that all the Assert methods including Assert.That and Throws work as expected.

As far as MEFContrib project is concerted, I didn’t have to introduce many modifications. MefContrib.Extensions.Generic project runs without any changes. MefContrib.Integration.Unity project didn’t need to be changed in terms of its implementation. However, all stubs used in unit tests were declared as internal, and it seems MEF for SL has some troubles while instantiating non public members (or SL policy doesn’t allow this?) so most tests were failing. Fortunately, changing access to public repaired everything :) The story is a bit different for the MefContrib.Models.Provider project. This project adds to MEF custom provider model with three programming models built on top of it. These three programming models are

  • Attributed – as it name suggest, parts are registered using attributes,
  • Configurable – parts get registered via App.config,
  • Fluent – parts are registered through method invocation.

The problem lays in the Configurable programming model, because it is implemented using System.Configuration namespace, which is not available to SL programmers. Thus, MefContrib.SIlverlight does not support this model.

The last trouble I had was with two test, which reside in MemberInfoServicesTests test fixture, namely

  • GetMemberInfoShouldReturnMemberIfMemberNameIsSupplied,
  • GetMemberInfoShouldReturnTypeIfMemberNameNotIsSupplied.

Both unit tests test MemberInfoServices class. Both were throwing an exception telling that the test assembly (MefContrib.Models.Provider.Tests) cannot be loaded or the assembly has already been loaded but the versions doesn’t match. To cut the long story short, it turned out that the following code was the root cause (code like the presented below is executed in MemberInfoServices.GetMemberInfo method in both tests) :

Type.GetType("MefContrib.Models.Provider.Tests.FakePropertyPart, MefContrib.Models.Provider.Testsl", false, true)
Don’t know why this doesn’t work. However, a simple modification like follows did the job :)

Type.GetType("MefContrib.Models.Provider.Tests.FakePropertyPart, MefContrib.Models.Provider.Tests, Version=, Culture=neutral, PublicKeyToken=null", false, true)
To maintain separate versions of both tests for regular CLR and SL, I used SILVERLIGHT compiler flag.

Please note that this version is an unofficial release, not available through codeplex.com site. However, I will put an effort to make this an official release or make next MefContrib release based on this one.

Full source code is available on my code gallery here.

Saturday, November 21, 2009

Watermark effect for WPF’s TextBox and ComboBox controls


I have updated this sample to contain the watermark effect for the ComboBox control too. Its implementation is almost identical to the TextBox’s one. Here are the screens showing the effect being applied to the ComboBox control:

image image

And here comes the original post.

In this post I’m going to show a nice watermark effect for WPF’s TextBox control. Sample application (link to the sources at the end of this post) looks as follows:

image image

As you can see, non focused text box containing no text, displays a useful clue to the user informing what kind of information should be entered. Focusing a textbox immediately removes that clue.

There are probably as many ways to introduce such a behavior as there are developers all over the world :) However, one particular solution is to be considered in this case. The above effect has been achieved using adorners. The adorner used for the effect contains a single TextBlock with optional style applied to it. A good introduction to adorners is available here.

The effect has been implemented using attached behavior pattern, so no inheritance was introduced.

Using the behavior is a piece of cake. Here’s how to apply the behavior to a TextBox control:

<TextBox Height="25" Margin="0,5,0,5"
Behaviors:WatermarkTextBoxBehavior.LabelStyle="{StaticResource watermarkLabelStyle2}" />

The first property, EnableWatermark, as its name suggests, enables the effect ;) The Label property holds the text to be displayed as a watermark. Finally, the LabelStyle property contains the style to be applied to the label. And the style, defined in Window’s Resources collection, might look as follows:

<Style x:Key="watermarkLabelStyle">
<Setter Property="TextBlock.Foreground" Value="{x:Static SystemColors.ControlDarkBrush}" />
<Setter Property="FrameworkElement.Opacity" Value="0.8" />
<Setter Property="TextBlock.FontSize" Value="12" />
<Setter Property="TextBlock.FontStyle" Value="Italic" />
<Setter Property="TextBlock.Margin" Value="8,4,4,4" />

I’m not going to discuss any implementation details here since the adorner itself is trivial, and the behavior is quite easy as well. Maybe I will tell you that the watermark is displayed when the TextBox fires its Loaded event. Why is that important to know? Keep reading… ;P Besides, skim the code and you immediately know how stuff works :)

Finally, one thing, which deserves to give attention to, is control loading and the adorner layer (adorner layer is a place always rendered over the control where all adorners for that control get displayed). When a control is contained within a portion of UI that is being displayed, but the control itself is not visible, it normally fires Loaded event, but because it is not visible, it has no adorner layer! So don’t assume that call to AdornerLayer.GetAdornerLayer(Visual) always returns the adorner layer! This is why the sample shown above contains a TabControl – the second tab, named Tab 2, contains a TextBox with the watermark effect applied to it, and this still works :)

As always, code sample is available through my Code Gallery here.

Saturday, August 22, 2009

Improved MEF + Unity Integration Layer

In my last post about Managed Extensibility Framework and Unity DI container I proposed a solution to make both frameworks work together in tandem, which in turn lets the developer leverage all the features from them at the same time. Now, the improved version is out, and it's a part of the MEFContrib project!

Having learned from developing the previous version, I decided to reimplement the integration layer from the ground up. The API changed very little, though ;)

The "biggest" change since the initial version is that you no longer need to provide boolean parameter during component registration in Unity to say that you want the component to be available to MEF. Now, this is done automatically using Unity container extension. So, the initialization of the layer now is super easy as it requires only single line of code :) Consider this:

// Setup
var unityContainer = new UnityContainer();
var aggregateCatalog = new AggregateCatalog();

// Register catalog and types
unityContainer.RegisterCatalog(aggregateCatalog); // this call initializes the layer
unityContainer.RegisterType<IUnityOnlyComponent, UnityOnlyComponent1>();

The first call to RegisterCatalog method does the initialization - under the hoods, ComposiotionContainer is created, and a link between it and Unity is established. Pretty easy, huh ? :)

Next, all the types are public, so for example, if the standard RegisterCatalog method doesn't fit your needs, you can easily create your own using all the provided types as building blocks. The one concrete use case that comes to my mind is that the current implementation of the RegisterCatalog method does not allow you to attach any additional export providers (your own root CompositionContainer for instance) to the underlying CompositionContainer. In such a case, you can easily create separate method which accepts export providers and initializes the layer. Investigating RegisterCatalog method might be beneficial :)

One neat implication of having all types public is that you can now establish one-way synchronization, being MEF to Unity, in which Unity container knows about MEF parts and can resolve them, and Unity to MEF, in which MEF can pull Unity's components.

Finally, I've added support for closed generics, i.e. you can pull components from Unity and MEF using generics.

The usage of this layer is quite well described on MEFContrib wiki page.

kick it on DotNetKicks.com

Friday, July 10, 2009

Statically Typed Dependency Properties

Recently, I found a nice post written by a friend of mine, regarding statically typed property names. His post can be found here. What I simply did was to put his concept into WPF world :)


Typical registration of a WPF's dependency property looks like follows:

public int MyInteger1
get { return (int)GetValue(MyInteger1Property); }
set { SetValue(MyInteger1Property, value); }

public static readonly DependencyProperty MyInteger1Property =
DependencyProperty.Register("MyInteger1", typeof(int), typeof(Window1));

Hmm, what's wrong with it ? It "breakes" the DRY (Don't Repeat Yourself) principle. Given code defines a property named MyInteger of type int, but this information is coded twice, in the property itself and during its registration. If you want to change the name or type of a single property, you have to update the code in two places.


Now consider the following code:

public int MyInteger2
get { return (int)GetValue(MyInteger2Property); }
set { SetValue(MyInteger2Property, value); }

public static readonly DependencyProperty MyInteger2Property =
DependencyPropertyHelper.Register<Window1>(t => t.MyInteger2);

What has changed here is the way the property is registered. Now, changing the name or the type of a property is done through its getter. Nice, isn't it ? This approach works with both regular and read only properties but does not with attached properties, because the latter does not use property to access its value but uses methods instead. Implementation behind the Register<TOwner> method used above is fairly simple and looks like this:

public static class DependencyPropertyHelper
public static DependencyProperty Register<TOwner>(
Expression<Func<TOwner, object>> property)
return DependencyProperty.Register(typeof(TOwner).GetPropertyName(property),

GetPropertyName and GetPropertyType methods come from the post I've mention at the beginning.

Full code can be downloaded from my code gallery.

Wednesday, June 10, 2009

WPF 3.5 (70-502) Exam Passed

Yesterday, I've successfully completed my first developer's certification by passing exam 70-502 TS: Microsoft .NET Framework 3.5 – Windows Presentation Foundation Application Development. My score was 921 out of 1000 which is also my personal best so far :)
I had 51 question, most of which were single choice, and 150 minutes to complete. Not all the questions were taken into account when computing the final score. Although I've chosen my questions in C#, I got one question in VB, so be prepared ;)

What can you expect from the exam as far as questions are concerned? Putting it simple, everything. Questions cover all the WPF' topics including WPF 3D, ClickOnce deployment, XPS and Flow documents, and Windows Forms interoperability.

As far as WPF 3D is concerned, the questions are rather easy and cover only the basics like cameras or meshes. If you are a novice, I recommend a brief reading about this subject (not because this appears on the exam, but because WPF 3D is a big fun). ClickOnce was heavily covered on the exam, so make sure you get your hands dirty playing with it. Besides basic knowledge, you should know how to download parts of the application on demand (parts which are not required for the application to run). Regarding flow documents, you should know what annotations are, how to manage them, display, persist, etc. Printing both flow and XPS documents is also covered on the exam, so brush up on this subject as well.

In my last words, I want to speak a little about books :) Generally, if you're already familiar with WPF, official Training Kit from MS is mostly sufficient, but it doesn't cover WPF 3D, and some subjects are touched rather briefly. But if you are at the very beginning, or if you simply want to broader you knowledge, I highly recommend picking up Adam Nathan's WPF Unleashed. Actually, if You are serious about WPF development, this book is a must read :)

Wish You good luck!

Sunday, May 24, 2009

Unity + MEF Integration Layer

In this post, I’m going to discuss two of probable many solutions to the problem of making use of the Managed Extensibility Framework together with Microsoft’s Unity Application Block in an enterprise application. Presented solution combines the power of both frameworks, and exposes an intuitive and easy to use interface. If you are interested in putting MEF together with Unity, this post is definitely 4U. If you use Unity and want to get some basic knowledge about writing extension to it, you still might want to go briefly through the code, as the provided solution is based on the Unity Container Extensions (and MEF extensions as well). This post also assumes that you have a basic idea of Dependency Injection and how it relates to the design of an application. Basics of MEF will be helpful as well.
Divagations presented here are partially based on a great post titled Hosting MEF Extensions in an IoC Container by Nicholas Blumhardt, and I recommend you take a look at it before further reading this post :).


People around are sometimes/often confused about the role MEF plays in the world of the Dependency Injection – should MEF be treated as an Injection of Control solution, and thus should supersede it, or it is something else and should be used differently? Well, this is a little bit tricky question, but in what I understand, MEF is all about composition and robust components loading, thus is best suited for providing well-known extension (plug-ins) to the application, whereas IoC serves more as a backbone of an application, which is primary responsible for making all application’s internal modules work together. To sum up, MEF and Unity are very flexible and in many cases may be used interchangeably, but a general idea is that:
  • if you want to provide a plug-ins infrastructure so that 3rd parties were able to provide extensions for the app, use MEF (or Managed Add-in Framework + MEF if you want robust plug-in isolation :)),
  • if you want to structure your application’s architecture, use modules that are decoupled but with the ability to communicate, etc., use Unity or any existing IoC.
Solution 1

The first solution is pretty easy – simply use both frameworks independently of each other.

The definite plus of this approach is its ease of putting it into action in the application. But it has some drawbacks, mainly that MEF and Unity components can’t make use of each other. In other words, MEF component cannot contain any dependencies on Unity components that can be automatically satisfied via dependency injection. The same holds true for the Unity components, they simply cannot have dependencies on MEF components (note that by MEF component I mean component initially instantiated by MEF, and by Unity component I mean a component initially created by Unity container). Another drawback is that unity does know nothing about MEF, and vice versa. And why is that important ? Consider the following sample showing a dummy Presentation Model in presenter first approach (a typical scenario):

public class MyViewPresentationModel
public MyViewPresentationModel(IMyView view, IUnityService1 service1,
IMefComponent1 mefComponent1)
Note that in the constructor, I have both Unity service and MEF component, and because the MyViewPresentationModel class is instantiated via Unity and Unity knows nothing about IMefComponent1, this won’t work. But it should! Argh...

Although this solution is fairly simple to implement, it has several drawbacks that makes using it painful. So let’s go to the second :)

Solution 2

This solution uses a middle component, Unity + MEF Integration Layer (implemented as Unity.Integration.Mef.dll), which allows full interoperability between Unity and MEF, as you can see from the following figure.

As you can see, Unity is the backbone component, that uses the integration layer to communicate with MEF. In this solution, Unity components may have dependencies on MEF components, and vice versa. Of course, all dependencies will by injected automatically! So the following code will work (ICoreService is a Unity service whereas IMefService is instantiated by MEF):

public class CoreService2 : ICoreService
public CoreService2()

private IMefService m_MefService3;

public void Foo()
What's even more important, with this approach, it's possible to mix components in the constructors, so the following both classes will work as well. Please note, that if you have a MEF component exported by name, you can reference it using the Unity's DependencyAttribute, and if you have a Unity component registered using a name, you can reference it in a MEF component using MEF's ImportAttribute ! :)

public class CoreComponent : (...)
private readonly IMefService m_MefService3;
private readonly ICoreService m_CoreService;

// Interesting thing happens here: Unity injects components created
// by both MEF and Unity
public CoreComponent(
[Dependency("MefService3")] IMefService mefService3,
ICoreService coreService)
m_MefService3 = mefService3;
m_CoreService = coreService;

[Import(AllowDefault = true)]
private IEnumerable<imefservice> m_MefServices;

public void FooBar()

public class MefService2 : IMefService
private readonly IUnityContainer m_UnityContainer;
private readonly ICoreService m_CoreService;

// Interesting thing happens here: MEF injects components created
// by both MEF and Unity
public MefService2(IUnityContainer unityContainer,
[Import("CoreService2")] ICoreService coreService)
m_UnityContainer = unityContainer;
m_CoreService = coreService;

public void Bar()
Using the Unity + MEF Integration Layer is very simple, just reference Unity.Integration.Mef.dll in your project and you're almost done! Here's a sample:

// Create the Unity container and self-register
var unity = new UnityContainer();

// Register MEF catalogs in Unity
unity.RegisterCatalog(new AssemblyCatalog(Assembly.GetEntryAssembly()));
unity.RegisterCatalog(new DirectoryCatalog("."));

// Register unity components
unity.RegisterType<ICoreService, CoreService1>(new ContainerControlledLifetimeManager(), true);
unity.RegisterType<ICoreService, CoreService2>("CoreService2", new ContainerControlledLifetimeManager(), true);

The public interface is defined using extension methods on the IUnityContainer interface. There are two thing you have to do. Firstly, register all the MEF's catalogs in the Unity. Secondly, register the types in the Unity as you normally do. Note, however, that in order to make a type registered in the Unity container available to MEF, you must register it with an overloaded Register(Type|Instance) method that accepts a boolean as the last parameter. If it is true, registered type/instance will be available to MEF.
Sometimes you will want to suppress MEF injections into Unity created instances. Why? Because it costs you a CPU cycles (believe me, lots of them!). This is where PartNotComposableAttribute attribute comes in. Just mark a class with it, and when an instance from the Unity is returned, no MEF's imports will be satisfied, conserving CPU time. This is particularly useful for presenters.


For now, MEF components can have Unity dependencies resolved only via constructor injection, so method injection on MEF components currently won't work.

Implementation details

The implementation is rather straightforward. It uses two Unity extensions and one custom MEF ExportProvider. As stated before, public interface is delivered as a set of extension methods on the IUnityContainer interface. I've also considered deriving directly from UnityContainer class, but the former approach (the one I've chosen) appears better suited for me. What do You think ? You can leave a comment on that :)


The idea of bringing the power of both frameworks is very tempting. And provided solution, although definitely not the only one, seems like a good one. The code + tests (NUnit 2.5) + demo app is available on my code gallery. Hope you like it!

kick it on DotNetKicks.com

I've reimplemented most of the layer from the ground up, now it's a part of the MEFContrib project. Please see my post about it here.

Tuesday, May 5, 2009

Mammoth Pattern Miner 2009 April CTP Showcase

As promised in my last post about Mammoth some time ago, here's a four minute video presenting Mammoth in action. The video was made by co-author of Mammoth, my friend Arkadiusz Świerczek, and was presented on Europoltech 2009 conference in Warsaw. The video is soundless and is in polish, but if you're not polish, you can still get the idea of what Mammoth is all about :)

Just to let you know (if you already don't), Mammoth is a data mining and visualization solution that can discover frequent and user defined patterns in various sets of data. The program is easily extensible, so adding new algorithms, visualizations, etc., is a piece of cake.

We plan to release public, free version by the end of august 2009.

Since the last CTP, we have slightly updated technologies that are behind Mammoth. So besides .NET 3.5 SP1, WPF, Prism 2.0, Unity 1.2, Enterprise Library 4.1 and SQL Server 2005, we are using Managed Extensibility Framework Preview 5 which is labeled as a stable release.

As far as MEF is concerned, we've developed custom, simple yet robust Unity + MEF integration layer. As far as I can say for now, our MEF + Unity integration layer works flawlesly and provides combined power of both frameworks. If you are curious how we did it, check it out on my SVN Code Gallery. I will also write a separate post entirely devoted to MEF + Unity integration related stuff.

Meanwhile, enjoy the vid!

Monday, April 6, 2009

Parallel Coordinates in WPF - Part 1

A few days ago I have completed working on a first version of a parallel coordinates chart, that has been incorporated into Mammoth Pattern Miner 2009 (see my post about it). Before rolling out my own implementation, I went through the internet trying to find any implementation with the attached source code. As a result, I found a nice post here, but without the sources. Thus, I have developed a nice looking, styleable (via custom control templates) parallel coordinates chart myself :) And despite the fact that I did it under my "company" time, my boss and I decided that it would be great if I posted the sources as well. So I did! :) This is how the diagram looks like:

Overall look and feel of the demo application

This is a first post about PC chart. It covers all the functionality the chart contains, and info about using it from the code. Next posts in this series will cover the chart internals.

Feature List

1. Lines highlighting / selecting and tooltips

1. Axes labels and range labels, helper axis

2. Diagram manipulation
Anytime you resize the window or manipulate the axes, you can fit the diagram to the current view. Simply right click anywhere on the diagram and choose "Fit To Screen" command as shown below.

Besides, you can interact with the diagram using two tools: Select and Grab. If you pick the Select Tool (default), you can select/deselect lines, rotate/swap/move/scale axes. And if you pick the Grab Tool, you can move the diagram. Bear in mind that anytime you manipulate the diagram, you can execute the "Fit To Screen" command to return to the optimal view.

3. Axis scaling / Points Moving

When your mouse is over any axis, you can move the points on it simply by clicking LMB and moving the mouse up and down or you can scale it using the mouse wheel. When the mouse cursor isn't over any axis, using the mouse wheel will scale all the axes. You can scale/move the helper axis as well :)

4. Axis rotating
Axis rotating simply reverses the axis direction. To rotate the axis, move the mouse cursor over it and click the button that will appear at the bottom of the highlighted axis.

5. Axis swapping
You can swap two axes by dragging the source axis (with left CTRL button pressed) and dropping it on the destination axis. After this, the source and the destination axes will swap their placements (see the picture below).

Using the PC chart

Using the chart is very straightforward. First, you need to add the Chart control. This is done in XAML like so:

<Charts:Chart DataSource="{Binding DataSource}" />

Now, you have to prepare the data. Suppose you want to visualize a collection of the following class.

public class DemoInfo
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public double V { get; set; }
public double K { get; set; }
public double M { get; set; }
public int Tag { get; set; }
All you have to do is: grab the data, create an appropriate data source, add property to axis mapping, name the labels, and that's it!

public void DataBind()
IList<DemoInfo> infos = new List<DemoInfo>();

// Generate random data
for (int i = 0; i < ObjectsCount; i++)
var x = new DemoInfo();
x.X = m_Random.NextDouble() * 400 - 100;
x.Y = m_Random.NextDouble() * 500 - 100;
x.Z = m_Random.NextDouble() * 600 - 300;
x.V = m_Random.NextDouble() * 800 - 100;
x.K = 1.0;
x.M = i;
x.Tag = i + 1;


// Create the data source and apply mappings
var dataSource = new MultiDimensionalDataSource<DemoInfo>(infos, 6);
dataSource.MapDimension(0, info => info.X);
dataSource.MapDimension(1, info => info.Y);
dataSource.MapDimension(2, info => info.Z);
dataSource.MapDimension(3, info => info.V);
dataSource.MapDimension(4, info => info.K);
dataSource.MapDimension(5, info => info.M);

// Name the labels
dataSource.Labels[0] = "X";
dataSource.Labels[1] = "Y";
dataSource.Labels[2] = "Z";
dataSource.Labels[3] = "V";
dataSource.Labels[4] = "K";
dataSource.Labels[5] = "M";
dataSource.HelperAxisLabel = "Helper axis";

myChart.DataSource = dataSource;
Full source code is available here. Note that I use M-V-VM approach :)
Hope you like it!

Sunday, March 15, 2009

Exam 70-536 passed :)

Three days ago (being more specific, on Friday 13th ;) ) I've passed my first Microsoft developer's exam, 70-536 TS: Microsoft .NET Framework - Application Development Foundation, scoring 876 points out of 1000. In short, I had 40 question and 135 minutes. As far as questions are concerned, there were many about serialization (rather not very straightforward), interoperability and globalization. No questions about mailing functionality. The questions ranged from very simple to quite though. Most of them were single choice questions, I got maybe three or four multiple choice ones.

Some say this is an easy exam. Well, I wouldn't say so, because the exam covers almost every .NET basic subject. In order to pass, you need to have solid theoretical background, but at the same time you need to get you hands dirty by playing with some code samples too. I recommend examining the official Training Kit (now there's 2nd edition, the first one was quite buggy so don't rely only on that book). Skimming MSDN seems like a good idea too ;) However, there's no better source of knowledge than the developer's head and experience. Most of the questions I answered because of my experience and not because of the books!

Next, I'm going for the exam 70-502: Microsoft® .NET Framework 3.5—Windows® Presentation Foundation. Good luck with your own certifications!

Tuesday, February 24, 2009

Lack of AttachNewRegion method in Prism 2.0

Today I have switched to Composite WPF and Silverlight 2.0 (known as Prism 2.0) in one of my current projects. The transition was quite smooth (I used a guide which I found here), although I found one issue - the IRegionManager interface does not contain the AttachNewRegion method :( This made me very unhappy because I used this method in the implementation of a IMenuService which is responsible for managing the main menu control within my application by exposing a friendly interface to all modules. After small source code investigation I realized that indeed there's no sign of the mentioned method. After reading interesting post here, I decided to write one myself, which was a trivial task ;) Here's the code:

using System;
using System.Windows;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;

namespace Mammoth.Presentation.Infrastructure.Common
public static class RegionManagerExtensions
public static void AttachNewRegion(this IRegionManager regionManager, object regionTarget, string regionName)
if (regionManager.Regions.ContainsRegionWithName(regionName))
throw new ArgumentException("Region already exists.", regionName);

RegionManager.SetRegionManager((DependencyObject) regionTarget, regionManager);
RegionManager.SetRegionName((DependencyObject) regionTarget, regionName);

As you can see, this is a very simple extension method that extends the IRegionManger interface. Inside, I simply set the region manager and the region name on the desired UI element.

This solution is very simple, still it works fine (at least for me). If you have any troubles with it, let me know.

Wednesday, February 18, 2009

WPF Wizard Control - Part II

In my previous post about rolling your own WPF wizard control, I've described how one can easily create simple, styleable wizard in WPF. Generally, I blogged that the wizard consists of two things, namely
  • Wizard class - representing the wizard with its buttons (Next, Previous, Finish, etc.) and simple behavior concerned around managing which wizard page should be displayed,
  • WizardPage class - representing a container for a single wizard page.
The first class inherited from the Control class whereas the second inherited from the ContentControl class. Because the Wizard class wasn't derived from any control that can have content, it had to have a bindable collection of wizard's pages. Thus, I brought WizardPagesCollection class into play, which was defined as follows:

    2     /// 
    3     /// Wizard pages collection.
    4     /// 
    5     public class WizardPagesCollection : ObservableCollection<WizardPage>
    6     {
    8     }

Besides the collection of pages, the Wizard had two properties, namely
  • ActivePageIndex - the index of the current page in the collection being displayed,
  • ActivePage - the active page itself.
Of course, both properties depends on each other, i.e. if ActivePageIndex changes, ActivePage has to be updated accordingly. This was done using dependency property callbacks. Moreover, I used coerce callbacks to validate the values.
After coding this solution I realized there's a problem with it - the only wizard page that is the part of the wizard's logical tree is the page being displayed! This meant that DataContext property wasn't set correctly, and binding to controls across wizard pages was not possible.

A better Solution

Fortunately, it is very easy to overcome these problems, even without modifying wizard's template! My first assumption about wizard's base class was mistaken, because wizard is indeed a control that should have a content - its own pages :) And because there can be more than one page, the choice is obvious - ItemsControl.

Inheriting from ItemsControl reduced the following code from the Wizard class:

    2 private WizardPagesCollection m_WizardPages;
    4 /// 
    5 /// Returns a collection of wizard's pages.
    6 /// 
    7 public WizardPagesCollection WizardPages
    8 {
    9     get { return m_WizardPages; }
   10     set
   11     {
   12         m_WizardPages = value;
   13         m_WizardPages.CollectionChanged += OnWizardPagesChanged;
   14     }
   15 }
   17 private void OnWizardPagesChanged(object sender, NotifyCollectionChangedEventArgs e)
   18 {
   19     // This code glues all wizard's pages to wizard's DataContext.
   20     // This is done due to the fact that when pages are switched, the
   21     // page that is hidden looses its data context.
   22     foreach (var page in WizardPages)
   23     {
   24         var binding = new Binding("DataContext") { Source = this };
   25         BindingOperations.SetBinding(page, DataContextProperty, binding);
   26     }
   27 }

This was actually the ugly code that attached the value of Wizard's DataContext property to each wizard's page DataContext which eliminated the problem no. 1. And because now wizard contains all the pages within its Items collection (which can be databound via ItemsSource property), all pages appear in the wizard's logical tree. Thus, problems described earlier in this post no more exist :)

Because now I used ItemsControl, I could virtually put anything in the wizard and it will compile. But the wizard expects to contain instances of WizardPage class, so I needed to tell the wizard that it need to wrap any content that is not a WizardPage into an instance of WizardPage. This is done using the following code:

    1 protected override DependencyObject GetContainerForItemOverride()
    2 {
    3     return new WizardPage();
    4 }
    6 protected override bool IsItemItsOwnContainerOverride(object item)
    7 {
    8     return item is WizardPage;
    9 }

Note, however, that in this solution, both ActivePageIndex and ActivePage properties still play vital role. Also note that there is not a single change in the Wizard's template, which is very simple. The one problem with it is that it defines the "view" for the wizard and for the wizard's page. This will be fixed in the third release :)

I will blog about better approach to implementing custom WPF wizard which fixes the complexity of using the two mentioned properties and uses separate templates for the wizard and its pages in my next post, so stay tuned ;)

The code for this post can be downloaded from here. Note that it actually contains three Wizard's implementations. The one described in this post is contained within WpfWizard2 project. WpfWizard3 will be subject of my next post.

Tuesday, January 27, 2009

Hide a window instead of closing it in WPF

Hiding a window instead of closing it is especially useful when the window is a singleton. This is a typical situation for "options" windows which store application settings. Balaji Ramesh proposed solution to this problem, which can be found here.

    2 // Handle closing event to hide window instead of closing it
    3 Closing += delegate(object sender, CancelEventArgs e)
    4 {
    5     e.Cancel = true;
    7     Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, 
    8         (DispatcherOperationCallback)(arg =>
    9     {
   10         Hide();
   11         return null;
   12     }), null);
   13 };

As you can see, the code is extremely simple. Everything it does is to subscribe to Window's Closing event (which is not a routed one), suppress the close action and invoke Window's Hide() method in the UI thread to actually hide the window. We could augment this code with Hiding and Hidden routed events to inform interested entities the window is hiding and when the window is hidden. Using Hiding event it's very easy to cancel window hiding as well.

But what would you do if you had dozens of windows which you would hide instead of close? Typing this code into every window constructor is by no means an option. The neat solution (at least in my opinion) is to implement this functionality as an Attached Behavior.

    1 public static readonly DependencyProperty HideInsteadCloseProperty =
    2     DependencyProperty.RegisterAttached("HideInsteadClose", 
    3     typeof(bool), typeof(WindowBehavior), new FrameworkPropertyMetadata(
    4         new PropertyChangedCallback(OnHideInsteadClose)));
    7 private static void OnHideInsteadClose(DependencyObject d,
    8     DependencyPropertyChangedEventArgs e)
    9 {
   10     var window = d as Window;
   11     if (window != null)
   12     {
   13         if ((bool)e.NewValue)
   14         {
   15             // Handle closing event to hide window instead of closing it
   16             window.Closing += delegate(object sender, CancelEventArgs args)
   17             {
   18                 args.Cancel = true;
   20                 window.Dispatcher.BeginInvoke(DispatcherPriority.Background, 
   21                     (DispatcherOperationCallback)delegate
   22                 {
   23                     var cancelArgs = new CancelRoutedEventArgs(HidingEvent, window);
   24                     window.RaiseEvent(cancelArgs);
   26                     if (!cancelArgs.Cancel)
   27                     {
   28                         window.Hide();
   29                         window.RaiseEvent(new RoutedEventArgs(HiddenEvent, window)); 
   30                     }
   32                     return null;
   33                 }, null);
   34             };
   35         }
   36     }
   37 }

The core concept behind the above implementation is to subscribe to the Window's Close event inside HideInsteadClose attached property's change callback. Besides, we can implement Hiding and Hidden attached routed events. (this has been omitted for clarity). Using this code is as simple as adding appropriate code as Window's attribute in XAML as follows:

Common:WindowBehavior.HideInsteadClose="True" Common:WindowBehavior.Hidden="HiddenHandler"

The code is available for download from my Code Gallery here.

Monday, January 19, 2009

Mammoth Pattern Miner - cool WPF application from AGH Department of Computer Science

I'm very excited to announce that a few days ago my university's Department of Computer Science has released the first version of Mammoth Pattern Miner 2009 (MPM), an application I'm currently actively developing (not alone of course :) ). The MPM is a data mining application that is able to analyze large amount of data and discover frequent sets and sequences, partial frequent sets and some user defined patterns. It uses some well known data mining algorithms as well as some custom implementations. Of course, it provides rich visualization capabilities, many filters and extensible application architecture (by the way, which application is not extensible nowadays :P ).

Here are some screen shots from the current release (click image to enlarge it). I'll try to post a video showing the system in action when I have a little free time.

Main view

Visualization and undocked Project Explorer (yes, every window is dockable)

Yet another visualization, tree this time :)

Mammoth Pattern Miner begun as an application that accompanied my master's thesis which has been developed during my stay at UTBM in France in 2008. After I graduated, I was given the opportunity to continue working on this project at my university. To cut the long story short, I simply accepted it.

Now, Mammoth is a mature software product which provides quite big functionality. Nevertheless, there's still much work to do ;)

Just in case you are curious, Mammoth uses Microsoft's .NET Framework 3.5 SP1, WPF and SQL Server 2005. It runs pretty fast on my Lenovo T61p laptop. However, big data sets require lots of ram.

Mammoth official site, for now available in polish only, is located at http://caribou.iisg.agh.edu.pl/proj/mammoth/. If you think you or your work might benefit from using this software, please email me.

Hope you liked it!