Nested properties initialization – syntactic sugar

I think most of developers are familiar with the object syntax initializer, which basically allows you to set up values of properties just like that

In this example the Settings property is assigned with new instance of CustomWebClientSettings class. However for time to time we only want to change particular property of given nested property and leave rest of the object intact. Of course we can write it usual way

but there is a much cooler syntax for that. The code above can be rewritten to

Note that there is no new keyword in the assignment of Settings property, which means that the Settings object is updated with the values of properties in braces. Of course this syntax can be safely used only if the nested property(in this case Settings) is initialized up front in constructor, otherwise you will get NullReferenceException. Source code for this post can be found here

Nested properties initialization – syntactic sugar

NHibernate – generating WHERE IN … OR … queries

Let’s assume that we have a simple table GL_Task which looks like this
I was asked to rewrite simple SQL query

using NHibernate’s QueryOver API. As simple as it may seem, solution for this particular problem is not straightforward. My first (not so clever) attempt was simply combining WhereRestrictionOn and Where clause

Of course this query returns wrong data because of the fact, that NHiberante by default “joins” queries using AND operator. So above query will result in generating something like that

After a little digging I managed to write appropriate query

Although this code generates correct SQL, it is hard to use it in case of many OR statements. For example, adding one more OR force us to write

In my opinion this is a little bit hard to read, so I continued my searching to find more elegant solution. My third attempt was based on Restrictions.Disjunction

This was almost perfect solution. Adding new OR statements do not require us to do function nesting

However the ultimate solution is to just add NHibernate.Criterion namespace and use IsIn extension method. This operation simplify our query into single lambda expression

Source code for this post can be found here

NHibernate – generating WHERE IN … OR … queries

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

Resharper – custom snippet

I think all Resharper users are familiar with snippets. Resharper’s snippet basically generates a piece of code, which can be easily customised on the fly. All you have to do is to press TAB, and you can change names of auto-generated variables etc. Today, I decided to write my own snippet, which would make writing unit tests easier. In general, all my unit test methods looks like this

So let’s write a snippet which will generate a method with this signature. In order to do this, let’s choose a Templates Explorer… from the Resharper’s menu.
In the opened window, click on the plus sign and a new tab should appear.
Let’s name our snippet test and paste the following code into the main editor.

Now, we’ve created a simplified snippet for generating our test function signature. However, this snippet is not really useful as its user cannot navigate through the underscored chunks. In order to employ the Resharper’s navigation features, we have to slightly modify our snippet. Let’s replace the previous code with this one:

Please notice that now some parts of the method’s name are written between dollar signs. Thanks to this syntax, the Resharper is able to iterate over these parts and lets us change their names on the fly. $END$ is a special control sequence which tells the Resharper where to stop iteration over variables. At this moment, our snippet is fully functional and we can use it by typing the word test and hitting the TAB button.
custom snippet

Resharper – custom snippet

Argument validation with attributes and Ninject interceptor

1. Introduction

It is a common practice to validate function arguments before running actual code. Usually validation looks like that:

There is nothing wrong with this code, however we have to repeat this piece of code in every function. Of course we could create some helper class for argument validation and call approperiate validation function before launching rest of the code

However I was searching for more universal way for argument validation. That is why, I decided to try function interceptors and attributes.

2. Creating validation attributes

Let’s start for creating base attribute

In the next step let’s create specialized attribute for “not null” validation. This argument may look this way:

3. Using IInterceptor interface

That was an easy part, now it’s necessary to somehow intercept function execution and run attribute validation.In .NET there is no build-in mechanism to do that,that is why I’ll use extension for Ninject – Ninject Interception. First of all we have to add to our project three dll’s

  • Ninject
  • Ninject.Extensions.Interception
  • Ninject.Extensions.Interception.LinFu

You can easily add them using NuGet. Having all necessary files added to solution,let’s create function interceptor – ValidaitionInterceptor.

As You can see ValidationInterceptor implements interface IInterceptorwhich belongs to Ninject.Extensions.Interception. This interface has one method Intercept which is called before function from registered component is called. In this function I iterate over all function attributes of type ArgumentValidationAttribute and call ValidateArgument function. If validation passess function invocation.Proceed() is called, which continues execution of original function.

4. Example of usage

In order to take advantage of benefits of function interceptors, we have to resolve objects from Ninject container. First of all I’ll create some examplorary classes

In the next step I’ll create simple wrapper for Ninject container and register CarRepository in Kernel

Please, notice that registration of CarRepository was used with option Intercept().With(). Thanks to this configuration,everytime we call method from CarRepository, Intercept method from ValidaitionInterceptor will be called first. Now, it is time to use our repository,we could do that this way

Argument entity in method Update from interface IRepository was decorated with NotNull, that is why our validation mechanism should throw exception.
Argument validation

5. Validation of return value

Using IInterceptor we could go one step further and also validate return value of method. In order to do that, we have to slightly modify Intercept method in ValidaitionInterceptor class.

We also have to change attribute usage of ArgumentValidationAttribute to

Now, we can decorate function GetAll with NotNullattribute

Since this moment, everytime function GetAll returns null, the ArgumentNullException will be thrown.

6. Drawbacks

Unfortunately using attributes for argument validation have some drawbacks. First of all, argument validation is based on function interceptors, and as I mentioned before only function, which are in objects, which are resolved from IoC container can be intercepted. What is more, interceptors allow us to intercept only functions marked as virtual or inhirited from interface. Source code for this post can be found here

Argument validation with attributes and Ninject interceptor