ASP.NET MVC, Javascript

ASP.NET MVC and HTML5 Web Workers

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

Although the technology has been around for a while now, HTML5 Web Workers didn’t draw my attention until a few days ago. As I’m building a client facing SaaS application for my client, performance is crucial. Having worked with asynchronous methods in C#  for years, I thought of using this concept in JavaScript. As it turns out, multithreading in Javascript isn’t really part of the package. You had to work with timeouts and callbacks to implement some kind of asynchronous architecture, but splitting some heavy work into multiple threads (and even background work for that matter) wasn’t really supported out of the box – until HTML5 Web Workers were introduced. In this article, I’ll explore the capabilities in two different ways in the context of a ASP.NET MVC 5 application.

Continue reading

Advertisements
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:

https://gist.github.com/hbulens/a2601f90d9867d68ae65cc72409f4cb5.js

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;
            break;
        case GradeLevel.SecondYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.SecondYear
                           select student;
            break;
        case GradeLevel.ThirdYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.ThirdYear
                           select student;
            break;
        case GradeLevel.FourthYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FourthYear
                           select student;
            break;

        default:
            break;
    }
    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));
          break;
      case "startswith":
          MethodInfo startsWithMethodInfo = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
          comparingExpression = Expression.Call(member, startsWithMethodInfo, Expression.Convert(constant, member.Type));
           break;
   }
}

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.

MVC, Troubleshooting

ASP.NET MVC fixing error ‘Multiple types were found that match the controller named’ when routing is not the problem

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

I just came across following error message while I was converting one of my ASP.NET MVC applications:

Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

The request for 'Home' has found the following matching controllers:
hbulens.WebUI.POC.Controllers.HomeController
hbulens.POC.WebUI.HomeController

Beschrijving: Er is een onverwerkte uitzondering opgetreden tijdens het uitvoeren van de huidige webaanvraag. Raadpleeg de stacktracering voor meer informatie over deze fout en de oorsprong ervan in de code.

Details van uitzondering: System.InvalidOperationException: Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

The request for 'Home' has found the following matching controllers:
hbulens.WebUI.POC.Controllers.HomeController
hbulens.POC.WebUI.HomeController

Normally, you would expect something is wrong with the routing engine, The error messages on this subject are quite clear:

[InvalidOperationException: Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

In my case, this wasn’t the problem. Instead, I changed the namespaces and assembly name of my MVC project from hbulens.WebUI.POC to hbulens.POC.WebUI, but the ASP.NET MVC project itself remained intact.

Being uncautious, I left the old assembly output in the bin folder while I was trying to debug the new assembly output, with beforementioned error as a result.

There is a very easy way to fix this: delete your bin folder and rebuild your project.

C#, Wordpress

Retrieving blog posts using C# and the WordPress REST API

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

As part of my new professional website that I hope to release later this year, I thought it would be a good idea to dedicate a part of my site to this blog. Instead of choosing the rather traditional  way of integrating blogs (e.g. embedded HTML snippets), I have chosen to take a look at its Web API. In this article, I will focus on one scenario: working with blog posts.

Continue reading

C#, MEF

Tutorial on creating loosely coupled applications with MEF

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

When I first read about MEF (Managed Extensibility Framework), I thought it was a great concept to create plugin-based applications, allowing customers to customize some behavior of the application for instance. Putting the whole concept into reality is something different, so in this article I will give a brief overview of the steps to take to get started with MEF.

Continue reading

C#, Cloud, Entity Framework, MVC

Creating SQL schemas using Entity Framework Code First

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

As you might have read in my previous post, I used SQL schemas to partition data between tenants. Being part of the true definition of SaaS, a new tenant should be up and running within minutes without any human intervention.

With my suggested approach, we need to do two things:

  • Registering a new tenant
  • Attaching users to the tenant

In this article, I am going to focus on the first item whereas the second one shouldn’t be a big deal if you are planning to create software as a service.

Continue reading