Short n' Sweet NHibernate Sample
People often have the perception that NHibernate is some honking great behemoth of a library that should only used in massive enterprise apps.
To prove this isn't true, it I've made a tiny four-file NHibernate sample with just over 100 lines of code.
Download .NET Visual Studio Solution (includes libs).
You don't see many of these tiny NHibernate samples out there on the web, so hopefully this might help someone dip their toes into NHibernate without having to wade through architecture or infrastructure. You can just open the solution and have a peek at the few files in there.
The files in the solution are:
Classes.cs
Contains a couple of entities that you can save and load
PersistentTestFixture.cs
NUnit test fixture demonstrating create, save and query.
hibernate.cfg.xml
A minimal NHibernate config file.
mappings.hbm.xml
The XML to map the entities to the database
Also note:
- This requires virtually zero setup. The test fixture will even create a 'ClubTest' database on your local SQL Server if there isn't one there already (and create tables too).
- The mapping files are simple and very minimal, so they rely on the NHibernate sensible defaults.
Bear in mind that this is a very simple way of seeing some NHibernate code. It's not an industrial strength scalable code base! If you want to see recommended real-world samples then I'd point you at the Cuyahoga CMS, Sharp Architecture, nhforge.org or Summer of NHibernate (to name a few).
Man makes nice software. Sells it. Makes $100,000 in 5 months
In only 5 month's, Peldi Guilizzoni has sold $100,000 in licenses for his Balsamiq Mockups app.
I've blogged about Balsamiq Mockups a few times. I really love the concept.
Balsamiq is a one-man shop, and is the product of good ideas and passion. It reminds me that we can still make good money by selling cool little apps.
Peldi is very open about his earnings - showing Google Analytics and earning trends over the last 5 months.
If you're interested in this story, then you'll also be interested in...
- How 37signals made $765,000 over a few years.
- How The Daily App got to 1000+ visits per day in 3 weeks.
- How Steve Dementer's iPhone Game made $250,000 in 2 months.
What do you use for authoring articles, documents and books?
Whilst editing NHibernate in Action, I've clocked up about 300 hours using Microsoft Word. Right now, my opinion is that this is not a great tool for book authoring.
Manning Press use one document per chapter, which makes sense because chapters seem to be the logical unit of work in a publishing workflow. However, when you want to quickly generate a Table of Contents, or see the index for the book, you have to start using word trickery (sub documents etc). Manning don't use any of those features, probably because they require lots of word skillz for all involved, and is error prone.
What surprises me is that Manning didn't ask me to work with some purpose built, advanced book authoring software that fits the publishing workflow perfectly. Does such a tool exist?
Martin Fowler writes some very interesting stuff about how he uses XML for authoring. PoEAA was the first book he tried this on. Sounds like managed to get a lot of leverage from this approach, although he did have to essentially devise his own tool chain.
Would be great if anyone can share their thoughts on this. Are there any authoring tools you use and love?
Are you hiring .NET developers?
I have a few friends here in Yorkshire that are looking for contract work.
They're both enthusiastic, hard working and skilled .NET developers. And good blokes of course :) They're also both NHibernate savvy, and familiar with TDD, agile etc.
They're looking to work either remotely, or for companies in and around Leeds, West Yorkshire, UK.
No agencies please, they'd rather build a relationship directly. If you know of anyone, then drop me an email, or a phone call on +44 7900 907146.
NHibernate in Action - Impressive chapter on caching
I'm currently editing Chapter 5 for NHibernate in Action (we hope to be in print in a 2-4 weeks, so this is the last time!).
Chapter 5 is about transactions and caching. There's a lot of information on the 2nd level cache, including process-scoped and cluster-scoped caches for distributed scenarios.
Despite that I've reviewed/edited this chapter a few times, I've not used NHibernate's 2nd level cache until recently. So I'm reviewing and learning at the same time!
Hats off to the original authors and Pierre Henri for writing such a strong chapter. The case-study style scenarios are particularly useful for working out optimal caching strategies.
For example, I just learnt that an app I'm working on could benefit from the nonstric-read-write cache usage:
<cache usage="nonstrict-read-write"/>
....instead of...
<cache usage="read-write"/>
Nonstrict-read-write means that when you save an object to the database, NHibernate will invalidate it in the cache too, but it does it asynchronously meaning there's no guarantee of exactly when it's removed from the cache. Of course, this introduces the chance that another process could read stale data from the cache (albeit only a few milliseconds stale!). This is a tradeoff, and the benefit is performance - because it's asynchronous NHibernate won't wait for both DB and Cache to confirm the changes.
I'm looking forward to benchmarking the various caching options to see just how much my app can gain.
Right now my 2nd level cache is provided by the ASP.NET Session Cache, but in a few weeks I'm hoping to switch to a distributed cluster of Velocity caches. That will be fun!...
Green Screen Text Based GUI Mockups :)
I've blogged about text based GUI mockups before. I think they're useful.
Here's one I did today, it took about one minute. It was to clarify how a use case would work.
I wrote it as part of an email in Outlook, using the Courier font. I also used the foreground/background colouring in Outlook to make it stand out from the rest of the email.

A bit silly, but possibly effective :) 1980's eat your heart out...
ASP.NET MVC - Losing the CodeBehind
Like some other people, I'm not really enjoying having code behind files in ASP.NET MVC.
As Tim Barcz points out, if you want to lose the CodeBehind and still have strongly typed ViewData.Model, you can do this:
<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]" %>
<h1>Welcome <%= ViewData.Model.Username %></h1>
It's ugly, but it works!
What about another approach?
<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewUserControl" %>
<% var Model = (LoginData) ViewData.Model; %>
<h1>Welcome <%= Model.Username %></h1>
Again, it's a kludge, but avoids playing with weird generic names :)
Build, test, refactor - a simple .NET Rake script
I just blogged about setting up Rake with .NET. Based on a few resources online (and some Ruby experience), I've cobbled together a quick Rakefile.rb that can build, test and analyze a solution.
- Build calls MSBuild on the Visual Studio solution file.
- Test calls NUnit on all DLLs with Test in the name
- Analysis calls NDepend which will then give me a list of top 10 refactorings.
What's nice is being able to just type rake and all these steps are performed. I know you can do this with Nant, but you have to admit the Rakefile.rb is very concise! If I want to run tasks individually, I can also type:
rake compile
rake test
rake analyze
Here's the Rakefile.rb script:
#Rakefile.rb
require 'rake'
require 'build_helper'
task :default => [:compile, :test, :analyze]
desc "MSBuild solution"
task :compile do
msbuild :squilbo
end
desc "NUnit tests"
task :test do
files = FileList['**/*.Test.*.dll'].exclude(/obj\//)
files.each do |file|
sh "#{NUNIT} #{file}"
end
end
desc "NDepend analysis"
task :analyze do
sh "#{NDEPEND} \"#{current_directory}\NDepend.Core.Xml\""
end
This file also includes another file - build_helper.rb, which contains constants and useful functions.
This could have been included inline, but I thought it might be neater to keep it separate.
#build_helper.rb
def msbuild(solution)
sh "#{MSBUILD} #{solution}.sln"
end
def current_directory
Dir.pwd.gsub(/\//,'\')
end
#
# Put your own definitions here. You could also load from a YAML or XML file
#
NUNIT = 'C:\Program Files\NUnit 2.4.7\bin\nunit-console-x86.exe'
NDEPEND = 'C:\Program Files\NDepend\NDepend.Console.exe'
MSBUILD = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
SOLUTION_FOLDER = current_directory
This is all just the first 30 minutes of playing with Rake, so I'm sure there are many better ways of doing things. But, thought I'd share the first experiences.
I'm looking forward to playing with NDepend more (they were kind enough to give me a license), my main goal is to get it tightly integrated into my development process so I can actually get some real, ongoing benefit from it.
Getting Started with Rake on .NET
Many people have discovered that Rake is a lean, mean, build assisting machine. Even better, some .NET developers enjoying it too. It's even been praised by some of the industry's best.
Getting started with Rake and .NET is actually childs play.
- Download the Ruby for windows one click installer.
- Install it
Great, you've now got everything you need installed on your machine and are ready to start using Rake. All that's left to do now is create a simple Rakefile and run it.
- Open any .NET solution you've been working on recently in Visual Studio.
- Add a solution item called Rakefile.rb (type is text file)
- Paste in the following and save
task :default => :welcome
task :welcome do
sh "echo Rake is up and running. Hurrah!"
end
- Open a command prompt (Start->Run->Cmd)
- Type:
cd c:\Code\MySolutionFolder(obviously put your own path in) - Type:
rake - Done!
If you see this, you've got a working installation of Rake.
echo Rake is up and running. Hurrah!
Rake is up and running. Hurrah!
If you want to now know how to get the most from Rake with .NET, go and see how other .NET developers are using Rake.
A Workflow Experiment
I recently blogged about how I like the idea of simple workflows. Ones that can be written and integrated in a few minutes.
I want to make prolific use of workflows in my apps, and for that I need as little resistance as possible. Minimal code, minimal tooling, and minimal infrastructure.
I'm having a crack at solving this, for some deranged sense of fun :)
Problem No. 1 was designing and defining workflows. I don't want to have to use a graphical tool, DSL nor XML files. DSLs need learning, graphical tools slow you down, and XML is clumsy.
So, why not defining workflows in C# or VB.NET? By this I mean using C# as the DSL, not as an object model. After some juggling, I got some code like this. It defines a workflow for online registration.
public class NotRegistered : State
{
public Confirming RegistrationSubmitted { get; set; }
}
public class Confirming : State
{
public Registered ConfirmationReceived { get; set; }
public Deleted After14Days { get; set; }
public void SendConfirmationEmail(){}
public Confirming After2Days_SendReminder { get; set; }
public Deleted CacellationReceived { get; set; }
}
public class Registered :State
{
public void ActivateUser(){}
}
public class Deleted : State
{
public void AuditAndDelete(){}
}
This looks quite neat when viewed in a Visual Studio class diagram. Those 22 lines of C# code make a diagram like this:

As you can see, we have states, transitions, triggers, entry activities and trigger activities. No guard clauses yet, but they're on the way.
So that's the workflow defined in very little code. But, it doesn't *do* anything. It's just a definition.
Next blog post I'll focus on other aspects I've got working, including:
- Integrating the above workflow into the ASP.NET MVC default registration process in about 5 lines of code.
- Writing a simple workflow engine to parse the definitions (fluent API included).
- Persisting the workflows with NHibernate (in about 10 lines of XML)
- Handling time-based triggers.
Little Workflows?
Disclaimer: I have no experience using workflows in applications :)
I've been thinking about what I want to get out of workflows and state machines. Or even, what value can they add to my applications.
Workflows seem under-used. Windows Workflow doesn't seem to encourage prolific use. Setting up a workflow is a bit of a plumbing exercise, or so it seems?
I like the idea of having lots of light-weight workflows that can be created and consumed with very little effort (minutes of coding). They'd almost be like a first-class citizen in the language. I'd see them cropping up all over the place: workflows to govern GUI sequences. Workflows inside GUI controls to govern their current state. Workflows internal to domain entities used prevent execution of business logic at the wrong time.
I like the idea that, whenever I need to constrain when business logic is allowed to execute, I can create a workflow to describe that. So, business logic related to sequencing of events lives in, err, a workflow. But only that logic, not the other stuff.
This is a separation of concerns, the workflow is responsible for containing business rules related to what can be done and when it can be done, and possibly even by whom it can be done. This may keeps workflows light because they're not trying to do too much.
I also like the idea of a GUI observing a workflow, just as it does with other models, and use it to dictate the options that are presented to the user.
This is a bit of a waffling post. Again, I've got no experience with this, sorry if I'm talking crap!
With that in mind, does anyone know of any good articles/books defining proven patterns for using workflows in applications?
Is anyone using an abundance of light (or heavy) workflows in their applications?
Text Based GUI Prototypes
A few years ago I developed an Enterprise Architect CASE tool plugin for Wells Fargo bank. It allowed them to combine UML Activity Diagrams with the GUI prototyping diagrams, and then generate interactive HTML that users could explore. It was fun.
I like EA, but each tool comes with an overhead. You have to buy, learn, install and upgrade the tool. Also, it sits there using up memory and CPU. And, it's another "context switch" during development.
Given my current interest in .txt files, I've been playing with creating plain text files to mock up UIs. 1980's eat your heart out. I was able to mockup 8 screens in roughly 8 minutes, which is pretty good going. The format looks something like this (2 pages shown):
Login
=====
Username: XXXXXX
Password: XXXXXX
[x] Remember me
[Submit]
Register...
Forgot your password?...
Forgot Password
===============
Please enter your email and
we'll send you a password.
Email: XXXXXX
Enter Captcha: XXXXXX
[Send me my password]
One thing I like about this is that the essence of a GUI can be captured in very little time.
Like all models, this one helps me focus on a particular set of concerns. In this case, screens, content and workflow. Not layout, pixel perfection, design, colour, widgets adn controls, ajax, master pages and routes.
I'm not sure where all this is going, but I'm almost convinced the way to productivity is small, simple models that focus on a tiny subset of concerns. The problem I'm trying to get my head around is how to get value from such simple models in code, without making the models heavier. Perhaps you can't. Anyway, that's all for another rambling post :) ...
Anyone got any GUI prototyping experiences to share?
.NET code sharing: inspired by Ruby Gems
I just blogged about the dire state of code sharing in .NET. The main reason I've noticed this is because I have a good reference for comparison - Ruby and Ruby Gems.
One thing I absolutely love about developing with Ruby is how easy it is to leverage other peoples work.
Say I'm writing a spam filter app, and I want Bayesian classification. I can get that functionality in seconds by doing this:
gem install bishop
That downloads the latest version of the bishop bayesian classification library to my local machine. It fetches it from a central server with 1000's of reusable libraries (Rails included). Any applications I write can now make use of Bishop by adding a include statement in the source code.
require 'bishop'
I then just start writing code that uses Bishop.
Even better, next time the developers of Bishop do some funky updates that I want to make use of, I can simply do this to get the latest:
gem update bishop
And I've got the latest on my machine (I can also work with the older versions too, it's my choice)
This is all very good stuff. I'd be interested to hear how we might get this kind of thing in the .NET arena.
.NET code sharing: How can we fix it?
Leveraging code written by other developers is a big big deal.
You can ship more features in less time. You can have more fun playing with cool features that would take you months to write yourself. You can learn by studying other peoples APIs and design decisions. You can explore different possibilities to solve problems by scouting for libraries that may serve your needs.
I don't think code sharing is anywhere near easy enough in .NET right now. It's still a complex process to get leverage from the vast quantities of code us developers are sharing online. All that code and so little sharing. Sad.
If we had something like Ruby Gems, then we could do stuff like this...
c:\MyProject\> lib update ASP.NET-MVC
c:\MyProject\> lib install NHibernate
c:\MyProject\> lib install NHibernate.Validators
c:\MyProject\> lib install RSS.NET
c:\MyProject\> lib update Lucene.NET
Better. Much better. Of course, we'd want a Visual Studio plugin for exploring and installing libraries.
Does anyone else agree that we need this kind of functionality in .NET?
TODO.txt 2008 Ultimate Team Edition
Believe it or not, the simple TODO.txt ticks a lot of boxes when it comes to collaborative issue management. Check out this list of cool features for the mighty TODO.txt file.
- Full Version History - when used in conjunction with GIT or SVN
- Task Prioritisation - TODO items can be reordered into priority order
- Release Management - TODO items can be put into different releases.
- Centralised Issue Management - when used in conjunction with GIT, SVN, FTP or WebDav
- 100% Collaborative - Many developers can view and edit TODO.txt at once with little risk of conflict.
- Low Cost - there are no licensing fees.
- Easy to install - no web server or desktop client needed. Use with your existing text editor (Notepad++, TextMate, Visual Studio or Vim recommended).
- Easy to Learn - it's as simple as typing text!
- Non Intrusive - use TODO.txt from within your IDE whilst developing.
- Small Footprint - uses almost NO memory or CPU.
- True Mobile Platform - TODO.txt works on 90% of mobile phones.
- Cross Platform - TODO.txt works on any computer platform created after 1960.
- Easy Import/Export - Export data to any other bug tracker using RegEx and SQL.
- International Support - when used with a UNICODE compliant editor.
Ok, this is a bit tongue in cheek, but you have to admit, the humble TODO.txt has a lot going for it.
Example
Here's part of the TODO list for Squilbo, a web based database tool I'm working on.
Key
===
* = This release
> = Bumped to some future release
x = Done or Cancelled
Feature: Schema Browser
=======================
* show stored procedures
* show functions
* clear and show waiting signal whilst loading new schema view
* show "Please wait" when loading data from server
* drag n' drop tablename onto query
> right click table gives option "Select top 100 records"
> right click on column gives option "Select top 100 distinct values"
x show data types on hover over column name
x show views
x refresh databases drop down on connect
x show key columns with different icon
So this question is this. I'll obviously have to move to something more sophisticated after release 1 of my little project. But what is the next step up?
Humour aside, can anyone name a bug/issue/task tracking tool that comes close to the criteria listed above, and builds on them? And no, Excel is not an option I'd consider :)