Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

NHibernate 2.0 beta1 was release a couple of days ago, so I thought it was time to go through some more new stuff that has been added since version 1.2.  I found a new useful helper class named CritieraTransformer which can be used to clone ICritiera queries. This is very useful if you want to perform multiple queries with small variations (in the where clause for example). It also has a useful function that adds a row count projection to a query.

Example:

var customersCritiera = session.CreateCritiera(typeof(Customer));
var totalCustomersCritiera =  CriteriaTransformer.TransformToRowCount(customersCritiera);

var inGroupCriteria = 
  CriteriaTransformer.Clone(customersCritiera)
    .Add(Expression.Eq("Group", group));

var goldenInGroupCritiera = 
  CriteriaTransformer.Clone(inGroupCriteria)
    Add(Expression.Eq("IsGold", true);                          
                
IList results = session.CreateMultiCriteria()  
     .Add(inGroupCriteria)
     .Add(goldenInGroupCritiera)
     .Add(totalCustomersCritiera)
     .List();

IList inGroupCustomers = (IList)results[0];
IList customers = (IList)results[1];
IList counts = (IList)results[2];
int count = (int)counts[0]; 

The multi criteria feature allows you peform multiple database queries in a single database call, the downside is that the IMultiCritiera interface does not support generic lists.

ASP.NET MVC Preview 3 was released today and while browsing through the code I saw something which I have seen before but never really reflected on.

protected internal ViewResult View() {
    return View(null /* viewName */, null /* masterName */, null /* model */);
}

protected internal ViewResult View(object model) {
    return View(null /* viewName */, null /* masterName */, model);
}

See how they have an inline comment with the argument name for the null arguments? This is a really nice practice as it makes function calls where nulls are passed much more readable and understandable. Functions that take in objects that can be null or booleans can often be very cryptic since you don't know what argument they represent. In some languages like ruby you can optionally name arguments:

def View(model)
  return View(viewName: nil, masterName: nil, model: nil)
end

For functions taking in booleans you have the option to instead use an enum, this can in some cases make function calls a lot more understandable. For example:

FileStream stream  = File.Open (“foo.txt”, true, false);
FileStream stream  = File.Open (“foo.txt”, CasingOptions.CaseSenstative, FileMode.Open);

For parameters that can be null you could instead use the null object pattern but this might not be feasible in many scenarios so I think that having a short comment like in the first code snippet is a nice way to handle this.

There is a new framework in the NHibernate Contrib project named NHibernate.Validator. The project began as port of the java Hibernate.Validator project and is started by Dario Quintana. This framework allows you to validate objects in a similar way to other validation frameworks except that it has out of the box integration with the NHibernate's entity lifecycle. This means that you can configure it to do validation on entity insert/updates. The integration with NHibernate is not required however.

You can specify the validation rules either as property/field attributes directly in the code or in a separate xml file with a schema similar to that used in NHibernate mapping files.

Example:

public class User
{
  public virtual int Id
  {
      get { return id; }
  }

  [NotEmpty, NotNull]
  public virtual string UserName
  {
      get { return userName; }
      set { userName = value; }
  }

  [Email]
  public virtual string Email
  {
      get { return email; }
      set { email = value; }
  }

  [Past]
  public DateTime CreatedDate
  {
    get { return createdDate; }
    set { createdDate = value; }
  }

  [Min(18, Message="You are to young!")]
  public int Age
  {
    get { return age; }
    set { age = value; }
  }

  [CreditCardNumber]
  public string CreditCardNumber
  {
    get { return creditCardNumber; }
    set { creditCardNumber = value; }
  }
  
  ///... 
}

If you don't like to clutter your code with attributes you can use the xml config option, example:

<nhv-mapping xmlns="urn:nhibernate-validator-1.0">
  <class name="NHibernate.Validator.Demo.Winforms.Model.Customer, NHibernate.Validator.Demo.Winforms">    
    <property name="FirstName">
      <not-empty/>
      <not-null/>
    </property>    
   
    <property name="Email">
      <email/>
    </property>

    <property name="Zip">
      <pattern  regex="^[A-Z0-9-]+$" message="Examples of valid matches: 234G-34DA | 3432-DF23"/>
      <pattern  regex="^....-....$" message="Must match ....-...."/>
    </property>    
    
  </class>  
</nhv-mapping>

Personally I can barley stand the NHibernate xml mapping files (don't like to poke around in xml files that much) so I think I prefer the attribute version. But it is nice to have this option. It makes it possible to validate objects in third party assemblies that you do not have the code for. There are many more validators than the ones used above and it is very easy to create custom validators.

You can configure the validation engine in code or in app/web.config, this is how you can do it in code:

NHVConfiguration nhvc = new NHVConfiguration();
nhvc.Properties[Environment.ApplyToDDL] = "false";
nhvc.Properties[Environment.AutoregisterListeners] = "true";
nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";
nhvc.Mappings.Add(new MappingConfiguration("NHibernate.ValidatorDemo.Model", null));

ValidatorEngine validator = new ValidatorEngine();
validator.Configure(nhvc);

Since NHibernate.Validator uses the event listener system I think you have to use NHibernate 2.0 if you want the NHibernate integration. To validate an object you simply use the Validate function, here is a simple example (using MonoRail):

public void Create([DataBind("user")] User user)
{
  InvalidValue[] errors = validator.Validate(user);

  if (errors.Length > 0)
  {
    Flash["errors"] = errors;
    RedirectToAction("index");
  }
  else
  {
    repository.Create(user);
  }
}

And here is the view:

<div>
    <h2>Create user</h2>    
    
    ${Html.FormToAttributed("Home", "Create", {@id: "create-form"})}
    
    <p>    
        <label for="UserName">UserName:</label>
        ${Form.TextField("user.UserName")}
        
        <label for="UserName">Email:</label>
        ${Form.TextField("user.Email")}
        
        ${Html.SubmitButton("Submit")}
    </p>
            
    ${Html.EndForm()}
    
    
    <?brail if IsDefined("errors"): ?>
        <ul>
        <?brail for error in errors: ?>
            <li>${error.PropertyName}: ${error.Message}</li>    
        <?brail end ?>
        </ul> 
    <?brail end ?>
</div>

This is of course a very simple example. You probably want to have the error message after each field and some client based validation. I think I will do another post about trying to integrate NHiberante Validator with JQuery validation.

If you want to try NHibernate validator and do not want to build it from the trunk there is a 1.0 alpha release available on sourceforge. The release contains a WinForms examples that shows how to integrate it with the WinForms error provider system.

Last week Fredrik Normén had a couple of nice posts on argument validation using C# extension methods. It got me thinking on a different approach where a method interceptor could handle the validation.

First a short recap on argument validation. I guess everyone have seen or written code with some kind of argument validation, like this for example:

public void Add(string value)
{
  if (string.IsNullOrEmpty(value)) 
      throw new ArgumentException("The value can't be null or empty", "value");
    
  ///...
}

To make argument validation easier I have (to a small extent) used a modified version of this design by contract utility class. This utility class lets you write argument validation like this:

public void Add(string value)
{
  Check.Require(value != null, "value should not be null");
    
  ///...
  
  Check.Ensure(Count > 0);
}

So this got me thinking on how you could handle argument validation using method interception. With a method interceptor you could inspect the function arguments checking for validation attributes. I envisioned code looking like this: 

[Ensure(() => this.Count > 0)]
public void Register([NotNull] string name, [InRange(5,10)] int value)
{
  ///...
}

Getting the ensure post condition to work like that will be impossible since you can only use constant expressions in attribute constructors. This is something I think they should look at for C# 4.0, being able to define lambdas in attribute arguments would make interesting scenarios possible (like this). The NotNull and InRange attributes were very simple to implement: 

public abstract class ArgumentValidationAttribute : Attribute
{        
  public abstract void Validate(object value, string argumentName);
}

[AttributeUsage(AttributeTargets.Parameter)]
public class NotNullAttribute : ArgumentValidationAttribute
{
  public override void Validate(object value, string argumentName)
  {
    if (value == null)
    {
        throw new ArgumentNullException(argumentName);
    }
  }    
}    

[AttributeUsage(AttributeTargets.Parameter)]
public class InRangeAttribute : ArgumentValidationAttribute
{
  private int min;
  private int max;

  public InRangeAttribute(int min, int max)
  {
    this.min = min;
    this.max = max;
  }

  public override void Validate(object value, string argumentName)
  {
    int intValue = (int)value;
    if (intValue < min || intValue > max)
    {
      throw new ArgumentOutOfRangeException(argumentName, string.Format("min={0}, max={1}", min, max));
    }
  }
}

This is of course the easy part. It is the actual interceptor that is making the magic happen. This implementation is just a proof of concept, and not optimal from a performance stand point.

public class ValidationInterceptor : IInterceptor
{
  public void Intercept(IInvocation invocation)
  {
    ParameterInfo[] parameters = invocation.Method.GetParameters(); 
    for (int index = 0; index < parameters.Length; index++)
    {
      var paramInfo = parameters[index];
      var attributes = paramInfo.GetCustomAttributes(typeof(ArgumentValidationAttribute), false);

      if (attributes.Length == 0)
        continue;

      foreach (ArgumentValidationAttribute attr in attributes)
      {    
        attr.Validate(invocation.Arguments[index], paramInfo.Name);
      }            
    }

    invocation.Proceed();
  }        
}

To make this interceptor more feasible for production you would probably have to add some smart caching mechanism. This interceptor based argument validation is of course somewhat limited in applicability. You have to use a dynamic proxy generator to get the interceptor functionality and only interface and virtual functions can be intercepted. But it is an interesting idea and shows another nice usage scenario for method interception.

The concept of being able to intercept method calls is something that would be great if it was built into a future version of the CLR runtime. That way static and non virtual methods could be intercepted. It is a nice way to implement cross-cutting concerns (like validation). But until then we will have to live with proxy generators, it works nicely for interfaces:

public interface IRegistrationService
{
  void Register([NotNull] string name, [InRange(5, 10)] int value);

  void Register([NotNullOrEmpty] string name);
}

If you specify the attributes on an interface you do not need to duplicate them on the implementation methods! A small update to the interceptor to support validation of the return value would allow something like this:

public interface IUserRepository
{
  [return: NotNull]
  User GetById([GreaterThanZero] int id);
  
  ///...
}

The syntax for attributes on return values are kind of funky. If Spec# isn't the future (I hope it is) then maybe something like this can be :)

The ideas and concepts that the Microsoft research team has realized in spec# are too great not to be included in a future version of C# !

Just look a this example:

public static int Subtract(int x, int y)
     requires x > y;
     ensures result > y;
{
     return x - y;
}

It is not only the runtime aspects of spec# that are exiting. It is the amazing level of static analysis that they have implemented that at compile time validates (across many method boundaries) that requirements are uphold.

C# has really evolved a lot in the last two iterations (especially in 3.0), and think this fast evolution has given it a good edge compared to other static languages (java). But why stop now? Here are a few more things I would like in C# 4.0 :)

Extensible compilation pipeline:

The Boo .NET language has this concept of an extensible compilation pipeline that allows for really powerful usage scenarios. With it you can extend the language with new keyword constructs and attributes that actually manipulate the abstract syntax tree (AST). Here is an example where I have extended Boo with some constructs for design by contract:

[ensures(total > 0)] 
def Add(int value):
    requires value > 0
    total += value

Extending the Boo language like this is very trivial. For example the requires keyword is implemented like this:

macro requires:
  return [|
    if $(requires.Arguments[0]) == false:
        raise ArgumentException("requires precondition failed")
    |]

This is just a simple example, you can do more powerful stuff. A Boo macro is very different from C++ macros. The Boo macros operate on the compiler's AST and can query the object model and modify it in very powerful ways. The open compiler architecture makes Boo a language suitable for writing domain specific languages. I doubt that something like this will be implemented in C# though since new compiler features are more likely to break existing implementations. Something I think the C# team are not allowed to do.

Dynamic method invocation and duck typing:

If a class implements the IQuackFu interface in Boo you can call methods on it that are resolved at runtime. This is similar to method missing in ruby. The IQuackFu interface looks like this:

public interface IQuackFu
{
  object QuackGet(string name, object[] parameters);
  object QuackSet(string name, object[] parameters, object value);
  object QuackInvoke(string name, params object[] args);
}

This interface can for example be used as front to an xml document, allowing you to access elements as properties. I think the C# team is actually considering something like this if you are to believe the rumours from the MVP Summit.

Anyone else having ideas or a whish list for C# 4.0?

Nate Kohari informed me that he fixed the performance issue that I discovered in my last test, so I thought I rerun the benchmark against the trunk version (revision 62) of Ninject.

I have also included another new container named Autofac, written by Nicholas Blumhardt and Rinat Abdullin.

This container has nice list of features, here are a few:

  • Autowiring (with out any intrusive attributes)
  • XML Configuration Support
  • Nice C# registration API (including possibility to create components with expressions)
  • Module system (nice way to structure parts of your application)
  • Nested containers

The registration API is at first glance like any other IoC container except it also provides the ability to override the autowiring by defining how components are created by using lambda expressions. Here is an example:

// using autowiring
builder.Register<UserController>().FactoryScoped();
// using expressions
builder.Register(c => new UserController(c.Resolve<IUserRepository>(), c.Resolve<IAuthentificationService>()))
  .FactoryScoped();

The second method could potentially be a lot faster since in it you create a anonymous method that creates the object directly. There is a lot more code to write and if you change the constructor you need to update the registration code, so I am not sure you would want to use it to for most components. To be fair to the other containers in the test I tested Autofac with both autowiring registration and with expression based registration. For more detail on how the benchmark works please view the first benchmark post.

Another interesting feature of Autofac is it's support for nested containers with predicable component cleanup. 

var container = // ...
using (var context = container.CreateInnerContainer())
{
  var controller = context.Resolve<IController>();
  controller.Execute(); // use controller..
}

In the above example the controller and all it's dependencies that implements IDisposable will be disposed.

Here are the results:

IoCSingleton_Autofac

IoCTransient_Autofac

It is nice to see that the Ninject problem has been solved. When using Autofacs expression (lambda) based registration API the results are, not surprising, a lot quicker than the other containers. I would have almost through that the performance difference was going be bigger, seeing how fast the new operator was in my first benchmark (where I made a crude comparison with using the new operator directly to create all the instances).  

My conclusion is the same as after the first test, the performance difference is not significant to warrant consideration when choosing a IoC container. Unless you create a incredibly large amount of transient components (not recommended), then maybe use Autofac :)

It was fun to try out Autofac, it is looking like an interesting contender, and might even replace Castle Windsor as my favorite. I doubt it though, Castle Windsor probably has the largest user base and I am pretty familiar with it's codebase / extension points. But who knows, you shouldn't always stick to what you know :)

For the benchmark code: IoCBenchmark_ReRevisted.zip

If you want to automate some of your manual integration testing I can highly recommend WatiN. It is a great library for doing browser automation. The new version allows you to automate Internet Explorer and Firefox through a common interface.

example:

[Fact]
public void SearchForCodingInstinctOnGoogle()
{
  using (IBrowser ie = BrowserFactory.Create(BrowserType.InternetExplorer))
  {
    ie.GoTo("http://www.google.com");
    ie.TextField(Find.ByName("q")).Value = "Coding Instinct";
    ie.Button(Find.ByName("btnG")).Click();
    Assert.True(ie.ContainsText("Coding Instinct"));
  }
}

I am using xUnit.NET in the above example (Fact = Test). xUnit.NET has been mentioned in a lot of blogs lately and I think for good reasons. It comes bundled with a very nice set of extensions that are very useful, especially for integration testing.

ExcelData:

One of the extensions that comes with xUnit is an attribute that lets you fetch test data from an excel file, xUnit will then execute your test method for each row in the excel file. Here is an interesting usage scenario:

[Theory, ExcelData(@"Resources\PortalUrls.xls", "select * from PortalUrls")]
public void UrlShowsExptectedContent(string url, string contentText, bool requireLogin)
{
  InitBrowser(url);
  
  if (requireLogin)
  {
    LoginAction.WithAS();
  }

  Assert.True(Browser.Text.Contains(contentText), string.Format("\"{0}\" was not found", contentText));
}

My current customer is using a portal application to host a number of separate applications (that use a common SSO). With this simple test I was able to check all portal URLs and with a very simple validation check that the applications (and the login) was up and running.

The excel file:

In the excel file you must use the function "Name a Range". This function can be found by selecting the table, including the header and right clicking. It is also found under the "Formulas" tab (Define Name, Name Manager).

The test above is of course a very simple test, It only checks that the portal is configured correctly and that all applications are up and running, but it is a good start. Now I can go into each application/feature and write automated tests for each of the manual test cases.

UI test fragility:

When writing browser tests you need to do a lot of html element selections so the tests become very fragile to UI changes, this is especially true for WebForm applications where element names and ids are constantly changed for minor UI changes.

To combat this problem I tend to place most of the element selections in static helper classes. I also use a RegEx to identify elements. The reason for using a RegEx is to ignore a large part of the id prefix that the WebForm html renderer so gladly adds. example:

public class LoginAction : ActionBase
{
  public static void WithAS()
  {
    Browser.TextField(new Regex(".*txtUserName")).Value = "xxxx";
    Browser.TextField(new Regex(".*txtPassword")).Value = "xxxx";
    Browser.Button(new Regex(".*btnLogin")).Click();
  }
}

There are many more useful xUnit extension attributes, for example: InlineData, PropertyData and SqlServerData. For more information on WatiN and xUnit.NET here are some links:

In most applications you usually store and cache some user information in a session object. Most actions are dependent on this information, which means that many services require this information. This problem can be solved using different approaches. What I usually end up with is creating a user ticket class which holds maybe a subset of the user information (or the complete user class) and other session specific information. The simplest approach is then to pass this object along to each service / method that needs it:

public class WishListService
{
  private IWishListRepository wishListRepository;

  public WishListService(IWishListRepository wishListRepository)
  {
    this.wishListRepository = wishListRepository;
  }

  public void AddToWishList(IUserTicket ticket, Product product)
  {
    // handle all the important stuff
  }
}

The problem with this approach is that all callers need to fetch the user ticket. If you have deep method stacks and the deepest component needs the session information then all methods needs to pass the object along.

A sometimes nicer approach is to let the components fetch the session information on their own (through an interface):

public class WishListService
{
  private IWishListRepository wishListRepository;
  private ITicketAccessor ticketAccessor;

  public WishListService(IWishListRepository wishListRepository, ITicketAccessor ticketAccessor)
  {
    this.wishListRepository = wishListRepository;
    this.ticketAccessor = ticketAccessor;
  }

  public void AddToWishList(Product product)
  {
    IUserTicket ticket = ticketAccessor.Current();
    // handle all the important stuff
  }
}

This approach makes the component easier to use and the method calls are simpler, dependencies to the session (ticket) information is handled by the ITicketAccessor which can be inject by a IoC container.

Another approach is to have a static RuntimeContext class which static properties to access the session information from anywhere in your application:

public class RuntimeContext
{
  private const string KEY_TICKET = "RuntimeContext.Ticket";        

  /// <summary>
  /// Used to access the ticket for the current request
  /// </summary>
  public static IUserTicket Ticket
  {
    get
    {
      // try local execution context first
      IUserTicket ticket = Local.Data[KEY_TICKET] as IUserTicket;
      if (ticket != null)
        return ticket;

      // try session
      if (Local.RunningInWeb && HttpContext.Current.Session != null)
      {
        ticket = HttpContext.Current.Session[KEY_TICKET] as IUserTicket;
        // cache in local 
        if (ticket != null)
          Local.Data[KEY_TICKET] = ticket;
      }

      return ticket;
    }
    set
    {
      Local.Data[KEY_TICKET] = value;

      // store in session if running in web 
      if (Local.RunningInWeb)
      {
        HttpContext.Current.Session[KEY_TICKET] = value;
      }
    }
  }
}

The Local class in the above code is an abstraction over HttpContext.Current.Items and Thread data depending on if the code is being run in web context or not. This last approach is very easy to work with but you have less control over where and how the data is accessed.

There is also Thread.CurrentPrincipal which is a good to use, especially for user authorization. I am not sure which of the approaches I like more, the second one is probably the best one from a purist / TDD point of view. I will post a question in the ALT.NET mailing list to find out what solutions smarter people than me have arrived at.

I am currently trying to prototype how a portal application could be build using ASP.NET MVC (I would prefer to use MonoRail but can't).

There is a big problem in the way the default implementation of the IControllerFactory is handling controller types. It is using a simple dictionary to map controller names to controller types. The key in the dictionary is only the controller name (like "Home" for a HomeController type), this means that you cannot have controllers with the same type name (no matter what namespace or assembly the controller is in). In big applications you probably want to group your controllers into areas in which case a controller of the same name could be likely.

So currently it is not possible to group controllers into what MonoRail calls Areas.  To do this you would have to implement IControllerFactory from scratch since the root of the problem is the ControllerTypeCache which is being used by the DefaultControllerFactory, and the ControllerTypeCache is of course internal and sealed. There are probably other changes that would need to be made to introduce the concept of areas.

There is a extensibility point named IViewLocator used by the WebFormViewEngine which can be exchanged to change the way the view engine locates views. A simple example:

public class PortalViewLocator : ViewLocator
{
      public PortalViewLocator ()
      {
          ViewLocationFormats = new[] {
              "~/CustomViewDir/{1}/{0}.aspx",
              "~/CustomViewDir/{1}/{0}.ascx",
              "~/CustomViewDir/Shared/{0}.aspx",
              "~/CustomViewDir/Shared/{0}.ascx"
          };
          MasterLocationFormats = new[] {
              "~/CustomViewDir/{1}/{0}.master",
              "~/CustomViewDir/Shared/{0}.master"
          };
      }
}

To solve the problem with controller areas MonoRail has something it calls a Controller Tree which serves the same role as the ASP.NET MVC ControllerTypeCache. In MonoRail the area of a controller is specified using the optional ControllerDetails attribute:

using Castle.MonoRail.Framework;

[ControllerDetails(Area="admin")]
public class UsersController : Controller
{
    public void Index()
    {
    }
}
With the default routing the above index function would correspond the URL "/admin/users/index". If ASP.NET MVC adopted a similar approach it could check for an attribute in it's clever Html helper functions which takes in lambda functions (i.e. expression trees):
Html.ActionLink<UserController>(c => c.Register(), "Register now!")

I understand that they want the keep the ASP.NET MVC framework as lightweight and simple as possible and only add features when they are really needed (which is a good philosophy) and have extensibility points for specific scenarios. However I think that a concept like controller areas should built into the framework.

I also hope they start looking at scenarios where you might want to create a modular web applications composed of multiple sub projects. I guess it would be possible to do that now but it would be very hard and would require you to replace many of the default implementations in the MVC framework.

Microsoft seems to be about reinventing the wheel again, Krzysztof blogged about a new framework being worked on with these goals:

MEF is a set of features referred in the academic community and in the industry as a Naming and Activation Service (returns an object given a “name”), Dependency Injection (DI) framework, and a Structural Type System (duck typing)

They are currently just experimenting with different approaches and a CTP is likely to be released soon. The example that Krzysztof showed might not be indicative of how it will eventually turn out but it doesn't look very promising (requiring property attributes to declare dependencies, etc).

The approach I was hoping that Microsoft would take was to try and incorporate the concepts of an IoC container but make the concrete container pluggable. Maybe even to introduce this concept on the CLR level or maybe just C#/VB. Maybe something like this:

this.authService = resolve IAuthentificationService

If C# could introduce a new keyword (resolve) that would request a component from a container. The .NET framework would probably need a basic implementation of the container but it should be completely pluggable so you can exchange it with for example Castle Windsor or StructureMap. I haven't really thought this through but If Microsoft is going to include an IoC Container in the core framework this is the approach I wish they would at least try (maybe they have?).

Someone (Joshua) mentioned Ninject in the comments to in my IoC Benchmark. I hadn't heard of this project before but after checking out ninject.org and seeing the project slogan "lighning-fast dependency injection" I felt that it deserved be included in the test.

I am not sure what the slogan refers to though, lightning-fast usage and setup or runtime performance? Anyway it has a nice fluent registration API:

Bind<IUserRepository>()
  .To<LdapUserRepository>()
  .Using<SingletonBehavior>();
  
Bind<IAuthentificationService>()
  .To<DefaultAuthentificationService>()
  .Using<SingletonBehavior>();

Bind<UserController>()
  .ToSelf()
  .Using<SingletonBehavior>(); 

The tests were made with the release build of RC1 downloaded from the project homepage. I was kind of surprised by the results:

IoCSingleton_WithNinject
IoCTransient_WithNinject

I might be doing something wrong here but this is the result I got. For the transient case there seems to be a big memory leak. The Ninject kernel seems to keep references to transient objects. I tried the kernel's Release function but the memory leak was still evident.

Just to check that it was not something wrong with my code I did a profiling trace with JetBrains dotTrace:

NinjectTrace

It could still be me setting something up in the wrong way, but it looks like it's a bug in the Ninject Core.

Just a note: I think that doing premature optimization can result in bad design and architecture. The reason I did this and the previous test was not to find the fastest container, it was firstly to get a change to play with new (to me) containers, and secondly to see if there were any significant performance difference between them worthy of taking into account when choosing a container.

My conclusion in the previous test was that the difference in performance was not big enough to be relevant compared to other aspects of the containers, like how much you like the API or the features. The Ninject result for the transient test above is very significant, however it is probably caused by a memory bug in the release candidate and will likely be fixed in the next release. If you disregard this bug I actually kind of liked Ninject, it a had a nice API and a way of doing things, but it's slogan is currently a little misleading :)

For the complete code: IoCBenchmark_Revisited.zip

Updated (2008-05-05):

Nate Kohari has fixed the performance issue, the results are now inline with the other containers. For the new results (which also includes Autofac) please view this post.

Here is an interesting problem, try writing the bellow Linq query using lambda expressions.

var usersWithBigOrders =
  from usr in context.Users
  from ordr in usr.Orders
  where ordr.Total > 10
  select usr;

I ran into this interesting Linq question when writing yesterday's post. To figure out what the above query actually does I used Reflector. The code bellow is what the C# compiler will generate (when reverted back from IL to C#):

context.Users.SelectMany(
Expression.Lambda<Func<User, IEnumerable<Order>>>(
  Expression.Property(CS$0$0000 = Expression.Parameter(typeof(User), "user"),
   (MethodInfo) methodof(User.get_Orders)), new ParameterExpression[] { CS$0$0000 }),
    Expression.Lambda(
      Expression.New((ConstructorInfo) methodof(<>f__AnonymousType0<User, Order>..ctor,
       <>f__AnonymousType0<User, Order>), 
       new Expression[] { CS$0$0000 = Expression.Parameter(typeof(User), "user"), 
       CS$0$0002 = Expression.Parameter(typeof(Order), "order") }, 
       new MethodInfo[] { (MethodInfo) methodof(<>f__AnonymousType0<User, Order>.get_user, 
       <>f__AnonymousType0<User, Order>), 
       (MethodInfo) methodof(<>f__AnonymousType0<User, Order>.get_order, 
       <>f__AnonymousType0<User, Order>) }), 
       new ParameterExpression[] { CS$0$0000, CS$0$0002 }))
.Where(Expression.Lambda(Expression.GreaterThan(
  Expression.Property(Expression.Property(
    CS$0$0000 = Expression.Parameter(typeof(<>f__AnonymousType0<User, Order>),
     "<>h__TransparentIdentifier0"),
      (MethodInfo) methodof(<>f__AnonymousType0<User, Order>.get_order,
       <>f__AnonymousType0<User, Order>)), (MethodInfo) methodof(Order.get_Total)), 
       Expression.Convert(Expression.Constant(10, typeof(int)), typeof(int?))), 
       new ParameterExpression[] { CS$0$0000 }))
        .Select(Expression.Lambda(Expression.Property(
          CS$0$0000 = Expression.Parameter(typeof(<>f__AnonymousType0<User, Order>),
           "<>h__TransparentIdentifier0"), 
           (MethodInfo) methodof(<>f__AnonymousType0<User, Order>.get_user,
            <>f__AnonymousType0<User, Order>)), 
            new ParameterExpression[] { CS$0$0000 })).ToList<User>();

It is quite surprising how much code that the compiler actually generates. The reason for the amount of code above is because the LinqToSql table class implements IQueryable. When the compiler detects this interface instead of generating IL that performs the query it will generate IL that builds up an expression tree that describes the query.

So in order to understand what the above code actually describes I wrote the same Linq query but instead of querying LinqToSql I queried a normal .NET collection. The code that Reflector generates now looks like this:

List<User> users = new List<User>();
if (CS$<>9__CachedAnonymousMethodDelegate6 == null)
{
    CS$<>9__CachedAnonymousMethodDelegate6 = delegate (User usr) {
        return usr.Orders;
    };
}
if (CS$<>9__CachedAnonymousMethodDelegate7 == null)
{
    CS$<>9__CachedAnonymousMethodDelegate7 = delegate (User usr, Order ordr) {
        return new { usr = usr, ordr = ordr };
    };
}
if (CS$<>9__CachedAnonymousMethodDelegate8 == null)
{
    CS$<>9__CachedAnonymousMethodDelegate8 = delegate (<>f__AnonymousType0<User, Order> <>h__TransparentIdentifier0) {
        return <>h__TransparentIdentifier0.ordr.Total > 10;
    };
}
if (CS$<>9__CachedAnonymousMethodDelegate9 == null)
{
    CS$<>9__CachedAnonymousMethodDelegate9 = delegate (<>f__AnonymousType0<User, Order> <>h__TransparentIdentifier0) {
        return <>h__TransparentIdentifier0.usr;
    };
}
IEnumerable<User> usersWithBigOrders = users
  .SelectMany(CS$<>9__CachedAnonymousMethodDelegate6, CS$<>9__CachedAnonymousMethodDelegate7)
  .Where(CS$<>9__CachedAnonymousMethodDelegate8)
  .Select(CS$<>9__CachedAnonymousMethodDelegate9);

This is a lot more understandable, but still it took a while to figure out exactly what the above code was doing. Here are both queries, one using Linq syntax the other using the lambda syntax, they are equivalent.

var usersWithBigOrders =
  from usr in context.Users
  from ordr in usr.Orders
  where ordr.Total > 10
  select usr;

var usersWithBigOrders = context.Users
  .SelectMany(user => user.Orders,(user, order) => new {User = user, Order = order})
  .Where(anonType => anonType.Order.Total > 10)
  .Select(anonType => anonType.User);

One of the biggest strengths of O/R mappers is that many have object-oriented "query by criteria" API. I will show what I mean by that in a bit. But to explain why I think a criteria API is such a great thing I will show the alternatives first.

Lets take a common search form scenario where a user can specify a number of customer filtering options like date added, name, the customer should have an address, the customer should be linked to a specific salesman, etc. If you were forced to use a stored procedure how would you implement this query?

I have seen a couple of solutions to problems like this, here is one that is really bad:

IF @name = ''
BEGIN 
     --- the whole query for this case 
END    
ELSE IF @name <> '' AND @shouldHaveAddress IS NOT NULL 
BEGIN 
    --- the whole query for this case 
END 
ELSE IF @name <> '' AND @shouldHaveAddress IS NOT NULL AND @salesmanNr <> '' 
    --- the whole query for this case 
END

Here the whole query is duplicated for each possible parameter mutation. I have seen a stored procedure like this recently that duplicated a very long query about 10 times (with very small variations in the where and join clauses).

Another solution is to complicate the query with embedded IFs, CASE and additional OR statements. But this solution does not only make the query unintelligible but also I think has some limitations. The solution that I see many arrive at is to build the query using string concatenation.

SET @sqlSelect = 'SELECT distinct ' + @NEWLINE + ' ' + @returnColumns + @NEWLINE
SET @sqlFrom = ' FROM Customers cust' + @NEWLINE
IF @companies is NOT NULL
BEGIN
  SET @sqlFROM = @sqlFROM + ' JOIN Companies comp on comp.Id=cust.CompanyId' + @NEWLINE
  SET @sqlFROM = @sqlFROM + ' LEFT JOIN Addresses addr on addr.Id=cust.AddressId ' + @NEWLINE  
END
IF @salesmanId IS NOT NULL
BEGIN
  SET @sqlFROM = @sqlFROM + ' JOIN Salesmen sal on sal.Id=' + @salesmanId 
END
...
..
.

I actually think that building up the query like this is not all that bad, however I would do it in C# and skip the stored procedure. The reason I prefer this approach is that it there is less duplication and because it is somewhat easier to maintain. But it is far from what we want!

So how do can we handle this via the nhibernate query api?

ICriteria query = session.CreateCriteria(typeof(Employee));

if (searchOptions.FirstName != null)
{
  query.Add(Expression.Eq("FirstName", searchOptions.FirstName));
}

if (!searchOptions.LastName != null)
{
  query.Add(Expression.Eq("LastName", searchOptions.LastName));
}

if (searchOptions.PhoneNumber != null)
{
  query.CreateCriteria("PhoneNumbers")
    .Add(Expression.Like("Number", searchOptions.PhoneNumber + "%"));
}
return query.List<Employee>();

The nhibernate criteria api might be verbose for simple scenarios compared to a SQL query in a string, but it is scenarios like the above that it really shines :) But wait it can be better. If you use Ayende's great NHibernate Query Generator (NHQ) you can do this:

QueryBuilder<Employee> query = new QueryBuilder<Employee>();

if (options.FirstName != null)
{
  query &= Where.Employee.FirstName == options.FirstName;
}

if (options.LastName != null)
{
  query &= Where.Employee.LastName == options.LastName;
}

if (options.PhoneNumber != null)
{
  query &= Where.Employee.PhoneNumbers.Number.Like(options.PhoneNumber, MatchMode.Start);
}            

return Repository<Employee>.FindAll(query, OrderBy.Employee.LastName.Desc);

NHQ is a very clever code-gen util that you setup as a post-build step. It generates the Where/QueryBuilder classes from the nhibernate mapping files. The result is that you do not need any strings in your queries! More commonly you use it like this:

return Repository<User>.FindAll(Where.User.Name == name);

I think it comes very close to using LINQ. So to end this post I guess I need to show how the above query would look with LINQ, because LINQ to SQL handles the above scenario pretty well.

IQueryable<Employee> query = linqContext.Employees;

if (options.FirstName != null)
{
  query = query.Where(emp => emp.FirstName == options.FirstName);
}

if (options.LastName != null)
{
  query = employees.Where(emp => emp.LastName == options.LastName);
}

if (options.PhoneNumber != null)
{
  query = from emp in query
	  from phoneNr in emp.PhoneNumbers
	  where phoneNr.Number.StartsWith(options.PhoneNumber)
	  select emp;
}            

return employees.ToList();

The above code is nice, but I think querying across relations is handled nicer in the nhibernate critiera api especially when using NHQ. Well that is all, now you know why I think a criteria API is are one of the mayor reasons to use an O/R mapper.

I don't use NHibernate for everything, so when I do use the ADO.NET API directly I like to use a small static utility class that lets me do this:

Db.Transaction(delegate(SqlCommand cmd)
{
    cmd.CommandText = "DELETE FROM LogEntries WHERE DateCreated < @DateCreated";
    cmd.Parameters.AddWithValue("@DateCreated", DateTime.Now.Subtract(TimeSpan.FromDays(30)));
    cmd.ExecuteNonQuery();
});
This simple static method takes care of so much of the repetative code that you never want to write twice, like setting up the connection, registering the transaction, handling the try catch and commit/rollback. Here is the code for the Transaction method:
public static void Transaction(SqlCommandHandler handler)
{
    using (SqlConnection connection = new SqlConnection(Settings.CommonDb))
    {
        connection.Open();

        SqlTransaction tx = connection.BeginTransaction(IsolationLevel.ReadCommitted);
        try
        {
            using (SqlCommand cmd = connection.CreateCommand())
            {
                cmd.Transaction = tx;
                handler(cmd);
            }
            tx.Commit();
        }
        catch
        {
            tx.Rollback();
            throw;
        }
    }
}

The C# language became a lot more power in the 2.0 update when anonymous methods (i.e. closures) were introduced, and the 3.0 update that introduced the lambda syntax made it even better. If it weren't for these new features of C# I would probably be compelled to move to ruby!

There are a number of inversion of control containers out there so I thought it would be an interesting experiment to do a simple benchmark. There are different ways that one can instantiate a type in .NET, for example via the new operator, Activator, GetUninitializedObject and Dynamic Method. The performance difference between these methods are in some cases quite high, maybe the same is true for these IoC containers? Granted IoC containers do more than just create objects so other factors will probably play a big role in the results.

So here are the contestants:

I have been using Castle Windsor since 2005 and I think it is the best of the bunch, so I guess I am unconsciously biased toward Windsor.  However I will try to make this benchmark as objective as I can.

The scenario for this test:

  • Have each IoC container resolve a UserController 1000 000 times
  • The UserController will have two constructor dependencies
  • Run the test with transient (new instance for each resolve) and singleton components

The UserController looks like this:

public class UserController
{
    private IUserRepository repository;
    private IAuthentificationService authService;

    public UserController(IUserRepository repository, IAuthentificationService authService)
    {
        this.repository = repository;
        this.authService = authService;
    }
}

I have also a general container interface that the benchmark engine will use. Each container will implement this interface.

public interface IContainer
{
    string Name { get; }

    T Resolve<T>();
    
    void SetupForTransientTest();
    void SetupForSingletonTest();
}

All tests used the latest released version of each library. Before you interpret these charts please observe that the measurement is for one million component resolves which means the actual time difference between each container is actually very small.

Here are the results when all components were setup as singletons:

IoCSingleton

Here are the results when all components were setup as transient:

IoCTransient

So what does these charts tell us? Lets take the biggest difference in the transient case, Spring.NET took 44.149 seconds and Unity took 8.164 seconds, what is the actual difference when resolving a single instance?

  Spring.NET : 44.149 / 1000000 = 0.000044149 seconds
  Unity      :  8.164 / 1000000 = 0.000008164 seconds

So the actual difference is only about 36 microseconds. Another way to put these values into perspective is to compare against the new operator. I created a NewOperatorContainer with a resolve method that looks like this:

public T Resolve<T>()
{
    object o = new UserController(new LdapUserRepository(), new DefaultAuthentificationService());
    return (T) o;
}

OK, comparing the above with an inversion of control container is like comparing apples to oranges, an IoC handles so much more than just object creation. Also an IoC cannot use the new operator directly but must use one of the other methods. My guess is that all IoC containers in this test uses an approach which involve IL Generation which if cashed comes close to using the new operator directly. Anyway I think it will show just how small the difference between the real IoC containers are. In order to visualize this I needed to invert the values so that high means fast and low means slow.

IoCInversed

Update: The above chart can be very misleading. The x-axis is not seconds but 1/s. I hope it shows that the difference between the containers are very small compared to instantiating the objects manually.

OK, can we draw any conclusion from the test? Well I think we can say that performance should not be an issue when choosing one of these IoC containers. The difference is too small. When you choose which container to use you should consider other aspects, like how invasive the container is to they way you want to work.

For the complete code: IoCBenchmark.zip

The new statistics class in Hibernate 2.0 is a great tool to use for monitoring potential performance problems with your app. The class exposes a large number of counters and measurements. Here are some highlights of what is available:

  • EntityDeleteCount
  • EntityInsertCount
  • EntityLoadCount
  • EntityUpdateCount
  • QueryExecutionCount
  • QueryExecutionMaxTime
  • QueryExecutionMaxTimeQueryString
  • QueryCacheHitCount
  • ConnectCount
  • SessionCloseCount
  • SessionOpenCount
  • CollectionLoadCount
  • CollectionUpdateCount
  • CollectionRemoveCount
  • Queries
  • PrepareStatementCount

The statistics engine can be turned on/off dynamically with the IsStatisticsEnabled property and you can get statistics on specific entities as well.

Just to try this out I created a MonoRail filter that checks for "nhibstats" in the query parameters of the request. If the parameter is found it will turn on the nhibernate statistics, this is done before the controller action is executed. After the action as completed it will add the stats data to the PropertyBag so the view can access it.

public class NHibernateStatsFilter : IFilter
{
    public bool Perform(ExecuteWhen exec, IEngineContext context, IController controller,
                        IControllerContext controllerContext)
    {
        if (context.Request["nhibstats"] == null)
            return; 
        
        if (exec == ExecuteWhen.BeforeAction)
        {
            sessionFactory.Statistics.Clear();
            sessionFactory.Statistics.IsStatisticsEnabled = true;
        }
        else if (exec == ExecuteWhen.AfterAction)
        {
            controllerContext.PropertyBag["nhibernate_stats"] = sessionFactory.Statistics;
            sessionFactory.Statistics.IsStatisticsEnabled = false;
        }
    }
}

I use the same filter for both the before and after action "events", this means that you have to specify the filter attribute like this:
[Filter(ExecuteWhen.BeforeAction | ExecuteWhen.AfterAction, typeof(NHibernateStatsFilter))]
public class BaseController : Controller
{
        
}
Now you can add to your top layout view something like this:
<?brail if IsDefined("nhibernate_stats"): ?>
    <dl>
        <dt>EntityInsertCount</dt>
        <dd>${nhibernate_stats.EntityInsertCount}</dd>        
        <dt>EntityUpdateCount</dt>
        <dd>${nhibernate_stats.EntityUpdateCount}</dd>        
        .
        ..
        ...
    </dl>
<?brail end ?>

I think this could be really useful. Now you don't have to open SQL Profiler whenever you want to know what NHibernate is up to!

It took some time but Slick Code Search is now finally published on codeplex. There is a binary release available on codeplex and the source is available via Google's subversion hosting: http://slickcodesearch.googlecode.com/svn/trunk/

So what is this thing? Well it is a small WPF application that lets you index and search through your source files (C# only for now), in short a Google desktop for your local code.

slickcode3

When you start it up you get this floating textbox where you can type in a Lucene search query. Your can search for both type and method names. Currently you need to press the enter key to execute the search and update the result list.

Example Lucene queries:

  • t:ISessi*   Searching for a type beginning with "ISessi"
  • m:Get*     Searching for all types that have a method beginning with "Get"

For a complete description of the Lucene syntax: http://lucene.apache.org/java/docs/queryparsersyntax.html

The result list looks like this:

slickcode4

You can navigate the result list by using the up/down keys. To expand/collapse an item just press the left/right keys. Once an item is expanded the type's methods will be listed and you can now navigate those with the up/down keys. If you press right when a method is highlighted a code window will appear with that method in focus.

You can also press the enter key while having a result item highlighted, this will open that file in a program you can specify in the options dialog.

slickcode5

The above screenshot shows how an item looks while it is expanded. If anyone has any good ideas for new features then please add them in the issue tracker on codeplex. I think this app needs something more to be really useful.

The code for this app is a little strange. It started as a "learn WPF demo" app that grew to something more. Then I tried a model view presenter pattern with castle windsor integration just for fun, but this refactoring is more like an afterthought and it shows in the code.

I actually started this app along time ago after seeing a screencast by Ayende where he developed a code search engine. Some of the basics of what he did in that cast can be found in Slick Code Search (a SharpDevelop library that handles the CSharp file parsing and Lucene.NET for the text searching).

NHibernate 2.0 Alpha1 was released a few days ago and the 2.0 version brings a lot of new features. There is a completly new event / listener system that can be used for all sorts of cross-cutting concerns. A basic example would be to register a save/update listener that would update some common fields (like ModifiedBy, ModifiedDate).

In order to use the event system you need to create a class that either inherits from a default nhibernate event listener or from the many event interfaces. Here is an example:

using NHibernate.Event;
using NHibernate.Event.Default;

public class CustomSaveEventListener : DefaultSaveEventListener
{
    protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
    {
        IEntity entity = evt.Entity as IEntity;
        if (entity != null)
            ProcessEntityBeforeInsert(entity)