Browsing Posts published in June, 2008

Many people have asked over the past few months whether I will be offering a public course on NHibernate. The answer is now “Yes!” and it will be debuting in Calgary in August.

If you’re interested in OR/M with NHibernate and can’t come to Calgary, then maybe the course can come to you! Email me for more information on bringing the course to your city. I also offer this course privately if your company prefers that format. Once again, email me for more information.

If you’re interested, you can register for the Calgary course here (credit card). Please email me directly if you wish to pay via purchase order.

Object-Relational Mapping with NHibernate

Location The Westin Calgary
320 4th Avenue SW
Calgary, AB T2P 2S6
(map)
Dates Tuesday, August 26, 2008 to Thursday, August 28, 2008

Overview

Object-relational Mapping with NHibernate is an intensive 3-day course designed to introduce students to the core concepts of object-relational mapping (OR/M), such as querying and persisting objects to a relational database and mapping objects, collections, and inheritance relationships. The course will cover querying with the Hibernate Query Language (HQL) and the Criteria API. Students will learn how NHibernate encapsulates data access using the identity map and unit of work patterns, lazy loading, persistence by reachability, and automatic dirty checking. Advanced topics will be covered as student interest and time permit, including how and when to use the NHibernate’s 2nd level cache, building a persistence layer using the repository pattern, batching operations with multicriteria and multiqueries, and querying with LINQ to NHibernate.

Topics

  • Introduction to O/RM
  • Configuring NHibernate
  • Mapping Basics
    • Mapping primary keys
      • PK Types – Native, Identity, Guid, GuidComb, Sequence, HiLo
      • Composite Keys and why you shouldn’t use them
    • Mapping Fields and Properties
  • Querying Basics
    • ISession.Load/Get
    • hibernate.show_sql
  • Mapping Components
  • Schema generation
    • Using SchemaExport to create/update your database schema
    • Adding additional mapping attributes
  • The CUD in CRUD
    • Persistence by reachability
    • ITransaction
  • Mapping Relationships and Collections
    • One-to-one, one-to-many, and many-to-many
    • Handling cascades
    • Understanding Inverse=true
    • Lazy loading
    • Avoiding the N+1 SELECT problem
  • Mapping Inheritance hierarchies
    • Concrete table inheritance (table per concrete class with complete columns)
    • Single table inheritance (uses descriminator column and all possible columns)
    • Class table inheritance (aka table per class with diff of columns)
  • Advanced Querying
    • Querying with Hibernate Query Language (HQL)
    • Querying with the Criteria API
    • Projections
  • Optional Advanced Topics
    • Multicriteria and multiqueries
    • Future queries
    • Advanced querying with native SQL
    • NHibernate with sprocs
    • LINQ to NHibernate
    • Implementing a query govenor
    • Abstracting the persistence layer with unit of work
    • Optimizing database access with the level 2 cache

Requirements

  • Familiarity with C# and .NET Framework
  • Laptop with Visual Studio 2005 or 2008 and SQL Server 2005 Developer or Express installed

Included in the cost is:

  • 3-days of intensive training on NHibernate
  • Screencasts recorded during the course for easy review
  • NHibernate in Action by Kuate, et al. (ebook)
  • ReSharper 4.0 Personal License
  • All code examples created throughout the course

psake 

A build automation tool… now with less XML…

psake is a build automation tool written in PowerShell. It avoids the angle-bracket tax associated with executable XML by leveraging the PowerShell syntax in your build scripts. psake has a syntax inspired by rake (aka make in Ruby) and bake (aka make in Boo), but is easier to script because it leverages your existent command-line knowledge.

psake is pronounced sake – as in Japanese rice wine. It does NOT rhyme with make, bake, or rake.

psake is a proof-of-concept still in the early stages of development. It consists of a single file, psake.ps1, which contains all the logic for creating a graph of dependent tasks and executing them in the correct order. You can download it from Google Code using Subversion or TortoiseSVN:

svn checkout http://psake.googlecode.com/svn/trunk/ psake-read-only

Here is a simple psake build script:

properties {
  $testMessage = ‘Executed Test!’
  $compileMessage = ‘Executed Compile!’
  $cleanMessage = ‘Executed Clean!’
}

task default -depends Test

task Test -depends Compile, Clean {
  Write-Host $testMessage
}

task Compile -depends Clean {
  Write-Host $compileMessage
}

task Clean {
  Write-Host $cleanMessage
}

The properties and task script blocks can contain any valid PowerShell commands. To execute the script, simply type:

psake [task(s)]

(This assumes that psake.ps1 is in your PowerShell path.) If you don't specify a task or list of tasks (separated by spaces), it will look for a task named "default". You can display the command line syntax by typing:

psake -help

psake [buildFile] [tasks] [-framework ver] [-debug]
  where buildFile is the name of the build file, (default: default.ps1)
        tasks is a list of tasks to execute from the build file,
        ver is the .NET Framework version to target - 1.0, 1.1, 2.0, 3.0, or 3.5
            3.5 is the default
        debug dumps information the tasks.
psake -help
  Displays this message.

Remember that psake is syntactic sugar around PowerShell. So anything you can do in PowerShell, you can do in psake. That means that you can run MSBuild, NAnt, or other scripts. There is no need to completely replace your current build system. You can use psake to automate and extend it!

psake automatically adds the appropriate version of .NET Framework to its path. So you can access MSBuild, csc.exe, vbc.exe, or any other tools installed in $env:windir\Microsoft.NET\Framework\$version\ without the fully qualified path.

task default -depends DisplayNotice
task DisplayNotice {
  msbuild /version
}

As I mentioned earlier, psake is a proof-of-concept. You're likely to find some rough edges. I am releasing to the community under a MIT License. I would love to get your feedback and ideas for improving it. If you are interested in contributing, please contact me. Go forth and free yourselves from the shackles of executable XML! Take a sip of psake and enjoy!

Thanks to everyone for coming out to see Achieving Persistence Ignorance with NHibernate at the Calgary .NET User Group this past Wednesday. You can download the slidedeck and code here. The following are some good resources on NHibernate and the importance of persistence ignorance.

I also mentioned during the presentation the trick of modifying Configuration before constructing your SessionFactory to turn immutable entities into mutable ones for testing or data loading. You can find the details in my blog post:

Lastly I will be putting up a registration page for Object-Relational Mapping with NHibernate course in the next few days. If you’re interested or have any questions, don’t hesitate to email me.

Bil joins John and James on ooVoo to try out three-way videocasting. Play Silverlight video. Play MP3 audio only.

I’ll be speaking about Achieving Persistence Ignorance with NHibernate at the Calgary .NET User Group next Wednesday.

Achieving Persistence Ignorance with NHibernate

Object-relational persistence can be very complex and middle-tier code is often dominated by persistence concerns. Your Customer class probably contains more code related to loading and saving customers to the database than it does actual business rules about customers. Wouldn’t it be nice if you could remove all this persistence-related noise? This session examines why the concept of persistence ignorance is important and how to use NHibernate to build persistence ignorant domain models.

You can register here.

Date: 25-June-2008
Location: Nexen Conference Centre (801 – 7th Avenue SW, Calgary)
Registration: 4:45 pm to 5:15 pm
Presentation: 5:15 pm until everyone’s brain is full

Food and beverages will be provided.

I’m writing some integration tests around the .NET PetShop, which has no tests whatsoever. Since the architecture is tightly coupled, you can’t really start writing unit tests effectively. You have to start applying Michael Feather’s techniques for breaking dependencies. Before doing that, I want some smoke tests around the application. That’s where WatiN comes in. I am writing integration tests at the browser level. These tests are slow because you’re exercising the full stack – browser to web server to database. You need at least some of these full stack tests in every application. A good heuristic (for a large application) is a few dozen full stack integration tests, a few hundred presenter/controller integration tests, and a few thousand unit tests. (Smaller applications would probably be a dozen full stack integration, 50 presenter/controller integration, and a few hundred unit tests.) Enough testing theory… I wrote the following unit test:

[Test]

public void CanLoadHomePage() {

    using(var ie = new IE(“http://localhost:9999″)) {

        Assert.AreEqual(“Welcome to .NET Pet Shop Evolved”, ie.Title);

    }

}

 

When I ran the test (using Gallio‘s awesome ReSharper 4 Unit Test Runner support for MbUnit), Internet Explorer appeared, but I got a failed unit test:

image

and this stack trace (reproduced in text form from the image for Google’s indexing benefit):

WatiN.Core.Exceptions.TimeoutException: Timeout while waiting for main document becoming available
   at WatiN.Core.WaitForComplete.ThrowExceptionWhenTimeout(String timeoutMessage)
   at WatiN.Core.WaitForComplete.WaitWhileMainDocumentNotAvailable(DomContainer domContainer)
   at WatiN.Core.WaitForComplete.WaitForCompleteOrTimeout()
   at WatiN.Core.IEWaitForComplete.DoWait()
   at WatiN.Core.DomContainer.WaitForComplete(IWait waitForComplete)
   at WatiN.Core.IE.WaitForComplete()
   at WatiN.Core.IE.CreateNewIEAndGoToUri(Uri uri, LogonDialogHandler logonDialogHandler, Boolean createInNewProcess)
   at WatiN.Core.IE..ctor(String url)
   at WatiNTests.HomePageTests.CanLoadHomePage

 

Alrighty then. A TimeoutException and the Internet Explorer* instance was left stranded on my desktop. Taking a look at WatiN’s FAQ, I find this:

Which windows versions are supported?

Windows 2000, Windows XP and Windows 2003. Using WatiN on Vista gives some problems when User Account Control (UAC) is enabled. If you disable UAC almost all WatiN unit tests pass.

Disable UAC to run a testing framework??? Note that I’ve used WatiN on Vista before without disabling UAC. So it had to be some other setting. I noticed that Internet Explorer was running in Protected Mode, which dramatically limits the damage that a hijacked browser can do. Protected Mode runs IE in low integrity mode. (Low integrity processes are dramatically limited in which window messages they can send to higher integrity processes – such as Visual Studio and where they can read/write files.)

image

Solution

The obvious solution is to turn off IE Protected Mode for the site. Easiest way to do this? Add the site to your trusted sites list.

image

Survey says!

image

image

So rather than turning off UAC or Protected Mode in IE completely, you can just add the site under test to your trusted sites list and WatiN works.

For the Paranoid

The astute among you may be wondering if I haven’t opened up a security vulnerability by adding http://localhost to my trusted sites list. Let’s put it this way… If some l33t haxor can drop files on your box and start a webserver, they have already pwned your box. They don’t need you to navigate to a local site with unprotected IE to infect you more. smile_tongue

* For the curious, I rarely use IE, mostly just for certain Microsoft sites that are still IE only. Heck, I’ve been running RCs of FireFox 3 for awhile and upgraded to the RTM version yesterday when it was released. If you haven’t tried FireFox 3, you really need to. Gmail is oodles faster in FF3 than IE or FF2. You might wonder why I’m using IE with WatiN… WatiN only started supporting FireFox as of WatiN v2, which is currently in CTP. Historically WatiN (and WatiR) have relied on IE’s COM automation API to interact with the browser, which is also why WatiN/R doesn’t provide a way of getting HTTP status codes – because the COM API doesn’t expose them!

For those of you who missed it, JetBrains officially released ReSharper 4 last week. A list of new features can be found here. Most notably is full support for C# 3.0 and LINQ, but there are improvements in lots of other areas. (I’ll point out these improvements in the Becoming a Jedi screencasts. I’ve got an episode planned all around the new C# 3.0 features, which should surface in the next few weeks.) New keymaps for both the Visual Studio and ReSharper 2.X/IDEA schemes can be found here. Congratulations to the entire JetBrains team for getting this release out the door! If you haven’t tried ReSharper 4, you owe it to yourself to take it for a spin.

My third episode of Becoming a Jedi is live. In this episode, I start looking at ReSharper’s refactoring capabilities.

Episode Listing

Part 1 of N: Code Browsing streaming download
Part 2 of N: Code Cleanup streaming download
Part 3 of N: Refactoring I streaming download

Streaming requires Silverlight 1.0 or higher. Download is via Microsoft Skydrive.

After finishing the episode, I realized that I committed a huge refactoring faux pas. I neglected to run unit tests after each refactoring. I was feeling cocky and just doing simple refactorings such as renames and similar. When I tried to run the application later, it failed because it could no longer find PetShop.SqlServerDAL.Category, which had been renamed to PetShop.Repositories.CategorySqlRepository. So even on simple refactorings, you need the safety net of a good suite of unit tests. Lesson learnt.

Earlier this week, I received three (3) complimentary copies of Visual Studio 2008 Team Suite with a MSDN Premium Subscription from S. Somasegar, Corporate Vice President of DevDiv at Microsoft. This very generous gift, worth $10,939 USD per copy, was a thank you to developer MVPs for their work in making Visual Studio 2008 a success. I am free to distribute the three copies as I see fit. There are no strings attached for me or the recipient (other than import rules related to your country, of course).

The first copy goes to Fabio Maulo, the recently-appointed leader of the NHibernate project. Fabio has been tirelessly porting features from Hibernate to NHibernate. Due to his hard work, the soon-to-be-released* NHibernate 2.0 has feature-parity with Java’s Hibernate 3.2.5. He is now working on porting Hibernate 3.2.6** features to NHibernate 2.1 (the current trunk). When not porting features, he is answering NHibernate-related questions on the NHibernate developers and nhusers mailing lists. Thank you for all your hard work, Fabio.

The other two (2) copies are part of the The Great NHibernate/Castle Giveaway. This is a big thank you from me to the vibrant communities around both the NHibernate and Castle projects. If you’re not familiar with either project, you owe it to yourself to check them out. Each project receives one copy to award to whomever they feel has made (or makes) significant contributions to their project. I humbly suggest that they encourage developers to get involved and contribute to the project with the award going to the developer with the most significant contribution over the next few months. The exact rules will be determined by the core team of each project. If you’re interested in contributing to either project, you can find information here:

NHibernate – Getting Started with the NHibernate Source Code

Castle Project – Get involved

* NHibernate 2.0 Alpha1 is available now. The general availability (GA) release should happen in the next few months.

** Hibernate 3.2.6 is the current production version of Hibernate.

Today I decided to contribute some patches to the upcoming NHibernate 2.0 release. First order of business was to get latest and then run:

nant clean build > output-debug-build.log

which compiles NHibernate and the unit tests. Unfortunately something went horribly wrong as the build finished early. Usually nant chews on a large project like NHibernate for awhile and then spits out something like this near the bottom of the output:

BUILD SUCCEEDED

Total time: 57.5 seconds.

I started splunking through the output to try to figure out what was wrong and noticed this at the bottom of the output:

BUILD SUCCEEDED

Total time: 11.9 seconds.

About 12 seconds to compile everything! I’m used to a quick return from nant usually meaning a failed compile. Not in this case. The Ultimate Developer Rig – Kovacs Edition is just plain fast. And that made me happy.

CORRECTION: The above NAnt command builds the unit tests, but doesn’t actually run them. Mea culpa.

UPDATE: I ran everything again including running the unit tests:

nant clean build test > output-debug-build.log

On my Latitude D820 (Core Duo 2.0 GHz), total time was 98.6 seconds.

On the Ultimate Developer Rig – Kovacs Edition, total time was 62.8 seconds.

Yes, unit tests – especially for NHibernate where you really have to touch the database for most tests – take time to run. Note that a really fast box doesn’t help unit test times as the unit tests take about 40 seconds to run regardless. This says to me that unit test times are dominated by the time spent communicating with the local SQL Server database.

N.B. NAnt does not support parallel builds. So only one core was kept busy. You can hack MSBuild to support parallel builds as documented by Scott Hanselman. Given the fact that most developers have at least dual if not quad-proc machines, I hope that build tools start officially supporting parallel builds.