Being lazy is its reward...

time to read 3 min | 490 words

Sometimes, being lazy is its own reward. Too many times, when I need to finish a task, I just go ahead and implement it. I usually manage to complete those tasks, but sometimes it's ugly or inefficient. Sometimes, the task seems impossible.

 A case in point is trying to build the NHibernate mapping GUI. NHibernate uses xml files for configuring the mapping options, and the mapping schema is over 1000 lines of complex xml.

At first, I just read the docs and tried to implement the UI. That worked, but there were a lot of things that I didn't support or only supported, and any change would cause me great pains.

Then I thought about first doing the model in code and then mapping it to the UI, that would've worked, but it would have required me to rebuild the mapping schema in code and again, any change would've cause pain.

I thought about code generation, and just when I decided that I don't want that because it would be harder to write the code generation code as it would be to write the code once (as I don't suppose that the mapping schema would change very often).

And then I remembered Xsd.exe, this is a tool that takes xml schema and convert them to code that can be XML - Serialized. I tried that, and it seems that I'll only need to write a mapping from the UI to XML serialization and that would be it. Further more, I would probably be able to do that for other schemas as well. I might lose something in the process, because I would lose the knowledge that a class element is more than just a string, but I think that this is a problem that would be much easier to solve than the first one.

Do you know that feeling when you have everything suddenly fall down together just the way it should be? That is how it's feeling now; it's just very natural to code this way.

Now, it's certainly not perfect, and there are several cases where I need to edit by hand, but xsd.exe did 99% of the work.

Apparently NHibernate mapping is complex enough that you cannot use the output from Xsd.exe directly, you would get exceptions from XmlSerializer. I consider this a bug in XmlSerializer, btw. The problem is specifying one element or more, which NHibernate does using this format:

<xs:sequence>

     <xs:element ref="column" />

      <xs:element ref="column" maxOccurs="unbounded" />

</xs:sequence> 

And Xsd.exe translate to:

public column column;

[System.Xml.Serialization.XmlElementAttribute("column")]

public column[] column1;

 

Then the XmlSerializer complains about 'column' already defined in this scope.

I solved this by removing the column variable, but I don't think that this should be the way to go.

In the meanwhile, I'm going to post it both to Microsoft and NHibernate, and see what come up.

But this is the first approach I've tried that took me so far, so fast.

 

 Robert A. Heinlein wrote a book about it in "Time Enough For Love"