NHibernate – Find not returning a result?

July 20, 2006

I was having an issue with NHibernate a while back (which I fixed a while back :-P) – anyway – here’s the problem and a hopeful fix if anyone else has come across the same thing. Maybe it might be something to go into the NHibernate base… Although I noticed with the new 1.2.0 Alpha release Find is being deprecated so maybe this comes a little late but anyway… It might be something you also want to patch in as I did (into the 1.0.2 release and the 1.2.0 Alpha releases – it still exists in the 1.2.0 Alpha release) 🙂

 The problem was when I did a search over a entity and the field I was searching on contained both full stops(.) and commas(,), even though I could see the entity in the database, it wouldn’t return it – it would always say the entity didn’t exist (if I escaped it – rightly so – the fields wouldn’t match) but if I didn’t escape it it would start throwing exceptions – arrrhhh. For example, say I was looking for a company with the name “BigCompany, United.” using Find – I would get nothing (escaped) or would blow up (unescaped). What was going on? Time to bust out the source code 😀

 Here’s the query at fault:

array = (ArrayList)session.Find(string.Format(“from Business.Mappings.Company as company” +
      ” where company.Name = ‘{0}'”,
       Utils.GetSafeQueryParameter(comapnyName)));

The problem exists down in the parsing of the find string. When it comes across commas and full stops it tried (if it wasnt escaped) to cast it to a class in the solution – if it failed to cast it would blow up. Trying to modify the source as little as possible, so everything else will stay the same, (theres some code down in here that really needs to be tidied up by the NHibernate crew – sorry guys) I did the following:

In the class ReflectHelper, in the method GetConstantValue I moved the try up 2 lines – so the exception will get caught and then the code that calls this will fall back on the “else” action (to pass the string through as a parameter – what we want). Here’s the modified method:

public static object GetConstantValue( string typeName, string fieldName )
{
    try
    {
        System.Type clazz = System.Type.GetType( typeName, false );

        if (clazz == null)
        {
            return null;
        }
        else
        {
            return clazz.GetField(fieldName).GetValue(null);
        }
    }
    catch( Exception )
    {
        return null;
    }
}

Drop that guy in and away you go 🙂 The problem is that with any extension dll’s they are compiled against a signed version of the NHibernate dll 😦 (which I dont have) To get around this I either had to recompile the extension packages from source – or – using reflector dissassemble the dll back to source so I could recompile it – or – in one case (where reflector was throwing hissy fits on some generics that were being used) dump the dll out to msil – delete the signed part form the msil code (its near the top of the file) and then reassemble it – turned out to be a little mission but fixed a bug that was really bugging me… Was good to get it solved 🙂

If anyone finds this useful then let me know/forward on a link to the Nhibernate guys… 🙂

NHibernate – SQL2005 Dialect

July 20, 2006

I had a random error happening the other day when I was running an NHibernate based app I was working on – the problem was the error (“Unable to perform find”) would only happen every now and it wasnt consistantly occurring in the same place. After a bit of digging I read a few other people where having similar issues – running on Sql2005 – something to do with the way 2k5 works with returning rows in certain block sizes… anyway I grabbed the Sql2005 dialect, compiled a dll and chucked it in – as I said the errors seemed to be sparatic… hopefully its fixed now but if anyone else is having the same problem then maybe give this a shot 🙂

 I originally got the dialect file off a link from Ayende Rahien’s blog: http://www.ayende.com/

I can’t find it now but I’m sure google might show you some love 🙂 If not then flick me an email and I’ll send you a copy…

In the config file you need to change the dialect setting:

<add key=”hibernate.dialect” value=”NHibernate.Dialect.Extension.MsSql2005Dialect, NHibernate.Dialect.Extension” />

Note the fully qualified class name and then the assembly name (the assembly you compile containing the new dialect will need to be referenced in the project or signed and placed in the gac) 🙂

DLinq

June 9, 2006

Ahhhh – DLinq if you haven't read about this or had a play with it then DO IT NOW! But be careful – you may love it as much as me and just wish it was out there now 🙂 I had a play with it way back at the first cut, liked it (but then kind of got busy on other stuff) –  and then havent got back to it until a couple of weeks ago. Finally after looking at the msi for over a month I decided that it was about time to install that puppy and see where it was at…

If your just starting then make sure you look at the help files – probably the "DLinq Overview for CSharp Developers.doc" in the Docs folder of the install. Theres a few quirks with the install but you'll get the drift and be praying for its final arrival too 🙂 I for one couldn't get the templates in – damn – yep I ran the vbs file to install it but still no luck – the only thing I really achieved was breaking the information tab guy in the ide (see msdn for an article on the reg key to edit on how to fix that) but no matter what they wouldnt go in. I ran the various scripts people had posted as fixes but still no love. Finally it was down to editing the project file 😀

If you edit the project file (in something like notepad) – just change the following line from this: <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

to this: <Import Project="$(ProgramFiles)\LINQ Preview\Misc\Linq.targets" />

 (this was with a console app)

Good times! You should be able to compile it but you may not get any ide support. Its not the "best" but it is a beta and you'll at least be able to write your own little apps for a bit of a play :-)… The other thing to check out is the SqlMetal.exe in the Bin folder of the install – this will reverse engineer the class's for you from a database. It seems to work and is the first step to getting some DLinq love! Some inital cool things I noticed was that it uses nullable types and generic collections – and does seem to work (although my database wasnt that complicated). Something I would like added though is when you do a 1-1 table mapping is a constructor on each class that takes in each of the "non-nullable" arguments for that table… this in my opinion is one of the most helpful things out and is something I have had to put into a number of different generators/generator extensions – it would be something pretty cool to get straight out of the generation box 🙂 (maybe I'll write a template and chuck that up… – man – so much to do 🙂 )

Things I picked up on were: attaching/detaching objects is easy, the model to work against is very intuative, it works (always a good one), it supports both lazy and greedy (?terminology) fetches by specifying the mode in the query – pretty cool! – the rest you will see when you play with it 😉

Some things that I'm not in love with are: the ide support (it will come 🙂 ) and var – I know all about var but the thing I hate is that its not a type when you look at it in your code – with your eyes – you have to go fishing. Its the same kind of thing with moving from ArrayList to List of T – you immediatelly look at a typed list and understand it. var to me feels like the ArrayList of C#3.0… just my thought in terms of looking at code – not around compilation etc but just around looking at it…

Anyway – check out DLinq – its awesome! 😀

http://msdn.microsoft.com/data/ref/linq/

OpenAccess

June 9, 2006

Hmmm – time for a few blog posts I think… well some short ones just on a few random bits and pieces I've played with (in amongst the busy but boring times at work lately 🙂 ). One product I had a bit of a play with about a month ago is Vanatec's OpenAccess. While I don't agree with some of there statements regarding NHibernate I did think it had a few pretty good features (they just need to be finished/extended). If your playing with NHibernate then this maybe worth a look at too just as a comparison.

One thing that is pretty cool is how smoothly it integrates into Visual Studio along with the "in the box" reverse engineering option – no need for bamming out your own generator 😉 – basically from inside Visual Studio you can point it at a database and you get your initial cut of classes to work with… thats pretty cool as you can try something pretty quickly – im not sure how good/robust it is for use in a real world scenario though – Ill leave that up to you 🙂 . Theres also a few other bits like web service support etc (its in there but to me still looks to need some work) which is nice to see but is not really as complete as I would like it to be – no doubt it will continue to be extended 🙂

The model seems pretty easy to work with and it does seem to work but one thing I didnt like was debugging it – sometimes it wasnt that intuative (and there seems to be some j# / java going on under the scenes (its been a while since I fired it up) – but its not that cool to see .java.lang… throwing out errors when your running on .net 🙂 )

 Anyways – not really here nor there on it but it is worth a bit of a play with if your looking around at O/R mappers and have been investigating NHibernate. They have a free trial download so install it, read the help, look at the samples and see what you think 🙂

http://www.vanatec.com/en

A few random bits:

April 29, 2006

"Code Camp" was on last weekend and there was a number of cool things shown off. Two classes I picked up on and everyone should check out are ObservableCollection of T and TransactionalCollection of T… No doubt checking out/using those will take you on a little tour of some cool bits and pieces out there in .Net 2.0 🙂

Going completely on another tangent this is also something that people might want to check out especially if you are into FPGA's – I noticed it was just posted up a day or so ago: http://www.netbsd.org/Ports/evbppc/

As for other things I have been working on, I now have sound in my code generator! I installed Quake 3 again for a Lan we had the other day and after realizing that a pk3 file is a zip file (for Quake anyway) I was able to extract some of the sound files. It's definitelly cool to generate with this bad boy now 🙂 The generator uses MyGeneration which is based on .Net 1.1 so I had to use the following to get to play the sound files:

using System.Runtime.InteropServices; …..

[DllImport("winmm", CharSet = CharSet.Auto)]
 public static extern long PlaySound(String lpszName, long hModule, long dwFlags); ……

PlaySound(@"F:\Program Files\MyGeneration\Templates\NHibernate\regeneration.wav",0,0);

(Note the file name! Yeah – thats the buisness!) 😉

Other stuff I'm working on is setting up Lighty + RoR and expermenting with a few different things in relation to hosting. I have Lighty working through scgi with RoR on top of a Postgres database at the moment… Maybe I should post up some details on that? 

My most favourite thing lately must be vmware – if you havent got this – seriously – get the free copy – its excellent to work with 🙂 The only thing to watch out for is if it says it can't find a bootable cd: 1) Check the vm's bios (F2 when you start the vm – move the cd rom drive to the top – the boot order is on one of the last tabs), 2) Check that the virtual machines cd rom is looking at your cd rom – sometimes the auto detect doesnt pick up the right one so just set it to look at your normal physical drive – once you have that sorted it should be smooth sailing.

The only issues I've had so far are to do with installing Fedora (very slow, booting etc, even when there lots of Ram allocated). As for windows/ubuntu – I would say once you install the vmware tools they are just as good as a physical machine…

Oh, and if your into starting working with device drivers on Linux then check out this article: http://www.freesoftwaremagazine.com/articles/drivers_linux With a good book to follow up with afterwards you should be away 🙂

VMware – Browser Appliance, IE6

April 13, 2006

I was reading Aprils atomic magazine the other day and spotted a small piece on vmware and there Browser Applicance – basically its a vm download of around 250M with Ubuntu and Mozilla installed. The idea is to run your browser inside the vm to keep your main machine all nice and clean – good idea – but nothing you couldn't setup yourself. The cool thing is it is all done and just seems to work – run the vm up, it connects to the network and away you go. (It also lets you have a look at Ubuntu as well if you haven't already done that – the version is a little old now though – the current Browser Appliance download uses version 5.10)

After I grabbed the download I decided to chuck on ies4linux (installed wine and cabextract first – follow the instructions here: http://www.tatanka.com.br/ies4linux/en/instructions/ ). This is very easy to do – tick a couple of boxes, double click a script, it does some downloads and its done – installing on linux has never been easier :-). Bascially I wanted to see how wine was going since I haven't used it for a while and I also find things like web outlook etc need IE. Anyway – it seems to all work and layout pretty nicelly (may need some font packs) – so could be something to give a try – considering everything (even vmware) is free you can't really go wrong 🙂

log4net – Logging for your .Net Apps!

April 10, 2006

Ok I’m no log4net expert but it is a very cool package that everyone should use – believe me – it’s very quick to chuck in and will save you mountains of time and make you look like a pro without even really trying 🙂 It’s been around for along time (google for lots of tutorials etc) but I thought I’d put up my most basic x step guide to get running with log4net (this is once again so I can remember too 🙂 ):

1) Grab the log4net dll and register it in the project you want to use it in. (http://sourceforge.net/project/showfiles.php?group_id=31983&release_id=171808)

2) Make up a static class / singleton and chuck something like this in it:

private static ILog _log;

….

XmlConfigurator.Configure();
_log = LogManager.GetLogger(“GlobalLogging”);

…..

public static ILog Log
{
     get { return _log; }
}

3) Chuck a section like this in your main app.config:

<configSections>
 <section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler, log4net” />
</configSections>

<log4net>
 <appender name=”FileAppender” type=”log4net.Appender.FileAppender”>
  <file value=”Log.txt” />
  <appendToFile value=”true” />
  <layout type=”log4net.Layout.PatternLayout”>
   <conversionPattern value=”%date [%thread] %-5level %logger – %message%newline” />
  </layout>
 </appender>

 <appender name=”ConsoleAppender” type=”log4net.Appender.ConsoleAppender” >
  <layout type=”log4net.Layout.PatternLayout”>
   <conversionPattern value=”%date [%thread] %-5level %logger – %message%newline” />
  </layout>
 </appender>

 <root>
  <level value=”INFO” />
  <appender-ref ref=”FileAppender” />
  <appender-ref ref=”ConsoleAppender” />
 </root>

<logger name=”GlobalLogging”>
 <level value=”INFO” />
 <appender-ref ref=”FileAppender” />
</logger>
</log4net>

Note: Get rid of the console appender if you just want to chuck the logs to a file.

4) Use your logger: Helper.Log.Info(“This is a log message”);

Now there are different types of messages (warn, info, debug etc) so these types need to be specified in the config – just add <level /> nodes in for the ones you want to log – if they arent in there then they get ignored and wont be written to the file 🙂 That’s how you can say do logging on development (debug) and then turn those off on production without changing your code! Just remove your setting from the config!

Another trick is to use logger sections with named loggers (note the “GlobalLogging”). By getting rid of the <root /> node and only having the logger node you can filter the messages down. This is useful if other components also perform logging but you dont want there messages to come through i.e. it can be used as a filter 🙂

Anyway, its really easy to use and you will get the hang of it “just like that” 🙂 – definitelly worth much more than the 2 minutes it takes to chuck in!

Castle Project

April 10, 2006

I’ve been meaning to post about this stuff for weeks but I can’t seem to find the time so just go here and check it out for yourself 🙂 http://www.castleproject.org/index.php/Main_Page It’s definitely worth the effort! In particular I was loving the Active Record pattern/generator they have built to sit over NHibernate. I could’nt get the generator gui to work (seemed to be broken) but I may have just been having “one of those moments” at the time 🙂

It seems to be getting better and better – lots of examples in the solution and it seems to be pretty self explanitory at how the basics work – if you have written an NHibernate solution then there’s no doubt you will love this – if you havent then it’s probibly not a bad idea just to grab this guy straight off the bat 🙂

Kororaa – Prepacked XGL

April 10, 2006

If you want to play around with Linux (or get an install an up and running quickly) then you can't go past Kororaa (http://kororaa.org/) – Just download the iso, burn a bootable image, boot from the cd and away you go! This guy comes prepacked with all the stuff for Xgl and "just works" straight out of the box – check out the screenshots if you havent seen xgl running – this is very cool! The linux system you have always wanted 🙂 Bascially its a prepacked gentoo install (with xgl) just to get you up and running really quickly.

The part I liked most is that I could have a play with xgl without prep'ing my machine and then spending a week downloading packages and trying to get it all setup – it just worked 🙂  I run an ATI 9800 and it had no problems – came up first time – all the effects worked! Ye-yah! The only issue I found (which they already had logged in the known issues) was that the terminal doesnt work under gnome with an ATI card (how an issue like that comes about I dont know!) but in KDE it was away 🙂 I'm thinking this is cool enough to do a full install which also is just a click away 🙂 If you are thinking that you wouldn't mind checking out xgl then this is definitelly the way to go 🙂 

 Top marks to the Kororaa team – this is awesome! 😀

Xbox360 and DivX (VLC360)

March 30, 2006

So the Xbox360 got released here on the 23rd of March and for a start I wasn't really planning on getting one (go the ps3 in November 😀 ) but then we decided to go for a little "look". Well….. yeah….. it was raining so the weekend was going to be an inside one…. and November is a long time away…… so yup – before we knew it we were on a mission to Johnsonville (town had sold out) to get one and a couple of hours later we were back getting it all fired up!

I wont go into a talk on the console but my briefest discussion on it is: games are cool, wireless controllers are awesome, os/user interface is very easy to use/well put together, the unit does get hot so dont stand/lie in on the carpet (i got some graphics glitches after about 4 hours of game time – PGR3 – don't know how hard this drives the unit it but it looks like it would be a good test?), its a shame it doesnt support more codecs etc out of the box… but anyway read on 🙂 (/\ndrew sent me a link today of a guy with some water cooling 😀 pretty cool but I think I'll stick with the fans).

Ok so the xbox is running but now I wanted to play my videos, music etc etc. Ah – you need a Windows Media PC (or do you? 😛 ) I couldnt really afford a media pc so I decided to try out the old virtual machine – and it worked! 😀 First I stopped off at www.vmware.com and got a free download of VMware Server – very easy to use, performant, and has just become free (or for a time? I'm not to sure on this one), installed Windows XP into a virtual machine with SP2 and then put the Windows Media Center install over the top.

Then I connected up the xbox to the lan and it game me a code when I fired up Media Center on the remote, went to the website and did the 80M download (dont do the small one – 7M one – this will install the software but doesnt ask for the xbox code and it doesnt want to work). All cool – the xbox was now talking to my VM 🙂 I shared up my music and the xbox was away – Now for the video…

First I tried this one http://www.mperfect.net/mceDivX360/ (and yeah it does look like it would work – but it didnt want to for me – I'm not sure if the video wasnt supported (Media Encoder loved it, along with Media Player) or maybe I just didnt set something up right….(btw good work to all the guys out there working on all of this stuff – its really cool! – more and more seems to be popping up everyday) ) so I then went on a scout  and found a version of our friend VLC for the 360 here 🙂 http://jortega74.free.fr/error.html .

Its called VLC360 and it just works! Map your network drives (so it can see them and you are away!) My videos are now streaming from my VM pc down to the 360 through a network share off my normal pc – No extra pc needed! 🙂 Its just like I was playing the videos on my pc and seems to be really good quality. I have a 64 bit 3200+ with 2G of RAM and it seems to sit at about 35% CPU utalization – the network traffic is pretty much nil – no hanging, glitching or anything. Really cool – If you have a 360/planning on getting one and you need divx then this install comes highly recommended – and yep – the VM's are a cheap/good option too 🙂