Geen categorie

Things I always have to Google…

Note: this blog is no longer maintained. Please go here to see the latest updates of this post.

Every now and then, I have to Google for something that I’ve Googled before numerous times because I forgot. Because this is a time consuming activity, I’ll bundle them all into one post. In other words, this is a post that will be often updated.

Continue reading

C#, NServiceBus, Service Bus, Tutorial

Getting started with NServiceBus

Note: this blog is no longer maintained. Please go here to see the latest updates of this post.

In this blog post we’ll take a look at NServiceBus, a popular open-source service for .NET. With an easy to follow tutorial, you’ll have a working service bus up and running within minutes.

Continue reading

Geen categorie

Create lambda expressions on the fly in C#

Note: this blog is no longer maintained. Please go here to see the latest updates of this post.

The last couple of weeks, I have been working with client-side frameworks such as Kendo UI and Sencha ExtJS a lot. One of the requirements of my clients was server-side filtering, grouping and ordering of several grids and other components. The challenge here is that you don’t know exactly what information might be coming in: which field do you have to filter or sort, which direction, what operator do you have to use, etc. There is only one proper way to do this in C#: Expressions!

Meer lezen…

At some point, every developer will use the fantastic capabilities of LINQ. If you look under the bonnet, you’ll notice all of this is possible thanks to delegates and expressions.

Note: the difference between expressions (Expression) and delegates (Func) is explained really well in this StackOverflow article. I’d like to simplify this by saying that Func is just a regular delegate whereas Expression is some kind of wrapper around the delegate with added metadata. Of course, there’s much more to it but that’s out of scope of this article.

With just one line of code, you can query a list with a complex filter – with the list being any kind of collection such as a database table or just a plain IEnumerable collection:

This kind of code works well if your queries are static and are not likely to change. However, when queries are dynamic and not known upfront, you’ll have to get rid of this approach and go a slightly different way. In fact, if you look at the definition of the Where extension method, you’ll see it expects a delegate:

public static IEnumerable<TSource> Where<TSource>(
	this IEnumerable<TSource> source,
	Func<TSource, int, bool> predicate

Looking at this definition, the following code snippet is perfectly valid:

Func<MyClass, bool> whereClause = (x) => x.MyField == 1;
return myCollection.Where(whereClause );

For every item in the collection, the whereClause delegate will be executed. You can see this happening if you set a breakpoint on the delegate.

This is all well and good, but this is still a static query. Enter PredicateBuilder! The PredicateBuilder allows you to generate dynamic queries.

Let’s take this original example:

p => p.Price > 100 &&
     p.Price < 1000 &&
     (p.Description.Contains ("foo") || p.Description.Contains ("far"))

The same result can be achieved with the PredicateBuilder:

var inner = PredicateBuilder.False<Product>();
inner = inner.Or (p => p.Description.Contains ("foo"));
inner = inner.Or (p => p.Description.Contains ("far"));

var outer = PredicateBuilder.True<Product>();
outer = outer.And (p => p.Price > 100);
outer = outer.And (p => p.Price < 1000);
outer = outer.And (inner);

The important thing to notice is how the PredicateBuilder brings it all together. You can define your queries independently from each other, after which you can tie them together using the AND or OR extension methods.

This is incredibly nice if you want to get rid of these kind of constructions:

static void QueryByYear(string level)
    GradeLevel year = (GradeLevel)Convert.ToInt32(level);
    IEnumerable<Student> studentQuery = null;
    switch (year)
        case GradeLevel.FirstYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FirstYear
                           select student;
        case GradeLevel.SecondYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.SecondYear
                           select student;
        case GradeLevel.ThirdYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.ThirdYear
                           select student;
        case GradeLevel.FourthYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FourthYear
                           select student;

    Console.WriteLine("The following students are at level {0}", year.ToString());
    foreach (Student name in studentQuery)
        Console.WriteLine("{0}: {1}", name.LastName, name.ID);

There’s just one problem with what we’ve got at this point: the filters are still static. You still have to write somewhere in your code what you want to query. Enter expressions!

In cases where you don’t know which field will be ordered or which field will be filtered by which value, you’ll have to build this query up from the ground. To give you an idea of, here’s an example of a Web API that is used by the client-side frameworks:

 public async Task<dynamic> Get(int page, int start, int limit, string sort = null, string group = null, string filter = null)

Data from the sort, group and filter arguments are formatted in JSON. I usr the handy JSON.NET NuGet package to deserialize this information into CLR objects:

 public class Filter
        public string Property { get; set; }
        public string Value { get; set; }
        public string Operator { get; set; }

With this information, I can start creating my query. I know which property is targeted, what value is passed as the argument and how to compare the value to the property. The following code will do all of this, let me guide you through it.

  public Expression<Func<T, bool>> GetExpressionForType<TEntity>(string field, string operation, object value, string ignoreCase)
  Expression<Func<T, bool>> whereClause = default(Expression<Func<T, bool>>);
  ParameterExpression param = Expression.Parameter(typeof(T), "x");
  MemberExpression member = Expression.Property(param, field);

   Type propertyType = member.Type;
   TypeConverter converter = TypeDescriptor.GetConverter(propertyType);
   var result = converter.ConvertFrom(value.ToString());
   ConstantExpression constant = Expression.Constant(result); 

Expression comparingExpression = default(BinaryExpression);
switch (operation)
      case "eq":
         comparingExpression = Expression.Equal(member, Expression.Convert(constant, member.Type));
      case "startswith":
          MethodInfo startsWithMethodInfo = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
          comparingExpression = Expression.Call(member, startsWithMethodInfo, Expression.Convert(constant, member.Type));

First your start of by creating the return value type: Expression.
Next, you setup the left-hand side of the lambda expression: (x) =>. In many cases, one parameter will do but it could be possible that you want to define multiple parameters.
Now the property of the generic T type is targeted: (x) => x.PROPERTY. If you have complex navigation properties, you can define a MemberExpression of a MemberExpression, which will result in (x) => x.PROPERTY.PROPERTYOFPROPERTY
The following 4 lines will create the value to compare to. The typeconverter will ensure that apples can be compared to apples (int to int, string to string, …).
At this point we have all components ready to be tied together. Depending on the type of operation, you’ll want to use GreaterThanOrEquals, Equals, NotEquals, etc… Add your logic here and then set that value to the Expression variable.
The last thing to do here is to convert the expression to a lambda:

var lambda = Expression.Lambda<Func<T, bool>>(comparingExpression, param);

Now you’re done, you’ve successfully created a dynamic query. The lambda variable can now be used anywhere where you would use lambda expressions otherwise. Do keep in mind that not all LINQ providers are equally strong. For instance, the capabilities of Entity Framework are limited, so you cannot execute complex algorithms in the runtime of Entity Framework.

The same kind of code is perfectly valid for sorting and grouping, but there’s less complexity involved in the process as you don’t have to define operators and values.

I really love to work with expressions, it’s very flexible and it allows you to generate code on the fly, which I think is amazing.