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
Table
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

NHhibernate – multiple queries in one roundtrip to server

Usually when we need to retrieve data from database server, we write code which looks like that

This code will execute two queries,each of them in separate roundtrip to the server.
SeveralRoundtrips
This is the most popular way of getting data for multiple tables etc. However it is possible to enhance the code above and execute several queries in only one roundtrip to the database server. NHibernate provides us with three different mechanisms to accomplish this goal:

  • MultiQuery
  • First way to execute several queries at once is MultiQuery. In my opinion this is not very handy mechanism because of the fact, that we must use HQL. Here is an example of usage

    As You can see thanks to CreateMultiQuery method we are able to aggregate multiple queries. In order to get access to results, we have to execute code below

    Now we can get result of specific query using indexer

    If we don’t like this approach, the CreateMultiQuery method has an overload which allows to give “names” to queries. Thanks to this we can get result of query by its name.

  • MultiCriteria
  • Much better way of creating multiple queries is MultiCriteria. In this case we can use QueryOver API, so we don’t have to rely on HQL query strings.

    As You can see the usage of CreateMultiCriteria method is pretty consistent with CreateMultiQuery. Unfortunately we still have to retrieve data from specific query by index or by query name.

  • Future
  • My personal favorite for creating multi queries is Future. The usage is pretty straightforward

    As You can see, we can leverage QueryOver API and instead of calling List we call Future. NHibernate will aggregate our queries and will execute them once we start to iterate over one of them.
    delayedenumerator

Despite the fact that all three mechanism has completely different syntax ,SQL created by all of them is the same and looks like that
multiple queries

NHhibernate – multiple queries in one roundtrip to server

Resharper – “Go to Everything”

In Resharper 8 JetBrains introduced new command called “Go to Everything”. You can use it by hitting the CTRL + N keys (CTRL + T with Visual Studio keyboard shortcuts layout) This command is basically combination of three features known from previous versions of Resharper, namely: “Go to Class”, “Go to Type” and “Go to Symbol”. Most common usage of this functionality is just to search classes, properties or functions.
Go to Everything
However not everyone knows, that we can narrow down search criteria and find methods or properties in given class
Go to Everything
What is even more interesting, is the fact that it is possible to go to specific line in searched type
Go to Everything

Resharper – “Go to Everything”

Resharper – annotation attributes

1. Introduction

I think one of the most important features of Resharper is on-the-fly code quality analysis. Basically, every time Resharper finds possible pitfall in code, it indicates this with appropriate warning. The most common warning is “Possible System.NullReferenceException”. You can easily reproduce it by writing this code

singledefaultwarning
As you can see R# is able to figure out, that LINQ SingleOrDefault function can return null. However there is no warning if we try to do something like that

So it got me thinking, how Resharper recognizes whether or whether not to show warnings. It turned out, that it uses annotation attributes, which describe behavior of functions, properties, classes and interfaces.

2. Source code annotations

In order to use these attributes we have to place them in our project. First of all, let’s create Annotation.cs file and then copy default implementation of annotations into this file. The default implementation can be found in Code annotation option (Resharper->Options->Code Inspections->Code Annotations) under the button “Copy default implementation to clipboard”.
resharperOptions
annotationoptions
From now on we can decorate our functions with e.g. CanBeNull attribute

and we will get warning if necessary
annotation attributes
Of course there are a lot more of attributes to use. My favorites are:

  • StringFormatMethodAttribute
    annotation attributes

  • PathReferenceAttribute
    annotation attributes

  • NotifyPropertyChangedInvocatorAttribute
  • annotation attributes

3. External code annotations

In case we do not have access to source code, we still are able to use annotation attributes. However we have to define annotations in xml configuration file. Let’s say we want to decorate NHibernte’s SaveOrUpdate function with NotNullAttribute. First of all we have to create xml file with appropriate declaration (This is standard XML Document Comment file. You can read specification here and here.)

Having prepared configuration file, we need to place it in appropriate location in order for Resharper to use it. It can be stored in

  • [ReSharper install directory]\Bin\ExternalAnnotations\[Assembly name].xml
  • [ReSharper install directory]\Bin\ExternalAnnotations\[Assembly name][Any name].xml.

So in my case the location is

After restarting Visual Studio, Resharper should load the file and show warning messages.
nhibernate

4. Generating initial XML annotation files

Creating xml annotation file for large library is very tedious task, fortunately Resharper have a hidden feature which can help us with generating initial xml file. First of all we have to run Visual Studio with /ReSharper.Internal parameter. In this mode we have an access to undocumented/hidden features of Resharper. Now, in the “Resharper” menu there is one additional menu item – Internal, where You can find Annotator submenu in which resides Annotate item.
annotator
Now You can specify for which dll Resharper should generate xml annotation file.
annotatorwindow
and after a while You should get complete xml declaration.
annotatorprogress
Please bear in mind, that Annotator is not official R# feature, so there is no guarantee that generating annotation files will succeed. Source code for this post can be found here

Resharper – annotation attributes