# Tuesday, April 24, 2007
I was going to use the NHibernate facility provided by Castle Windsor until I found out it didn't support using class mapping attributes.  I ended up rolling my own implementation but added a couple new features to my implementation:

  • Automatic context aware session container (web context or thread local).
  • Ability to use NHibernate mapping attributes instead of hbm.xml files.
  • Can use the built-in .NET 2.0 connectionStrings element to specify an NHibernate connection string.
I think the first two items are pretty obvious, but the last feature I added because most standard .NET applications make use of these elements - for better or worse.  I think its a good idea to be consistent if possible.  Additionally this would allow any standard .NET administration tool to examine and edit the connection string for the application.

I also wanted the ability to use a custom configuration section so that I could add additional elements and attributes as needed.  The configuration section handler produces a SessionFactoryConfiguration instance, which itself it a subclass of NHibernate.Cfg.Configuration.  The configuration section looks like this:

  <sessionManager>
    <settings>
      <setting name="hibernate.dialect">NHibernate.Dialect.MsSql2000Dialect</setting>
      <setting name="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</setting>
      <setting name="dotnet.connection_string">Laptop</setting>
      <setting name="hibernate.connection.provider">
         NHibernate.Connection.DriverConnectionProvider
      </setting>
    </settings>
    <resources>
      <resource assembly="Sneal.Northwind.Core" useAttributes="true"/>
    </resources>
  </sessionManager>

Notice the setting dotnet.connection_string.  This is the custom hook I added to my custom configuration handler that resolves Laptop to the .NET connection string named Laptop:

  <connectionStrings>
    <add name="Laptop" connectionString="Database=Northwind; Data Source=.\sqldev2000;" />
  </connectionStrings>

Then I just wire up my SessionManager instance to my Repository instance using an IoC container; currently Windsor.  I have an HttpModule which handles my Unit of Work currently, but unfortunately its tied to Windsor and my current application, so now I'm off to decouple it for reuse.
 

Tuesday, April 24, 2007 5:26:12 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, April 22, 2007
Adding to my previous post, I thought I would also add an example that uses the new LINQ query expression syntax.  The example is pretty much the same as the last, except that I added one additional person to the list and added an aggregate.

public static void DotNet35WithQueryExpresion()
{
    IList<Person> people = new List<Person>()
    {
        new Person() { Age = 28, FirstName = "Shawn", LastName = "Neal" },
        new Person() { Age = 16, FirstName = "Isabella", LastName = "Neal" },
        new Person() { Age = 15, FirstName = "Joe", LastName = "Velope" },
        new Person() { Age = 43, FirstName = "John", LastName = "Smoe" }
    };

    IEnumerable<Person> teens = from p in people where p.Age < 20 && p.Age > 12 select p;
    Console.WriteLine("The following people are teenagers:");
    teens.WriteAll();

    int sumOfAges = teens.Sum(p => p.Age);
    Console.WriteLine("Sum of all ages: {0}", sumOfAges);
}

Looks like I just wrote some statically checked SQL straight into my c# doesn't it?  Seeing how Ayende has declared that queries are a business concern (and I agree) and we now have LINQ, we can finally place our queries where they belong, in our domain/service layer or even our presentation layer.  You could put your queries there before, but the legions of Microsoft followers would cry out, "This is not the MS way!"  It should be much easier to convince the Microsoft drones that still insist on putting business logic in the database, i.e. stored procedures, that queries in fact belong in the application under unit test.  Yes, queries should be unit tested just like the rest of your application!  Remember that queries are business logic.

I'm still not sure if there is a LINQ query expression that I can apply in this scenario that would replace the lambda expression in the Sum function.  Any idea?

Saturday, April 21, 2007 11:20:16 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, April 21, 2007
I finally downloaded and installed Visual Studio "Orcas" beta 1 so that I could start playing around with the new functionality built-in to .NET 3.5.  I wanted to build a sample that compared an implementation between .NET 1.1, .NET 2.0, and .NET 3.5, here's the contrived example that I came up with based on a series of postings by Scott Guthrie.

Each example is making use of a simple POCO, note that in .NET 3.5 the private variables and public properties could be replaced by automatic properties.

public class Person
{
    private string firstName;
    private string lastName;
    private int age;

    public Person() { }

    public Person(string firstName, string lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public override string ToString()
    {
        return String.Format("{0} {1} - {2}", FirstName, LastName, Age);
    }

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}


The .NET 1.1 implementation is pretty terse, and requires the most work on the part of the developer.  Although I think it reads horribly, pretty much any developer (even Mort) can understand exactly what the code is doing.

public static void DotNet1()
{
    ArrayList people = new ArrayList();
    people.Add(new Person("Shawn", "Neal", 28));
    people.Add(new Person("Isabella", "Neal", 16));
    people.Add(new Person("John", "Smoe", 43));

    ArrayList teens = new ArrayList();
    foreach (Person person in people)
    {
        if (person.Age < 20 && person.Age > 12)
            teens.Add(person);
    }

    Console.WriteLine("The following people are teenagers:");
    foreach (Person o in teens)
        Console.WriteLine(o.ToString());
}

In .NET 2.0 things become easier for the developer with anonymous delegates and the new generic List implementation.  The only problem is that the syntax doesn't flow well and Mort might not get it, but at least the nasty foreach statement is gone.

public static void DotNet2()
{
    List<Person> people = new List<Person>();
    people.Add(new Person("Shawn", "Neal", 28));
    people.Add(new Person("Isabella", "Neal", 16));
    people.Add(new Person("John", "Smoe", 43));

    List<Person> teens = people.FindAll(delegate(Person p) { return p.Age < 20 && p.Age > 12; });
    Console.WriteLine("The following people are teenagers:");
    foreach (Person o in teens)
        Console.WriteLine(o.ToString());
}

Things in .NET 3.5 become a whole lot cleaner and elegant.  The people.Add() statements are replaced by much cleaner object initializers.  I also used the object initializer syntax for each person instance, even though I provided an overloaded ctor; in .NET 3.5 I could actually forgoe the overloaded ctor.  The most interesting part is that the List.FindAll has been replaced by a LINQ Where extension method with a lambda expression argument - compare that to the .NET 1.1 implemetation!  The final bit is that I added my own WriteAll() extension method just for fun.

public static void DotNet35()
{
    IList<Person> people = new List<Person>()
    {
        new Person() { Age = 28, FirstName = "Shawn", LastName = "Neal" },
        new Person() { Age = 16, FirstName = "Isabella", LastName = "Neal" },
        new Person() { Age = 43, FirstName = "John", LastName = "Smoe" }
    };

    IEnumerable<Person> teens = people.Where<Person>(p => p.Age < 20 && p.Age > 12);
    Console.WriteLine("The following people are teenagers:");
    teens.WriteAll();
}

public static class MyExtension
{
    public static void WriteAll(this IEnumerable enumerable)
    {
        foreach (object o in enumerable)
            Console.WriteLine(o.ToString());
    }
}

I'm now thinking of using .NET 3.5 on my current pet project - LINQ and extension methods are absolutely fantastic!


Saturday, April 21, 2007 4:40:08 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, April 18, 2007
I came across a cross cutting infrastructure requirement today that would have been best solved by using AOP.  Since the application I was using already uses Spring.NET I immediately thought about implementing a method interceptor using Spring.NET's AOP facilities, I even found an interceptor already coded on the web that was exactly what I needed.  Of course there was one problem, .NET defaults all public methods to non-virtual and the class I was trying to apply AOP to was a wsdl.exe generated class with non-virtual methods.  This meant that Spring couldn't generate an AOP proxy at runtime for the method I wanted to add a pointcut to.  Argh!

I think defaulting every public member in .NET to virtual would have been a better decision than defaulting to non-virtual.  Java doesn't have a virtual keyword, every public method in Java is virtual by default.  Isn't that the whole point of OOP and inheritence?  At a whim, I should be able to subclass and override ANY public method.  Yeah, I may implement things incorrectly in my subclass, but the onus is on me.  Not marking methods virtual in .NET is basically saying you don't trust the next developer.  This is especially annoying since dynamic subclassing has become so common ala DynamicProxy.  Want to use NHibernate with lazy loading?  Well you can't unless you mark everything explitly virtual.  All this means to me is extra cutting and pasting; of course I'm going to make everything virtual.  My point is that virtual should be the default, it should be extra work to make it non-virtual - just like sealing a class.

Some of you may say, but virtual methods are slower than non virtual methods because of the method lookup.  True, virtual methods are slower, but...  And this is a big one, all method calls in c# are virtual method calls, regardless if they are marked virtual or not.  If I'm already paying the price of having virtual methods, then why can't we just treat them as such in code?!

Wednesday, April 18, 2007 10:49:28 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, April 15, 2007
I just wrote my first Mono c# program, talk about easy.  The hardest part was figuring out how to invoke the mono c# compiler, and no its not csc, but mcs.  Mono can be installed from the Ubuntu "Add Applications" applet, but its actually easier and more direct to install it from the shell:

sudo bash
apt-get install mono mono-gmcs


Once Mono is installed you may want to install a text editor or MonoDevelop.  I just installed a text editor, called Cream, which actually picked up the syntax highlighting which surprised me.  Anyway I preceded to put together helloworld.cs in my home directory:

using System;

namespace SNeal
{
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World, from Ubuntu!");
        }
    }
}

Then from the shell again:

mcs helloworld.cs

Which produced helloworld.exe which can then be run (very similar to Java in this respect) by typing:

mono helloworld.exe


That's all there is to it!  Further things I plan to try out on Ubuntu with Mono: Generics, ASP.NET, NUnit, MonoDevelop, and Eclipse (which is my favorite IDE).

Sunday, April 15, 2007 6:41:21 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
Now this is what I consider a good morning:



Virtual Server 2005 R2 with Visual Studio Orcas CTP and VMWare with Ubuntu for other dev...
Sunday, April 15, 2007 3:57:07 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Friday, April 13, 2007
I really don't understand why Spring and thus Spring.NET chose to default all objects or beans to singleton scoping.  I mean why?  In my experience singletons are rare magical beasts that usually only exist because they act as a sort of service locator.  When I use any plain old C# object I have to use the new keyword.  I'm comfortable with the new keyword, and would seriously miss it if all my classes were forced to be singletons right out of the box.  You can think of the code that you write as the blueprints for constructing a new instance at runtime, well I think that should apply to the XML you use to wire objects up in Spring with - blueprints for new objects, not singletons!  Instead the designers of Spring chose to default to singleton prototyping so that every object I declare in my XML config only ever exists once.  This is a serious scoping mismatch especially when writing something stateless like a web application where you want new instances for each request.

Why am I ranting about this anyway?  I ran into a very subtle state bug where I forgot to set singleton="true" on one of my ASP.NET controller objects, so each request was using the same controller class instance.  This may explain another error that the testers were getting at times: Request is not available in this context.

IoC
Friday, April 13, 2007 9:45:39 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Wednesday, April 11, 2007
There may be a time you need access to the current executing ASP.NET handler's (page) view state without having a reference to the executing page.  I did today while creating a view state adapter that is injected into my page controllers.  I swapped out the Session adapter for this new ViewState adapter in my Spring.NET config.

Here's the code where I grab a view state reference in the adapter:

return ((PageBase)System.Web.HttpContext.Current.Handler).PageViewState;

Basically I grab the current handler and cast it to PageBase type.  In my application all pages inherit from PageBase, and PageBase exposes a public PageViewState property.  This allows me to grab the viewstate without having a direct reference to the page instance.  Some of this extra work is required because the System.Web.UI.Page ViewState property is not public, but protected.

Wednesday, April 11, 2007 8:53:47 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, April 06, 2007
Before running NAnt that uses the P4Edit NAntContrib task ensure that you go into P4Win and from the menu select Settings | Use Current as Default.  Without doing this you may run into an error message that [some file] - must refer to client '[client name]'.

Ant
Friday, April 06, 2007 9:16:52 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
I'm not sure hardware currently supports this, but it would be really cool if there was a web browser GPS control, header - or something to that effect.  Basically the idea is to be able to perform a search through your web browser that uses your GPS location as one of the search parameters.  This would be incredibally useful for handheld internet devices.  My navi in my truck already does this when I need to find a gas station, bank, or restaurant nearby.  Handheld browsers should be able to do the same without the user needing to manually input a GPS coordinate.  Think realestate listings.  You're driving down a nice neighborhood and you want to search for all listed houses within 3 miles, with GPS coords this would be a snap.  What if you are standing inside a store?  You could go directly to the store's web site just because you are physically standing inside it.  I think people would really dig this - I know I would.  What about location aware internet advertising?  This is just the tip of the iceberg, especially once everyone has a phone that also acts as an internet connectivity device.

Friday, April 06, 2007 5:46:32 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, March 27, 2007
I have finally come to the realization that my mindset, beliefs, programming methodology, and above all my spirit are incompatable with my current employer.  I need to work for IT company again.

WTF
Tuesday, March 27, 2007 9:59:20 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  |