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=0.0.0.0, 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

Update

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.EnableWatermark="True"
Behaviors:WatermarkTextBoxBehavior.Label="Label"
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" />
</Style>

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 :)

Problem

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.

Solution

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),
typeof(TOwner).GetPropertyType(property),
typeof(TOwner));
}
}

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 :).

Problem

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()
{
}

[Import("MefService3")]
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()
{
}
}

[Export(typeof(IMefService))]
[PartCreationPolicy(CreationPolicy.Shared)]
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
[ImportingConstructor]
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();
unity.RegisterInstance<IUnityContainer>(unity);

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

// Register unity components
unity.RegisterType<CoreComponent>();
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.

Limitations

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 :)

Conclusion

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

Update
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!