Combining expressions to use with the Entity Framework

You often have to create a screen where the information is filtered on a given condition and the user can set some more options through checkboxes. For instance, display all products of a certain category and those results should be able to be filtered on their active status.

We could send one query to the database to retrieve the products and then filter them in memory, but let’s try to use the database for all of this since they’re good at this. You’ll bump into several issues when trying to solve this and like most problems in software development someone else most likely encountered the same issue and has already found a solution. In this case take a look at this, albeit old, article which illustrates the problem and gives a solution. It will enable you to write code like this:

public class ProductFinder
{
  public  ICollection<Product> FindProductsBySubCategory(int subCategoryId, bool makeFlagMarked)
  {
    using(var context = new AdventureWorksEntities())
    {
      Expression<Func<Product, bool>> whereClause = x => x.ProductSubcategory.ProductSubcategoryID == subCategoryId; 
      if(makeFlagMarked)
      {
        whereClause = whereClause.And(x => x.MakeFlag);
      }
      return context.Products.Where(whereClause).ToList();
    }
  }
}

Changing Entity Framework model at runtime

Out of the box there is no way, or at least not an easy one, to change table or schema names used by the Entity Framework at runtime. If you used MyDbName.dbo.BlogPosts as table name during development you can not use MyDbName.dbo.CustomerA_BlogPosts if you want to support customer specific table names as explained in my previous post.

On CodePlex however you can find an adapter for your Entity Framework model to change it at runtime. You can change the connection to the database, change table names or use different schemas. So a lot of goodness to support multi tenant applications.

In order to use the adapter you should create a partial class with the name of your context class and inherit from AdaptingContext instead of ObjectContext.

public partial class AdventureWorksEntities
  : AdaptingObjectContext
{
  public AdventureWorksEntities()
    :base("name=AdventureWorksEntities", "AdventureWorksEntities",
            new ConnectionAdapter(new TablePrefixModelAdapter("MyPrefix"), Assembly.GetExecutingAssembly()))
  {
    OnContextCreated();
  }
}

This partial class has the same name as the partial class generated by the Entity Framework. You should remove the generated constructors and base class specification from that one or your code will not compile. Note that every time you update the model with the designer it will regenerate the constructors etc. so you have to remove them every time.

In this example I’m using the TablePrefixModelAdapter which will prefix all my tables with my specified prefix, in this case “MyPrefix”. Consuming this context is done just like a normal ObjectContext. You also need to specify where the mappings that need to be altered are located, in this sample I’m using a single console application so they are contained in the executing assembly.

using(var context = new AdventureWorksEntities())
{
  var products = context.Products;
  products.ToList().ForEach(x => Console.Write(x.Name));
}

And this generates the following SQL:

SELECT 
1 AS [C1], 
[Extent1].[ProductID] AS [ProductID], 
[Extent1].[Name] AS [Name], 
[Extent1].[ProductNumber] AS [ProductNumber], 
... 
FROM [Production].[MyPrefixProduct] AS [Extent1]

So we’re all set to support multi tenancy? Not quite. The code as available in the CodePlex project stores the updated mappings in a static variable for performance reasons, this is great if you’re developing against a development database and your code will run against a production database with different naming or schema.

For a multi tenant application we need a different model for each of our customers so we need to make another change to the code as available in the CodePlex project. If you don’t mind taking the performance hit to rewrite the mapping every single time an object context is created you can just open the ConnectionAdapter class and change the static variables which hold the model information to instance variables.

And optimized version would store all the mappings per customer so you only rewrite the mappings once a new customer hits the context, and from that point store them in i.e. a dictionary with key the customerID and value the updated mappings.

I’ve used Entity Framework 3.5 SP1 and Visual Studio 2008 in this post.

Covering multi tenancy in the database

You there, computer man! Make it a multi tenant application.

There are several ways to support multi tenancy on the database part of your application. The easiest approach would be to add a CustomerID column to each table. This is easy to maintain since any change you make in your development environment (add a column, change a type,…) needs to be done only once on the live environment. The downside however is that all data of all your customers is mixed in one table forcing you to add a where clause to all your queries to filter on the customer id, if you support different business logic per customer you might also run into issues. Customer A wants an additional field etc.

Another approach is to prefix or suffix your table names with some sort of customer identification. So you’d have CustomerA_BlogPosts, CustomerB_BlogPosts. You can have a single database for all your customers but now all data is stored in a different table. Since now you have multiple tables representing the same model you’ll have to figure out a way to migrate to new versions. It’s doable but keep it in mind, you’d also have to create some infrastructure to select the correct table when you issues your queries.

A variant on the customer specific table names is to create database schemas which are specific to your customer. So you’ll have CustomerA.BlogPosts and CustomerB.BlogPosts. Apart from the fact that all data is stored in specific tables per customer, like the approach stated above, you can also add an additional security layer by using a specific database user per customer which can only access the tables of the specific schema. All table names remain the same so you could even migrate specific customers to another database server as long as your infrastructure to look up the correct database / schema name.

The most flexible way however, but with quite an impact on your server, is to create an entire database instance per customer, this gives you the most available options. You can use all available database tooling to revert specific databases if the customer asks you to etc.

I’ve used all approaches stated in this post and even mixed and matched between them, it all depends on the scale and requirements of your project. For small projects I’d use the first approach with the additional column. For larger projects or where you need to support different data models per customer the schema specific approach or the entire database per customer are the way to go in my opinion.

Config file behaviour MonoDevelop and Visual Studio

Updated Mono and MonoDevelop to their latest version and I’m pleasantly suprised. Ran all unit tests of my channel library and they all passed with flying colours, that means there have been some serious WCF improvements.

The only small difference in behaviour I’ve noticed so far is that config files are not automatically copied to the output directory. In order to do this, right click the file go to “Quick Properties” and select “Copy To Output Directory”.

And another thing, “Add Reference” in MonoDevelop is pure bliss. Look at that speed Microsoft!

NoXML Spring.NET

If you say to any .NET programmer you use Spring.NET (that they know it exists is already good to hear) the discussion will head immediately into XML world. Yes they can be a pain but with a bit of discipline you can keep them structured and well maintained, though if I could choose I’d drop them too. The reason I’m still sticking to this framework is because it offers so much. DI, AoP, data access, messaging,… most applications I’ve created need at least some components from the Spring.NET stack.

Erich Eichinger has posted on CodeConfig and assembly scanning for Spring.NET a while ago and it is scheduled to be included in Spring.NET in the future. Go check it out.

Reading PDF files on the iPhone

You can natively read PDF files with your iPhone yet one feature that is lacking is a go to page feature. This is not an issue when you have a file which is only 2-3 pages long, typical size of a file being send through mail. But when you want to get some serious reading done and have already read a couple of hundred pages in the book, having to skip through all of them when you want to continue where you left off becomes a serious issue fast.

There are a lot of options when you look for pdf or ebook reader in the App Store some are payware some are free. I was very reluctant to get one in the past, hoping that Apple, in its infinite wisdom, would add the feature to the standard PDF reader.

Yet as of this date it’s still not implemented.

A friend suggested I check out Aji Reader, it’s free at the moment and I’ve used it for several months. I’m quite happy with it. You can get content on your phone with a desktop application that syncs your pdf files.

With the iPad around the corner I’ll probably read less on the tiny iPhone screen and move to this new platform but this blog post has been in my todo list for far too long.

Using SQLite in 64-bit .NET environments

When you download the binaries from the SQLite site you’ll notice that there are specific versions for different environments. While I used the 32 bit version on my Vista 64-bit machine in the past, or at least I think I did, I ran into problems with them when I migrated to Windows 7.

Turns out that some code in the 32-bit library can’t run on a 64-bit version for reasons that probably matter but are unknown to me.

.NET applications run natively in 32 or 64-bit mode depending on your system by default, if you keep your compile settings unchanged. The only way to use 32-bit libraries, that have specific 32-bit dependencies, is to change your compile settings or use a tool that ships with Visual Studio / the SDK.(CoreFlags.exe)

To change your compile settings in Visual Studio:

  1. Go to the startup project of your program.
  2. Open the properties window.
  3. Click the compile tab.
  4. Click advanced compile options.
  5. Change the target CPU options to x86.

Your program will now always run in 32 bit mode, even when run on a 64 bit machine.

You could also provide two distributions, one for each environment. While this will become the standard in the future, for my current project this was the best and easiest option.

More info can be found here: Running .NET Apps in 32-bit mode on 64-bit Windows, MSDN: 64-bit Applications, Visual Studio Development Environment 64-Bit Support, forum post at the SQLite site

October 2009 bookshelf

Sams Teach Yourself WPF in 24 Hours

I’m in the process of creating an application for a friend of mine who is starting his own company. He needs a little CMS system to support his business in the advertising world. He gave me a nice layout to use in the application so WPF seemed to be the best option. I jumped right in only to find that it was more complex than I first expected. After looking around what was available I decided to go for this book since it’s co-authored by Rob Eisenberg who is in charge of the Caliburn framework.

I’m just passed the first part of the book which introduces the layout containers (grid, stackpanel, wrappanel,…) and the basic containers. It already helped me getting the layout right for the application I’m writing. Also the code snippets in the book are in colour which certainly improves the readability of especially the XAML.

The Art of Unit Testing: with Examples in .NET

Though I’m convinced of TDD and unit testing in general I find it hard to apply when doing projects at work. I’m hoping this book will help me to structure my programming work around TDD and how to write good maintainable tests. The text is written in an easy to read manner and currently feels like a step by step guide on how to become a better test writer. You don’t need any prior knowledge to get started with this book. I’ve only read the first 100 pages but in my eyes it’s already a classic, go get it.

Dependecy Injection in .NET

Earlier this week you could get this one for a mere $10 via a twitter promo code. Though I’m fairly confident I know what DI is, when to use it and what the advantages are you always need to keep an eye out for any new insights or information. Have only read the first couple of pages where the problem of coupling between your components is sketched. The book is still a work in progress, but you can already get it via the Early Access Program.

WCF ChannelManagement bug fix

Not really a release but I’ve just applied a bug fix that solves a null reference exception when returning null from the service you’re calling. Thanks to Jay from the Spring.NET forum for reporting and fixing the issue. I’ll clean up the code and add some more test cases the coming days. The updated code is available in the svn repository.