Ayende @ Rahien

It's a girl

Replacing O/RM Is Hard

No, I'm not abandoning NHibernate to greener pastors, I'm talking about this post.
I'm not sure what the point of the author was, but on first reading, it read like FUD to me. Maybe it is the general tone of the post, or that there are a lot of numbers without any clue how the author got them, but that was my first feeling. A lot of the points that are raised are valid, but I just don't understand where the numbers came from.
I had a math teacher that used to look at a student excersize and say: "And suddenly there is a QED." when we did something stupid. I fill like saying it here.

Take for instance the part about entities and methods. I present you my most common method of dealing with O/RM:

public interface IRepository<T>
    void Save(T item);
    void Delete(T item);
    ICollection<T> Find(params Predicate[] preds);
    T Load(int id);
    T TryLoad(int id);

That is it. The implementation is generic as well, so I go five methods, not matter how many entities I have. In theory I can switch from O/RM to DAO to SOA to AOM (Acronym Of Month) with very little effort. I would replace the implementation of the IRepository<T>, and I'm done. Five methods, about 2.5 hours if I understand the math correctly, we'll add a couple of days to be safe, but we are still under 20 hours.  I don't even need to touch the UI since it works against the interface, and not the implementation.
The problem is that this math is that it is based on nothing in particular. I recently had to evaluate moving from one O/RM to another, and I had to survey the number of places where I was dependant on the O/RM. I counted 23 major features that I had to have if I didn't want to basically re-write my application from scratch.
Those ranged from lazy loading to cascades to reference equality for same entities in the same session, etc.
Replacing the O/RM would've have been hard at best, impossible at worst, and painful whatever I would have done. And I used a very similar interface to isolate myself from the O/RM (even though I never had any intention of replacing it).

Frankly, the issue is not the support of interface, but far smaller interactions. From knowing that you can map the same fields in a class to different properties in a hierarchy (an integer in one case, an object in the other, etc) is very powerful tool that will cause quite a bit of pain if you need to stop using it. That is where the cost of switching O/RM will come into play.
If you are doing anything at all interesting with your O/RM of choice (or hand written DAL), then you are going to get into some serious trouble if you think about switching.

For instance, I'm using NHibernate's Table Hierarchy to save strategies to the database, so when I load the object later, I'll get all its saved strategies with their parameters. It is making my life so much easier, but I don't want to even think what I would have to do if I had to write it all on my own.
To conclude, I agree with the first two observations, and disagree with the third. You can certainly optimize a good O/RM as much as you like. Usually you don't even need to see the O/RM code for this.
I really don't agree with his conclustions, though.

Training By The Ear

One of my tasks when I was in the army was to train people. It was often new guys that arrived, but also refreshing the knowledge and the skill of our existing staff. One Wendsday afternoon I got an urgent call from headquarters, I was to drop everything and go to another base, to train several cadets in the final stages of their training.
I was literally yanked away in a matter of a few hours. The course that I needed to pass was supposed to be two to three weeks long, and existed mainly as a set of power point presentations that were written by someone who never worked in the field.
I took a brief look at the material that I had and flat out refused to pass the course this way. It was, in fact, the same material that I was taught, and it hasn't changed a bit in over two years (and a lot has changed since). So I just played the course by the ear, without much sleep, but with a real devotion to make sure that the officer that I will train will go into the field as prepared as I can make them in a class room and in field trips.
I remember several times when I had to tell the cadets to wait for several minutes while I was finishing writing their next lesson, and then immediately giving it to them. Needless to say, in the breaks between lessons, I kept writing the next lessons. It was also one of the times that I had the most fun in the army (sadly, it wasn't even close to one of the times that I had least sleep).
I had a similar experiance today, writing a presentation and the lesson's plan in the morning, doing a short trial run on some co-workers, and then passing it later that day. In fact, I wrote the lesson for tomorrow while the students were doing excersizes.

Oh, and one point that I am particuallry proud of, the presentations and lessons that I created for the out of the blue course were used in the army for several years afterward (actually, to my knowledge, they are still in use today).

NHibernate Generics 1.0.6 Release

This release fixes a very annoying bug with NHibernate Generics and lazy load exception when the entity ref is set. A huge thanks for Daniel for giving me a much better solution than the workaround that I found.
You can find source and binaries here

Runas Mystery

I can't seem to use Runas on files that or a network share. I'm not sure why, but I'm getting invalid user name or password for combinations that are valids.
Anyone knows anything about this?

NHibernate & .Net 2.0 Nullable Types

If you want to use NHibernate with .Net 2.0 Nullable Types (int?, DateTime?, etc), all you need to do is to specify full type name of the (non nullable) property.
So, if you've something like "DateTime? DueDate { get; set; }", the mapping will looks something like this: "<propery name='DueDate' type='System.DateTime'/>"
You don't need to do anything else.

Mini Seria Review: The Witch, The Lion and the Wardrobe

I just watched The Witch, The Lion and The Wardrobe, the mini seria from the 80s.
It is far more primitive, but it has a certain charm.
The children actually looks like real children. When they needed to show a pegasus, they actually used animation.
The England that is shown is more in line with my excpectations of the time (a map of the war's progress on the wall, for instance), and the English accent is a delight.
I think I may have seen this as a child, there are some things that rings a bell, visually. but it is hard to know since I seen the new movie and read the books several times.
The White Witch looks far more like I thought it would be from the description in the book, and not like something out of a Muscle Woman magazine.
I really liked the proffesor's attidute in this movie.

The annimation is not on the level of Who Killed Roger Rabbit, but it leaves enough for imagination to fill, so I don't have a problem with this.
I just saw a unicorn in this movie that looked more real than any other. Aslan itself is both a surprise and a disappointment. It looks more or less like I imagines, a big lion, but his roar is not something that would frighten a kitten.
The White Witch is really a caricature, I think. Considerring the way she is portrayed in the book, I'm not surprised by how she is acting. It's all in line with the character, the problem is that the character is not believable.
First time I have ever seen a flying lion anywhere, but it is in this movie. Doesn't look very real, but it gives them a chance to show some country side, I guess.
The battle scene, which I really like in the recent movie, is the part that really can't compare, it is laughably bad in all regards.
The end was better, I think.


Published at

Comments on DNRTV #16

I just finished watching DNR TV #16, in which Carl is talking about async programming.
Some of the best DotNetRocks episode was with Carl and the host of the moment just goofing around and talking tech, so I had high expectations of this.
I'm not a VB programmer, and it's interesting to see how a VB guy works, and it even includes commentry.

One thing that I don't understand is this construct:

    ' do something that can throw
End Try

Isn't this a no op?

This video reminds me of a Joel On Software article about how hard it is to write a function that copies a file.
There is a lot of commentry on some ancient VB stuff along the way, since Carl often compare the way it was done right now and in VB6 and previous versions.
It is a nice show.


Published at

Reliable Software is Hard

There is a really good post about writing reliable software and why it is so hard.
Damien's writing is really good, and he touches on many interesting subjects.


Published at

A Story About Testing In Multi Threaded Environments

I just finished a really nice project that involved heavy use of multi threaded code. The project is enterprisey (which has turned into a really bad word recently, thanks to Josling and The Daily WTF), so I needed to make sure that I was handling several failure cases appropriately.

Now, testing multi threaded code is hard. It is hard since you run into problems where the code under test and the test itself are running on seperate threads, and you need to add a way to tell the test that a unit of work was completed, so it could verify it. Worse, an unhandled exception in a thread can get lost, so you may get false positive on your tests.

In this case, I used events to signal to the tests that something happened, even though the code itself didn't need them at the beginning (and didn't need many of them at all in the end). Then it was fun making sure that none of the tests was going to complete before the code under test ( there has got to be  a technical term for this, CUT just doesn't do it for me ) has completed, or that there were no false positives.

As I was developing the application, I run into issues that broke the tests, sometimes it was plainly bugs in the thread safety of the tests, and I could see that the code is doing what it should, but the test is not handling it correctly. I was really getting annoyed with making sure that the tests run correctly in all scenarios.

In the end, though, I was just about done, and I run the tests one last time, and they failed. The error pointed to a threading problem in a test. It was accessing a disposed resource, and I couldn't quite figure why. Some time later, I found out that an event that was supposed to be fired once was firing twice. This one was a real bug in the code, which was caught (sometimes it passed, the timing had to be just wrong for it to fail) by the test.

Actually, this was a sort of an accident, since I never thought that this event could fire twice, and I didn't write a test to verify that it fired just once. (In this case, it was the WorkCompleted event, which was my signal to end the test, so I'm not sure how I could test it, but never mind that.)

I spent some non trivial time in writing the tests, but they allowed me to work a rough cut of the functionality, and then refine it, knowing that it is working correctly. That was how I managed to move safely from the delete each row by itself to the BulkDeleter that I blogged about earlier, or to tune the consumers, etc. That final bug was just a bonus, like a way to show me that the way I used was correct.

Now, the tests didn't show me that if I try to shove a 30,000 times more data than it expected, the program is going to fail, that was something that load testing discovered. But the tests will allow me to fix this without fear of breaking something else.


Published at

AccessViolationException in Windows Services

I wrote a Windows Service and I couldn't get the service to start properly. After trying too long to debug it in a service mode, I gave up and tried running it as a console application, I immediately got the following error:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I so thought that I left those kind of bugs when I left C++. Just to be clear, there isn't a hint of unsafe / unmanaged code in the application. It turned out that my initialization was throwing an exception, and because my error handling was calling Stop(). This seems to be the trigger.

I repreduce the error with this code:

class Program


    static void Main (string[] args)


        new TestSrv().SimulateStart();



    public class TestSrv : ServiceBase



        public void SimulateStart()





        protected override void OnStart(string[] args)




                throw new Exception();


            catch (Exception e)


                //log exception






The fix was not to call Stop() from OnStart(), but to use Environment.Exit(-1), which tells the Services Manager that we exited with errors.

I filed a ladybug here.

s More reasons not to like Data Binding

It is not possible to bind to hierarchies of objects.

It is not possible to bind to external things, like attributes on the object, or the object name, this make it much harder to do Convention Over Configuration with data binding.


Published at


Note: This post started as a comment on the post just below, but it developed into a full blown rant along the way. I'm detailing many of my frustrations with the tools.

Scott Bellware has posted Mort or Elvis? A Question for a Bygone Era, which is a great post (as usual), but it also hit many of the pain points that I feel in working with VS 2005 recently. In fact, Scott does a great job of expressing those pain points than I could.

Microsoft's tools are getting progressively worse rather than better.  Microsoft development tools are showing the unmistakable signs of entropy and neglect that comes as a result of the parasitic infestation of product development groups by the cowardly side of the software business.... 

In the comments he talks about Microsoft's tools and then subtle product placement that I didn't recognize but drive me constantly crazy. I use VS.Net 2005 for the simple reason that it is the only one out there for .Net 2.0 development. ReSharper makes the job bearable, but it says quite a bit if I need an alpha quality tool just to feel good again.

Beyond VS.Net, my most common tools are not Microsoft ones (NAnt, NUnit, TestDriven.Net, etc). Scott comments on this:

And indeed, these folks [thinking developers] will bring an arsenal of better tools to the table.  Few of them will have been created by Microsoft, and most of them will be free, and open-source. 

Finally, there is this sentiment that I agree with wholeheartedly:

I would pay right out of my own pocket for a .NET IDE built by JetBrains. They could change me $1000 and I'd be delighted to fork over the cash if they could give me an IDE that was file-system and project-system compatible with Visual Studio with none of the bloat and none of the endless, insulting product placement clutter that has gained influence over the design of Visual Studio to the detriment of good, clean, usable product.

I wanted this for a long time. I hope that once they release ReSharper, they will rev up the work on .Net IDE. I know that I would buy Intelli.Net IDEA in a heart beat, and push it out as far as I can.

And now to my own ranting:

And my own note about the personas. They don't work anymore. I get questions from VB.Net developers that want to know how to use Rhino Mocks, there have been questions about VB.Net development with Castle, etc.(Not to go down on VB.Net programmers, but this is the language that is portrayed as Mort's favoriate). I has to do some UI work right now, and I tried hard to do this with VS.Net's Automatic UI & Coffee System(TM), but I couldn't make it do what I wanted, and I ended up doing most of it manually.

Simple UI should be the part where the tooling is excellent, but in order to use them, you need to know quite a bit about the tools, and that is not something that I see as highly productive. I know the WinForms (and Win32) API well enough to produce a working UI for most of everything, but I don't see investing time in learning the exact incantations that I need to do this or that (nothing highly complicated, by the way) for non standard scenario (binding Business Objects to a form).

By concentrating so hard on the tools, only the supposedly core scnerios are taken care of, leaving everyone that does something different high & dry. And the problem seems to be that there isn't any improvement along the way in the tools.

We have the Web Application Project, to get back the stuff they took away from VS 2003, but that is about it. Where is the promised Service Pack for Visual Studio 2005? I haven't even heard a whisper about it since it was announced, and it is not like there aren't bugs that need fixing in there.

Posts like this one, talking about how features are planned for VS, just scares me. It looks very much like the merit of a feature is its demo-ability. This produce software that demos great, but that just doesn't stand on its own when you need to develop a real scenario. Combine the non-tirivial time that you need to invest to learn how to work with the tool with the even more significant time to learn how to by-pass the tool, and you get a net loss situation. Non-demoable features end up being more important in the long run.

How many demos has seen the demo about File.ReadAllText() method? Yet it ends up saving me 5 lines of code every time that I need to read a file. Or the GC improvements? Or ASP.Net Build Providers? Linq will be cool if I could get a compiler support and intellisense alone. No need to build any UI on it, it is cool because of what it is, not because of what kind of UI I can show in a keynote.

I really like the framework, from ASP.Net to WinForms to Theards to ADO.Net. I just dislike the tool that I have to interact with it. It is nice and shiny from the outside, but don't take a too close look at the support beams. The IDE shouldn't try to help me. I know what I'm doing, thank you very much. I want to be able to work with code in my IDE, intelligence on the part of the IDE is required, otherwise I can just work in Notepad. I don't want to work like Microsoft thinks I should (TDD or DataBinding, for instance), I want to have the functionality in the class library, and the IDE should support it.

I get a far better value from TestDriven.Net than I do from VS' Test Tools, and TestDriven.Net has a far more primitive interface, with far less functionality, probably. But this is a zero friction tool, I don't need to adhere to Jamie's design philosophy if I want to use it.

Okay, that is enough ranting for now, I think

Why I like NHibernate Generics

Because I wrote it, of course J

Beside this, there is the nice part about smart collection and references that can save me quite a bit of code. Take this example:


RuleBase rule = RulesTree.SelectedNode.Tag as RuleBase;

if(RulesTree.SelectedNode.Parent==null)//top Rule






    ContainerRule parent = RulesTree.SelectedNode.Parent.Tag as ContainerRule;




I started to write this code, but soon realized that because I used NHibernate Generics’ smart collection, I could do this instead:


RuleBase rule = RulesTree.SelectedNode.Tag as RuleBase;

rule.Customer = null;

rule.Parent = null;


This is much simpler, in my opinion, and it has the same affect.

Published at

I don't think that data binding likes me

Why I don't like data binding:

  • You can't work with interfaces. If my object has a property with a type IList<T>, it wouldn't work. That is even if the collection implements IBindingList.
  • An error in the data bound grid cannot be exited short of killing the process.
  • You can't bind to non-IList data.
  • It looks like some weird stuff is going on behind the scenes, I get index not found exception when using the data grids, and I'm pretty sure that I am handling everything just fine.
  • I can't make deleting works, no matter what I do, it looks like the instances that it uses are different than the ones that I'm passing it, but I don't have the time to find out right now.  I can get it done more easily if I will simply do it by hand, I am afraid.


I started to add Support for Data Binding to NHibernate Generics:

  • Added IBindingList, IRaiseItemChangedEvents, ICancelAddNew support for EntityList<T>.
  • It will automatically subscribe to any inserted item when it implements INotifyPropertyChanged
  • Support searching out of the box.


Unfortunately, it looks like my implementation is flawed, so I'm not going to commit the changes (maybe to a branch), unless there is anyone out there who know more than I do about data binding and can help me get it to work.

Published at

Book Review Part 2: Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET

Data Binding with Windows Forms 2.0 : Programming Smart Client Data Applications with .NET (Microsoft Net Development Series)


Here is the rest of my review of this book.

Chapter 6 has a fairly complete introduction to the DataGridView control, which actually made sense to me. I'm still not certain how I'm going to go implement my UI, but this is mainly because I want hirerchial display of some sort, and apperantly the DataGridView doesn't support this. Since it is should be a two level hirerchy only, it shouldn't be a problem to display on the side, rather than on the grid itself, but I'm wonderring if I should take the time to investigate Infragistics' controls and see how easy it would be to this versus displaying it on a seperate grid.


Chapter 7: Right now I'm in the middle of it, and it is very boring. It covers all the essenstials interfaces for data binding, and I know I need those, it is just that some of this I know and most of this I will need to know, but I am slightly sick and it is a dry read.

So far it has only served to convince me that this stuff is not trivial.  Chapter 9 is supposed to show how I can implement it over normal business objects without too much trouble. I'm waiting expectantly, I really hope to avoid having to handle all the gotchas there myself.

I don't believe that I didn't know anything about TypeDescriptor and friends up until now, I kept doing it all by hand.


Chapter 8: Skipped this one right now, it talks about implementing data bound controls, which I have zero intention to do (ever!) . I'll probably be back later to check on it anyway, since it has cool stuff like "Autocompleting Input in a TextBox Control"


Chapter 9: Finally, I get to the real thing. "Implementing Custom Data-Bound Business Objects and Collections" is the whole reason I'm reading this book. So far it looks liket the author has as strong a bias toward DataSets as I have against them :-) I ended up implementing the functionality that I need right now by myself.  Since the bulitin support isn't enough. There are a lot of ideas about how to implement the interfaces correctly.


Chapter 10: Talks about validations and error handling, I'm skipping it right now.


Overall, this is a really good book, I don’t have time to play with everything that the author shows, but it looks very interesting.

Published at

Concurrency Questions

I was asked a question today, and I'm not sure what the answer is. The issue is with optimistic concurrency on the web. I got an edit page that allows a user to edit a page. I want to throw a concurrency exception if a second user has changed the object while the first user was editing it.

The issue is that when I get the values of the form back when the user is finished editing, I no longer know what version of the object the user has edited. It looks like I would need to store the version of the object (most likely a SQL Server Row Version) in the form as well, and then get the object from NHibernate, set the version property of the object (and all the rest of the fields), and then try to save, to see if there was a concurrency violation.

Any other ideas that I have not thought of?

Schema Generation

I just did a little test with NHibernate's Schema Generation capabilities, and I'm very impressed. The schema is very much like I thought it would be, and it makes sense.

So far I've been avoiding it, thinking that I can do much better and that it is something that I have to do by hand. This caused quite a bit of pain when I needed to make a change in the object model that required a DB change. I'm thinking that I'll be able to just use it to easily and painlessly re-create the schema every time I'm starting.

It looks much simpler this way. Of course, this means that I'll need to put more information into the mapping than I currently do (for instance, I don't always bother to specify not-null constraints, etc). I don't know how to handle column orderring, but I have a suspicition that it matches the orderring inside the mapping (which may bring interesting questions when I will try to apply it using Active Record).

What is Up With Passport?,

I'm trying to watch the Object Builder Webcast, but I keep getting an error when I try to register:

We're unable to complete your request
The Passport Network is experiencing technical difficulties. Please try again later.

It has been this way for over 24 hours. Anyone knows what is up with this?


Published at

Book Review: Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NETand

Data Binding with Windows Forms 2.0 : Programming Smart Client Data Applications with .NET (Microsoft Net Development Series)

12:57: I got this book from a friend, and I'm going through it in a speedy pace. I'm only finsihed chapter 2 right now, but I think that I can tell that this is going to be a good book. The datasets chapter was very good, without being condensingly simple, like most of the datasets tutorial that I encountered. As someone who can honestly claim to have never used a data set in a real app (not that I didn't try, I just couldn't make it do what I wanted), I appriciate the kind of treatment of the subject the book has.

I still have to go through more than just the "magic" demos, so I will update this post as I go along.

13:22: I finished chapter 3, which had me buliding a Master - Details relation with grids that is very close to what I need. I'm not sure that I understand how to get this to work with Active Record objects, though. I think that I can make it work. I'll need to see the chapter about binding to custom objects and playing with that a bit to get it to do something useful and pretty. I really like the binding navigator, though, it looks like it can be highly useful.

13:28: Just starting to read chapter 4, and it has a statement there that makes me want to jump up and cry "Halleluja"

This can all be set up in the constructor, and is typically done by dragging and dropping both the grid and the binding source onto the form and setting the appropriate properties in the designer. However, for now, let's focus on how to do things without the magic of the designer.

Now that is my kind of sentiment. Also check the "Code First Versus Design Features First" section in the beginning of the book.

14:21: Found that text boxes in Win Forms 2.0 has auto complete features. I did not know that. This is really cool.

14:36: Chapter 4 done, it was very interesting, and included examples of several interesting scenarios. Formatting / Parsing were interesting, as well as the more detailed explanations of how databinding works.

14:58: Chapter 5 is done. Lots of ways of using the designer. It included some stuff that I think are cool, since I have seen what kind of code I would need to write in order to make the databinding happen (and I know what kind of a pain it is to write this manually).

15:12: Tried to used what I learned so far, but it looks like interfaces & data binding aren't going well. At least with regard to the designer. I tried to bind to ICollection<T> and to IList<T>, and it fails. It works just find on List<T>.  I guess that I have a lot more reading to do.

I need to go ponder the meaning of matrix multiplication in the general scheme of the universe, so I'll post this now, and post the rest of the review when I return to it.

WinForms 2.0 Data Binding Resources?

I'm not a UI guy, not even close. Nevertheless, I need to work with it often enough. Right now I got to write a WinForms UI that involves displaying and organizing data from several sources, Database (via Active Record), Reflection, etc.

I want to use data binding for the whole thing, since the data is basically text and some combo boxes, nothing special. The problem is that while I can find a wealth of information on data binding in ASP.Net via declarative markup, and some information about binding and manipulating datasets in WinForms, I can't find any good explanations on how to do it with business objects (in this case, Active Record objects).

I thought about getting a book, but it is unlikely that I would read it, to tell you the truth, I just don't have the time, and I need the information as soon as possible. An added complexity is that while I have a fairly good understanding on the Win32 controls, (Textbox, ComboBox, ListBox, etc), I know practically nothing about DataGrid, and that is probably what will make the best control for the job.

I got some hierarchy that I want to display (one level only), and I am so not feeling like doing it all by hand.

Any good tutorials on the subjet? I'm pretty clueless about databinding and data grids.p


Published at

How To Optimize Code

A nice post about optimizing code, recommended.

One additional point that I wanted to make, don't optimize the new system based on the bottlenecks of the old system.

Published at

VS.Net resolving references of referenced assemblies

I have a problem with VS.Net 2005, it seems like it stopped copying the assemblies that are referenced by the assemblies that my project is referencing. For instance, I am using Castle.ActiveRecord, which is using Castle.Model. I have a reference to Castle.ActiveRecord, and when I run the project, I get an error because it can't find the Castle.Model assembly.

This is the first time that I got this issue, and googling doesn't seem to find anything about it.

Rude Advertising

Take a look at this suggestion from Phillips, it basically means that your TV will prevent you from skipping commericals (either via DVR or by changing the channel).

The comments are interesting, but I wonder how many of the same comments were made about the no-skip part of DVDs (I promise not to pirate the movie, not will you please skip the five minute if-you-copy-we-will-send-the-army-to-get-you movie that they stick there?) or about advertising in the movies (I got to a movie, and have to sit through 15 minutes or so of advertising before the movie begin. And they are the same advertising over and over and over and over again).

I'm starting to feel even better about my decision to avoid TV in general.