Another .NET Blog

To content | To menu | To search

Friday 25 March 2011

[CaliburnMicro] Embedded MessageBox

In this article, I'll show you how to use Caliburn Micro to create embedded message boxes. I will use the default implementation you can obtain in CM's big brother source code, and tweak it a little to have a better look.

Continue reading...

Monday 21 February 2011

[CaliburnMicro] Dependencies attribute on any depth level of properties

I didn't post anything on the blog for a very long time (2010-12-07), so let's break the silence with something new about Caliburn Micro.

In this post, I will briefly show you an update of an "old" article I wrote. The main drawback of the previous version of this dependencies attribute was its inability to make the availability of the action depend on more than one level.

For example, you could write these dependencies, which update the availability of the Do method when either OtherProperty (a property of the same view-model than Do) or OtherProperty.ChildProperty were modified.

[Dependencies("OtherProperty", "OtherProperty.ChildProperty")]
public IEnumerable<IResult> Do()
{

}

With the new Dependencies attribute I'll show you right after the break, you won't be limited to this single level of hierarchy, thus allowing you to write a dependency like:

[Dependencies("OtherProperty.ChildProperty.OneMoreLevelProperty.LastLevelProperty.*")]
public IEnumerable<IResult> Do()
{

}

Continue reading...

Tuesday 7 December 2010

[PostSharp] Ease the creation of configuration sections - Update

In the previous article, we saw how to use PostSharp to help us to use the configuration sections, with the use of two aspects. In this article, I will focus on the same objective. But this time, we will use only one aspect, which will be a mix of the two aspects of the last article.

Continue reading...

Wednesday 1 December 2010

[PostSharp] Ease the creation of configuration sections

In this article, I'll show yet another use of PostSharp, this time focusing on the ConfigurationSection class. If you look in the MSDN at the articles which explain how to use the ConfigurationSection, you may have noticed that the code you need to write is repetitive, tedious, and error-prone:

public class PageAppearanceSection : ConfigurationSection
{
	[ConfigurationProperty("remoteOnly", DefaultValue = "false", IsRequired = false)]
	public Boolean RemoteOnly
	{
		get { return (Boolean)this["remoteOnly"]; }
		set	{ this["remoteOnly"] = value; }
	}

	[ConfigurationProperty("font")]
	public FontElement Font
	{
		get	{ return (FontElement)this["font"]; }
		set	{ this["font"] = value; }
	}

	[ConfigurationProperty("color")]
	public ColorElement Color
	{
		get	{ return (ColorElement)this["color"]; }
		set	{ this["color"] = value; }
	}
}

As you can see, you have to put the ConfigurationPropertyAttribute on top of each property, and to make calls to an indexer to the Get and Set methods of the properties, using the same name you used in the attribute.

Doesn't this repetition look like to be a good candidate for an aspect?

Continue reading...

Thursday 18 November 2010

[PostSharp] [Caliburn] Automatic IEventPublisher subscription and publication

If you develop in WPF using the MVVM pattern, you have certainly heard about the Event Aggregator pattern, which allows, as the MSDN says:

decoupling of publishers and subscribers so they can evolve independently.

There are several implementations of this pattern:

Of course, as the title of this article told you, we are going to use the latter, and I will propose an implementation of a PostSharp aspect which will help us to subscribe to events, publish them, and dispose the subscriptions when the view-model is deactivated.

Continue reading...

Tuesday 19 October 2010

Server Migration

A small post to warn you that the site may be unavailable a few moment, because I'm currently migrating it on another server.

I hope the transition will be smooth, and won't take too much time.

See you later! (I hope...)

Edit: The migration seems to have been successfully completed. All should be working now :)

Monday 4 October 2010

[Caliburn Micro] Action filters - Dependencies on "properties of properties", using the Reactive Extensions

By default, Caliburn Micro (CM) doesn't contain the action filters which belong to Caliburn (C). There is a recipe on how to implement them back in CM, but unfortunately it doesn't cover all the initial functionalities which are in C.

One feature missing, and that I needed, is the possibility to depend on "properties of properties".

With the recipe, you can add a dependency between the property of a view-model (VM) and another property of this same VM. Thus, when the latter property is changed, the PropertyChanged event of the VM is fired, resulting in the update of the availability of the action on which the Dependencies attribute is put. But what it doesn't allow you to do, is to define something like:

[Dependencies("OtherProperty.ChildProperty")]

This would update the availability of the action if OtherProperty implements INotifyPropertyChanged and if the ChildProperty is modified. You could even use something like:

[Dependencies("OtherProperty.*")]

which would update the availability if any of the properties of OtherProperty is modified.

But let me show you how I implemented this feature on top of the recipe, with the great use of the Reactive Extensions.

Continue reading...

Friday 1 October 2010

[PostSharp] Don't NotifyPropertyChanged all properties

This article will show you another improvement which can be made to the DataBinding sample aspect found on SharpCrafters, after the Fire INotifyPropertyChanged.OnPropertyChanged for read-only properties depending on other properties article.

By default, the aspect will fire the PropertyChanged event each time any property is changed. But what if you don't want some of them to fire the event? Or what if, as it happened to me, you set the value of a property, and must do some work in the property setter, even if the new value of the property is the same as the old one?

The latter example is a bit odd, but in the default implementation of the aspect, in the OnPropertySet method, you have this code:

if ( args.Value == args.GetCurrentValue() ) return;

args.ProceedSetValue();

If the new value of the property is the same, the aspect will return, and then never call the args.ProceedSetValue(); method, which will avoid your code to be called in the property setter.

In this short article, I'll show you how to change the aspect, to call the OnPropertyChanged event on all properties, excepted those which are marked with a custom attribute.

Continue reading...

Thursday 30 September 2010

[Caliburn Micro] How to use the same view for multiple view-models

The default behavior of Caliburn Micro (CM), when it must locate a view from a view-model, is very straightforward: it takes the full name of the view-model, replaces the word "Model" by an empty string, and locates a view with this new name.

One problem with this way is that you must exactly have one view per view-model. So, if you have an abstract view-model, with multiple derived view-models, which only set some filters on the displayed data, you must have one view per derived VM. Which is kind of annoying, useless, and error prone.

In this short article, I'll show you how to easily implement a new feature which will allow us to specify, with an attribute on top of the VM, the view we want CM to display when we activate the VM.

Continue reading...

Thursday 23 September 2010

English twitter account

As I speak in french on my current twitter account, and because I choosed to write my blog posts in english, I decided to create a new twitter account which would be in english too, and where I would talk almost exclusively about programming, .Net, and the related technologies revolving around it. I hope this will help to ease the creation of interesting discussions with more people.

So here it is.

I hope to see you there !

Wednesday 1 September 2010

[PostSharp] Fire INotifyPropertyChanged.OnPropertyChanged for read-only properties depending on other properties

One problem of the INotifyPropertyChanged aspect concerns automatic notification of read-only properties which depend on other properties.

Indeed, say you have this class, on which the aspect is applied:

[NotifyPropertyChanged]
public class Test
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName { get { return FirstName + " " + LastName; } }
}

If you change the values of FirstName or LastName, the OnPropertyChanged event will be fired, and the view will be able to display the new values of the properties. But if a control of your view is bound to the FullName property, it won't be updated. A solution would be to declare FullName as an automatic property, and update it in the setters of FirstName and LastName. Not very practical.

In this article, I will show you how to extend the aspect, in order to make it fire the event for dependent properties when a "parent" property is modified.

Continue reading...

Monday 23 August 2010

[Ninject] Use one database session per view-model

One very useful web page I've read before beginning to code on my new project was this one: Data Access - Building a Desktop To-Do Application with NHibernate, from the well-known Ayende. In this article, among other hints and best-practices, he says, at the end of the Managing Sessions chapter:

The recommended practice for desktop applications is to use a session per form, so that each form in the application has its own session. Each form usually represents a distinct piece of work that the user would like to perform, so matching session lifetime to the form lifetime works quite well in practice. The added benefit is that you no longer have a problem with memory leaks, because when you close a form in the application, you also dispose of the session. This would make all the entities that were loaded by the session eligible for reclamation by the garbage collector (GC).

There are additional reasons for preferring a single session per form. You can take advantage of NHibernate’s change tracking, so it will flush all changes to the database when you commit the transaction. It also creates an isolation barrier between the different forms, so you can commit changes to a single entity without worrying about changes to other entities that are shown on other forms.

While this style of managing the session lifetime is described as a session per form, in practice you usually manage the session per presenter.

We'll see now how to implement this behavior, with Caliburn as the MVVM client framework, and Ninject as the dependency injector.

Continue reading...

Wednesday 4 August 2010

[PostSharp] How to virtualize all the methods of a class

When using NHibernate, it is recommended to declare the public and protected properties and methods of your entities as virtual, to be able to use them with proxies.

But missing a virtual keyword for a member of a POCO is easily forgettable, and unfortunately, you will only be warned of your mistake on runtime, when your mappings are being built.

In this article, I will show you how to 'not care' anymore about that, and let PostSharp do this stuff for us.

Continue reading...

Sunday 1 August 2010

End of holidays, and articles to come...

I'm back from 2 weeks of holidays, which partly explains why there wasn't a lot of articles recently.

Now that I'm full of energy, I will have more time to write some new stuff here on this blog. I have a few ideas of the topics I will address, but my next two articles should rely on:

  • PostSharp, and an aspect to virtualize all the methods of a class (to be used on POCO classes, so they can be used with NHibernate)
  • Ninject, and a solution to use one NHibernate session per View-Model in a WPF application, as recommended by Ayende Rahien here.

After these 2 articles, I don't know yet what I will write about. This is going to be the surprise...

See you soon!

Thursday 15 July 2010

[PostSharp] [FluentValidation] Automatic entity validation with IDataErrorInfo

This post is an english translation of this french post.

One way to manage data validation when using WPF is to implement the interface IDataErrorInfo on the classes to validate, and to modify the XAML file so that WPF automatically uses the functions of this interface to validate the value of the properties (See here for an example).

The problem with this, is that you have to alter your entities to add some logic inside them, which makes them become more than entities. One way to avoid that is provided by FluentValidation, which allows you to deport the validation logic outside of your entities, inside another class, where you can define some validation rules for your entity.

But as we always want our entities to continue to implement IDataErrorInfo, we have to operate a mix with FluentValidation. You can find a way to achieve that in this thread.

This thread was the starting point of the solution I'm going to propose to you, to fix this problematic in an easy way...

Continue reading...

[PostSharp] [Caliburn] - Automatically call NotifyOfPropertyChange on the view models

Here, I won't explain what are Caliburn and PostSharp. Their respective documentations, examples and samples already do that very well. But I will show you how to create an aspect which will be applied by PostSharp on the view models of a WPF assembly.

And as a result, on runtime, each time a public property will be changed, the event PropertyChanged of the interface INotifyPropertyChanged will be fired, and the WPF view will be able to refresh its state.

If you already know PostSharp, or have been on their website, you have certainly noticed that they already propose an aspect which intends to implement the interface INotifyPropertyChanged, and to call PropertyChanged when the value of a property is changed.

And if you already know Caliburn, you know that the classes you must inherit from to implement your view models inherit themselves from an abstract class named PropertyChangedBase, which implements INotifyPropertyChanged, and which proposes a function named NotifyOfPropertyChange, to which you give as a parameter the name of the modified property.

The aspect I'm going to show you will allow us to mix these 2 methods.

Continue reading...

Wednesday 14 July 2010

[MSBuild] How to reference an assembly specific to the OS architecture

This article is an english translation of this one.

This article is designed for those who, like me, must deal with 2 versions of a same assembly, depending on you have to work on a 32 or 64 bits OS.

In my case, the faulted assembly is System.Data.SQLite.dll, which allows to use SQLite databases under the .Net framework. Therefore, this assembly exists in 2 flavors: 32 and 64 bits. The problems began to arise when I started to build some unit tests to check the behaviour of my repositories. At the beginning, I was developing on 32 bits PC, referencing the 32 bits assembly, and all was fine. But since then, I work as well on a 32 bits PC as on a 64 bits one, and I always have to delete the reference to the assembly, and replace it with a reference to the assembly with the same bitness as the architecture on which the tests are runned.

Not so great...

But that time is now revolved! And if you encounter the same problem, know that a solution does exist. And here it is...

Continue reading...

Dernier post... en français !

Eh oui ! Cela fait un moment déjà que l'idée me trotte dans la tête, et je prends enfin cette grande décision: écrire dorénavant tous les articles en anglais.

Ecrire un blog technique sur la programmation, en français, est en soit une bien belle chose. Mais je commençais ces derniers temps à souffrir un peu de ne pas avoir plus de feedback sur ce que j'écris, plus de commentaires. De ne pas pouvoir éventuellement engager des discussions sur les sujets que j'aborde.

Peut-être que le passage à la langue de Shakespeare ne changera rien du tout à cet état de fait. Mais ouvrir ainsi l'audience du site au plus grand nombre devrait quand même, je l'espère, apporter un flux de visiteurs plus conséquent, et donc une probabilité plus importante d'augmenter le nombre d'interactions.

Tous les articles qui ont été écrit jusqu'à maintenant resteront en place, et continueront donc d'être accessibles en français. Mais certains d'entre eux feront en plus l'objet d'une traduction en anglais. Je vais essayer de m'imposer le rythme d'une traduction d'un ancien article à chaque fois que je publie un nouvel article en anglais.

En revanche, les noms des catégories et les tags seront tous traduits, car ce serait improductif d'avoir des doublons à ce niveau là.

Je vous dis donc non pas à bientôt, mais see you soon !

Friday 2 July 2010

[MSBuild] Comment référencer l'assembly spécifique à l'architecture de la plateforme

Cet article est destiné à ceux qui, comme moi, doivent jongler entre 2 versions d'une même assembly, selon que vous travailliez sur un poste en 32 bits ou en 64 bits. Dans mon cas, le fichier incriminé est System.Data.SQLite.dll, qui permet d'utiliser des bases de données sous SQLite, depuis le framework .NET. Cette assembly existe donc, vous l'aurez compris, en 2 exemplaires: 32 et 64 bits.

Les soucis ont commencé à arriver pour moi lorsque j'ai commencé à mettre en place mes tests unitaires pour tester le comportement de mes repositories. Car au début du développement, j'étais sur un PC 32bits, avec la DLL 32bits référencée, et tout allait bien. Mais, je me suis mis à travailler aussi bien sur une machine 32 bits que sur une machine en 64 bits, et à chaque fois je devais supprimer la référence vers l'assembly, et la remplacer par une référence vers l'assembly spécifique à la plateforme sur laquelle les tests étaient lancés.

Bien lourd donc...

Mais depuis, c'est fini! Et si vous avez également le même souci, sachez qu'il existe une solution. Que voici sans plus attendre...

Continue reading...

Monday 28 June 2010

[PostSharp] [FluentValidation] Validation de classes grâce à IDataErrorInfo

Une manière de gérer la validation des données lorsqu'on utilise WPF est de faire implémenter l'interface IDataErrorInfo par les classes à valider, et de modifier votre fichier XAML pour que WPF utilise automatiquement les fonctions de cette interface pour valider la valeur des propriétés. (Un exemple en action ici).

Le souci avec cette méthode est que vos entités deviennent un peu plus que des entités de base. Et vous vous dites que finalement, ça ne serait pas mal d'externaliser la validation de ces entités dans une autre classe. Et pourquoi pas de définir des règles que votre entité se doit de respecter pour être valide. Pour cela, il existe FluentValidation.

Mais pour continuer à utiliser IDataErrorInfo, on doit maintenant utiliser FluentValidation au sein des fonctions définies par IDataErrorInfo. C'est ce que propose ce thread dans le forum de FluentValidation.

C'est en partant de cet article que je vais vous montrer le cheminement qui m'a amené à utiliser PostSharp pour régler en beauté (j'espère en tout cas) cette problématique.

Continue reading...

- page 1 of 4