Implementing INotifyPropertyChanged without lambda expressions and “magic” strings

I think almost every .NET developer is familiar with INotifyPropertyChanged interface. Typical implementation of this interface looks more or less like that:

Thanks to lambda expressions we can get rid of so called “magic” strings when rising PorpertyChange event.

However, with .NET 4.5 we can even get rid of lambda expressions itself. Everything thanks to CallerMemberNameAttribute, which provides us information about caller of given method. Now we can rewrite NotifyPropertyBase class as follows

From this moment we can call OnPropertyChanged method without any arguments

and thanks to CallerMemberName attribute, argument propertyName will be filled with appropriate value.
Source code for this post can be found here

Implementing INotifyPropertyChanged without lambda expressions and “magic” strings

How to check if one function calls another function

An application which I’m currently developing has quite complicated authorization system. That is why, we can not use role based authorization, and basically every developer is obliged to call appropriate security check method in every controller action he or she writes. As You probably know it is quite easy to forget about that, therefore I decided to write a test which would check whether all controller’s action invokes this security critical function. After hours of searching for some anchor point, I came across this article in which author creates so called “reflection based ILReader”. ILReader is a class which allows You to iterate over IL instructions of every object of type RuntimeMethodInfo or RuntimeConstructorInfo .One of these instructions is InlineMethodInstruction which indicates method call. That is why, in order to get all methods which are called by given method, we have to simply select all instructions of type InlineMethodInstruction

We can go a bit further and create a recursive version of this function to iterate over entire function execution chain

Please notice, that I limited recursion depth to methods from user defined namespace, otherwise we would end up iterating over .NET’s native functions.
Now it is time to show some results. Here is a sample program which demonstrate possibilities of MethodInvokerCrawler class

calls another function
At this point checking whether function or constructor calls another function is limited to simple LINQ query

Source code for this post can be found here

How to check if one function calls another function

NHibarnate – using event listeners to set entity modification date

I think, that it is a common practice to store information about creation and modification date of entities. However keeping appropriate columns up to date manually is error prone. We must remember that every time we modify entity, we also have to change its modification date. Fortunately thanks to event listeners, NHibernate can do all of this boring stuff for us. Let’s start from creating class which implements two interfaces:

  • IPreInsertEventListener
  • IPreUpdateEventListener

As You probably guessed OnPreInsert method is invoked before insert, and OnPreUpdate is called before update of entity. Having prepared the basic skeleton of class, it is time to configure NHibernate to use our event listeners. The basic configuration is taken from my previous post about NHibernate automappings, so I will only extend it by appending event listeners

Now we can put some logic into OnPreInsert and OnPreUpdate functions. First of all we have to somehow identify entities which hold information about creation and modification time. In order to do that I created simple interface IDateInfo

In the next step we have to modify OnPreInsert and OnPreUpdate methods, so that they can set creation and modification date of entities which implement IDateInfo interface.

Unfortunately at this moment saving entity (which implements IDateInfo interface) will throw exception
Despite the fact that we set values of ModificationDate and CreationDate properties , NHiberante seems not to notice that. That is why we have to manually update values of State object from PreInsertEvent and PreUpdateEvent. According to the documentation State object from class PreInsertEvent holds values which should be inserted and State object from class PreUpdateEvent holds values which should be updated. Function which update values of state object might look like that

Updated NHListener class now looks like that

As You can see, after setting values of IDateInfo I also call function SetState and update state of appropriate properties. From now everything works fine and our entities can be saved without problems. Source code for this post can be found here

NHibarnate – using event listeners to set entity modification date

Fluent Nhibernate – automappings

1. Introduction

Writing mappings for models in large application is quite boring task. Fortunatelly, Fluent NHibernate provides possibility for automatic mapping creation – so called automappings.

2. Creating database and model

In order to show you, how to configure automappings in Fluent NHibernate, let’s create simple database along with model classes. The database structure is presented in the picture below.
Model classes which represent database tables look this way

3. Automappings configuration

Having our database and models prepared, now we can create and configure SessionFactory to use automappings.

As You can see I used the static AutoMap.AssemblyOf method. This method takes a generic type parameter from which Fluent NHibernate can deduce which assembly to look in for mappable entities. From now all classes defined in the assemlby of Project are mapped using build-in convention.

4. Mapping only specified classes

Mapping all classes from specyfic assembly may not be very useful. That is why, we need to “tell” Automapper which classes should be mapped. It can be achieved by creating custom configuration class which implements IAutomappingConfiguration interface or which is subclass of DefaultAutomappingConfiguration. IAutomappingConfiguration interface has quite a lot of functions, that is why I decided to craete class which inherits from DefaultAutomappingConfiguration and override only one method – ShouldMap

As You can see by overriding ShouldMap function,I specified that only classes which inherit from ModelBase class should be mapped. To use our new configuration, we need to pass an instance of it to AutoMap setup

5. Defining custom conventions

It is rather obvious that default automapping conventions may not come along with our database naming conventions. Fortunately we can create custom conventions(which override default ones), and pass them to AutoMap configuration. Here are examples of conventions I use IClassConvention – gives us access to properties and functions which allow us to change a default table name format for our entities.

IIdConvention is used for altering default identity conventions.

IPropertyConvention – allows us to modify properties mappings (lazy load, nullability,length etc)

IReferenceConvention – allows us to modify entities relationship convention

IHasManyConvention – allow us to modify default has-many relationship convention

In order to use new conventions we need to pass them into AutoMap configuration.

6. Overriding mappings

Sometimes it is necessary to slightly modify entity mapping. It can be achieved by creating class which implements IAutoMappingOverride interface

Override method gives us access to all actions known from fluent mappings. After creating class map, we have to call function UseOverridesFromAssemblyOf in our automapping configuration

7. It works

Here just couple of screens from NHibernateProfiler with basic queries
Source code for this post can be found here

Fluent Nhibernate – automappings

StringBuilder – removing trailing characters

Today just quick tip about StringBuilder
I used to remove last character(s) from StringBuilder using Remove method.

However, recently I’ve came accross even simpler solution. You just need to lessen the Length property of StringBuilder, in order to get rid of last characters

StringBuilder – removing trailing characters