NLog 2.0 Release Candidate is out!

June 18th, 2011

It is my pleasure to announce that the Release Candidate (RC) of NLog 2.0 is now available for download. This is the last milestone before NLog 2.0 final release.

  • Binary downloads are available on CodePlex
  • Source code on GitHub
  • Full release notes can be found here.

Please download the release and report any problems you may find. Assuming no critical issues are found, NLog 2.0 will be released within a month from the RC release.



NLog 2.0 Beta1 has been released

September 26th, 2010

It is my pleasure to announce that NLog 2.0 Beta 1 has been released.

NLog 2.0 release is focused on adding support for new platforms (Silverlight, .NET Framework 4), improving logging architecture and manageability and addressing most frequently reported user issues.

The following platforms are supported in this release:

  • .NET Framework 2.0 SP1 and above, 3.5 (Client and Extended profiles), 4.0 (Client and Extended profiles)
  • Silverlight 2.0, 3.0, 4.0
  • .NET Compact Framework 2.0, 3.5
  • Mono 2.x profile

Read full release notes:

Download Beta 1 bits on CodePlex:

Source code is available on GitHub:

Bugs can be reported on CodePlex:

Discuss on forum:

Subscribe to NLog RSS feed:

Follow @JarekKowalski on Twitter:

No Comments

EFProviderWrappers v1.02 is available

August 3rd, 2010

I’ve just updated EFProviderWrappers sample to v1.02. It’s a bugfix release, which fixes two bugs:

  • NotImplementedException during SaveChanges() when saving more than 1 entity
  • Non-query commands were sometimes cached which was causing update to fail

The code can be downloaded from:


Sample Provider for Entity Framework 4.0 is available

May 24th, 2010

Today Entity Framework team released an update to Sample Provider for Entity Framework 4.0. The provider is intended to be an example for ADO.NET provider writers but can also be used and hacked upon by everyone interested in the inner workings of an EF provider.

The sample can be downloaded from MSDN Code Gallery. It is licensed under Microsoft Public License (Ms-PL). EFQuerySamples includes additional examples of configuring and using the sample provider.

Tags: , ,


Update to EFProviderWrappers is available

May 24th, 2010

I’ve just posted a tiny update to EFProviderWrappers sample. It fixes the issue which was reported to me by several users, where NotSupportedException was being thrown during SaveChanges() from caching provider code.  

You can download updated bits from MSDN Code Gallery. If you find any other issues, please report them as comments here.

Tags: , ,


Attaching LINQ expression trees to delegates

May 18th, 2010

Inspired by discussion on Twitter today, I started exploring the possibility of attaching LINQ expression trees to compiled delegates. The idea is that you could pass around Func<T> instead of Expression<Func<T>> yet still be able to retrieve original expression tree used to compile the delegate. This makes some scenarios (testing, logging) much cleaner, because you don’t need to deal with expressions as much.

But how do you attach anything to a delegate and Func<T> in particular? Aren’t delegates essentially function pointers?

Well – in .NET each delegate holds information about both the target object instance and the method to invoke on it. This makes it possible to create a tiny wrapper object that would have a function which behaves like Func<T> but holds additional state. Let’s look at a simple wrapper for Func<T> which stores expression:

public class FuncWithExpression<TResult>
    private readonly Func<TResult> wrappedFunction;

    public FuncWithExpression(Expression<Func<TResult>> expression, Func<TResult> func)
        this.Expression = expression;
        this.wrappedFunction = func;

    public TResult Function()
        return wrappedFunction();

    public Expression<Func<TResult>> Expression { get; private set; }

Let us also define two of extensions methods: one which compiles Expression<Func<T>> and wraps the result with FuncWithExpression<T> wrapper and the other one which extracts the expression from Func<T>:

public static class ExtensionMethods
    public static Func<T> CompileAndWrap<T>(this Expression<Func<T>> expression)
        Func<T> compiledExpression = expression.Compile();
        return new FuncWithExpression<T>(expression, compiledExpression).Function;

    public static Expression<Func<T>> GetExpression<T>(this Func<T> func)
        var exp = func.Target as FuncWithExpression<T>;
        if (exp != null)
            return exp.Expression;

        return null;

That’s it! (Of course, in real life you would need to provide overloads for more Func<> types, since functions without arguments are not typically very useful). You can now write the code using just Func<T> and still be able to retrieve original expression tree used to compile the delegate:

class Program
    static void PrintAndExecute(Func<int> func)
        Expression originalExpression = func.GetExpression();
        if (originalExpression != null)
            Console.WriteLine("expression: {0}", originalExpression);

        Console.WriteLine("result: {0}", func());

    static void Main(string[] args)
        var body = Expression.Add(Expression.Constant(3), Expression.Constant(9));
        Expression<Func<int>> expr = Expression.Lambda<Func<int>>(body);
        Func<int> compiledExpression = expr.CompileAndWrap();


This will print:


No Comments

Improvements in generated SQL in EF v4.0

May 11th, 2010

Kati from EntityFramework team has published a detailed post about improvments in generated SQL in Entity Framework v4.0. The improvements are really impressive and make generated SQL perform better and and look much closer to hand-written query code. The best thing is: almost all of the improvements are provider-agnostic, so you will see automatic improvement on queries running on 3rd-party providers. In some cases (LIKE optimization) you will need to use EF4-specific version of the provider.


Tags: ,

1 Comment

Logging SQL statements in Entity Framework/Code First

April 23rd, 2010

Entity Framework/Code First feature released as part of Feature CTP 3 can work with any EF-enabled data provider.

In addition to regular providers which target databases, it is possible to use wrapping providers which can add interesting functionality, such as caching and tracing. In this post I’m going to explain how to use EFTracingProvider to produce diagnostic trace of all SQL commands executed by EF in Code First.

Setting up EFTracingConnection

In order to use the tracing provider, we need to create a wrapping DbConnection which adds logging every time the command has finished execution. The following helper will set up such connection. As you can see it can log commands to the console, log file or both. Plugging in additional logging mechanisms (such as System.Diagnostics, NLog or log4net) should be trivial.

private EFTracingConnection CreateTracingConnection()
    var connection = new EFTracingConnection
        ConnectionString = @"wrappedProvider=" + this.ProviderInvariantName + ";" + this.ConnectionString

    // set up an event which will be raised whenever command has finished executing
    connection.CommandFinished += (sender, e) =>
            if (this.LogToConsole)

            if (!string.IsNullOrEmpty(this.LogFileName))
                File.AppendAllText(this.LogFileName, e.ToTraceString() + Environment.NewLine + Environment.NewLine);
            // catch all exceptions so that we don't pass logging-related failures to user code

    return connection;

Object Context Factory

In order to efficiently manage tracing for the application we need to create a central factory class which will create ObjectContext instances for us. This is the place where we will create tracing provider connection and use it to instantiate ObjectContext.

Assuming our Object Context class is called MyContainer, the factory class will be called MyContainerFactory and will have a method called CreateContext, so the usage becomes:

MyContainerFactory factory = ...;

using (MyContainer context = factory.CreateContext())
    // use context normally

The factory will typically be be long-lived, created at the program startup and stored in a global variable or application state.

Having CreateTracingConnection(), we can now define our factory method by passing instance of the tracing connection to ContextBuilder<T>.Create():

/// <summary>
/// Creates instance of <see cref="MyContainer"/> with tracing enabled.
/// </summary>
/// <returns>Instance of <see cref="MyContainer"/>.</returns>
public MyContainer CreateContext()
    return contextBuilder.Create(this.CreateTracingConnection());

Simple, isn’t it?

Sample Project

I’ve created a tiny (100 lines of code) sample project which demonstrates this technique. Click here to download it

In the spirit of Code Only the project does not have any non-source artifacts (not even App.config file) and configures everything (model, mapping, tracing) through code:


Here is the output you get when running the application – as you can see all statements are logged to the console – log file is also created with similar output.



There is a known issue with this technique where creating databases is not supported on SqlClient provider. Other providers may or may not support this functionality depending on implementation. In general, because of that it is recommended to use unwrapped connections when using DDL APIs (CreateDatabase, DeleteDatabase, DatabaseExists()) as demonstrated in the sample.

Tags: ,


New version of EFProviderWrappers released

April 15th, 2010

EFProviderWrappers sample for Entity Framework has been updated to support new features in EFv4 and Visual Studio 2010:

Changes in this release since 3.5SP1 version:

  1. Upgraded all projects to .NET 4.0 and retargetted assemblies to use .NET Framework 4 Client Profile
  2. Removed reflection-based code to invoke CreateCommandDefinition()
  3. Moved AspNetCache to a separate assembly (which depends on .NET Framework 4 Extended Profile)
  4. Added wrappers for new provider API surface of DbProviderManifest class:
    • bool SupportsEscapingLikeArgument(out char escapeCharacter)
    • string EscapeLikeArgument(string argument)
  5. Added wrappers for new provider API surface of DbProviderServices class:
    • void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection);
    • bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection);
    • void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection);
    • string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection);
  6. Wrappers now work in partial trust – check out AspNetCachingDemo
  7. Removed Velocity adapter and demo.
  8. Recreated sample models using edmx (instead of explicit csdl/ssdl/msl)
  9. Removed the need to explicitly install the database in SQL Server – instead using |DataDirectory| and mdf files local to the project.

The sample can be downloaded from MSDN Code Gallery.

Tags: , ,


Migrating from EF POCO Adapter to Entity Framework v4.0

April 14th, 2010

Now that Visual Studio 2010 and .NET Framework 4.0 have been released, users of Entity Framework can use POCO objects with Entity Framework without the need for wrapper layers such as EFPocoAdapter. Since I know a number of people are using EFPocoAdapter in their production applications and it is not supported, I recommend they migrate to using native POCO support in EF v4.0 which is the supported way of using POCOs from now on.

This post will highlight the differences between EF and EFPOCOAdapter, which you must keep in mind when migrating your code base.

Read the rest of this entry »

Tags: ,