Nhibernate Many-to-many mapping with an Enumeration on One Side

I’m posting this because I was trying to do this in an intuitive way and was thinking about it in the wrong way. A post on StackOverflow,  Map to a list of enums, got me pointed in the right direction.

I prefer using Enum’s in code, in place of database lookup tables, doing this for single properties, it makes sense to just map the Enum value into the database column of the owning entity. However when thinking about mapping many-to-many, for example, the US States a person has visited, and you fall into DB thinking mode. Many-to-many is the solution, unless States is an Enum and that’s all you need. In that case you should think about the problem for the domain side, a person as a list of visited States. In this way, you only need to have a one-to-many relationship, where the many side is the Enum value.

Adding something like the mapping code below to you Person mapping will get a VisitedStates table with a PersonId column and StateId column. No lookup tables needed, of course one could be added to help the DBAs. In the code you have a States list on the Person class.

<bag name="States" cascade="all" table="VisitedStates">
  <key column="PersonId"/>
  <element type="States" column="StateId" />
</bag>

Advantages

  • No mapping table.
  • Lookup data defined in code, as an Enumeration.
  • Less classes and mapping files.
  • Don’t have to worry about updating a lookup table with new values.
  • Don’t have to worry about making a State class with a immutable mapping.

Disadvantages

  • DBAs won’t know the values without maintaining a lookup table (even if it doesn’t get used by code).
  • Can not reorder the Enumeration values without updating the DB.

Other advantages/disadvantages?


PowerVim, setup VIM to use Powershell

[https://candland.net/assets/binary/PowerVimsetupVIMtousePowershell_DAD5/vim_logo_2.png]

I’m using VIM more and more and have come to the point where issuing commands to the shell would be useful, the problem is I use PowerShell. This is fairly easy to setup in VIM, but I did hit two things that needed to be worked around. Script execution issues and my ps profile script changing directories.

First script execution, by default, does not allow custom scripts, like your modified ps profile. This was easy to take care of in the _vimrc file. Here’s what I added to setup PowerShell:

 # change to powershell       
 set shell=powershell.exe\ -ExecutionPolicy\ Unrestricted
 set shellcmdflag=-Command
 set shellpipe=>       
 set shellredir=>

You should also make sure to set your VIM encoding=utf-8. With that in place, PowerShell can be invoked and it will load your profile. However…

My profile always sets the current directory to my projects folder, which is good except when it’s being opened by VIM. Here’s my fix.

if ($HOME -eq $pwd.path) { 
   cd $projects 
}

With those changes in place I can now issue PowerShell commands from within VIM.


Psake Tab Expansion!

After installing the awesome posh-git stuff, I thought “it would be cool to have tab expansion for my psake tasks”. So, I read the posh-git stuff and decided it would be easy to follow the pattern they’ve used and adopt it for psake. That a complement on the job the posh-git guys have done and with only about 23 lines, a complement to the power of Powershell.

Anyway, below is how I integrated both posh-git and psake tab expansion into my powershell profile after including the PsakeTabExpansion.ps1 file.

After installing the awesome posh-git stuff, I thought “it would be cool to have tab expansion for my psake tasks”. So, I read the posh-git stuff and decided it would be easy to follow the pattern they’ve used and adopt it for psake. That a complement on the job the posh-git guys have done and with only about 23 lines, a complement to the power of Powershell.

Anyway, below is how I integrated both posh-git and psake tab expansion into my powershell profile after including the PsakeTabExpansion.ps1 file.

# Set up tab expansion and include git expansion
function TabExpansion($line, $lastWord) {
  $lastBlock = [regex]::Split($line, '[|;]')[-1]

  switch -regex ($lastBlock) {
      # Execute git tab completion for all git-related commands
      'git (.*)' { GitTabExpansion $lastBlock }
      '(Invoke-psake|psake) (.*)' { PsakeTabExpansion $lastBlock }
      # Fall back on existing tab expansion
      default { DefaultTabExpansion $line $lastWord }
  }
}

The zip file has a readme w/ some sample code to drop in your profile. And the PsakeTabExpansion.ps1 flie, which I have in the same directory as my profile. I’m going to send the psake team, hopefully they will add it to the psake codebase.

PsakeTabExpansion.zip


Ensure Spark Views Are Marked As Content With Powershell

I kept publishing a website project only to find each time a couple of spark files didn’t make it because they were not set as content in the cs project file. In order to limit the wasted time, I added the code below to the build script.

Below I’m using the following to grab the project file as xml. Then foreach (|%) None element in Item group elements. Where (|?) the Include attribute is a spark file, add to the $notset collection. If any, then list and throw to stop the build. This was just added as a psake task. BTW, I’m really loving psake, you should really check it out if you need a build script on windows, for anything.

$basedir = Resolve-Path .
$proj = [xml] (get-content "$basedir\src\website\website.csproj")
$notset = $proj.Project.ItemGroup |% {$.None} |? {$.Include -like "*.spark"}

if ($notset.Count -gt 0) {
  $notset; throw &quot;The above Spark files not set to content.&quot;
}

Mapping NHibernate many-to-many with a Class for the Joining Table

I wanted to have a many to many association in nhibernate so that additional info can be added to the joining table. Like the date the relationship was setup. I couldn’t quickly find anything on google, but then remembered that this is really 4 associations in nhibernate; one-to-many : many-to-one for ClassA and one-to-many : many-to-one for ClassB.

In this example we’re not going to map one-to-many from ClassB. ClassB will not know about this relationship, which will result in orphaned records if we delete any ClassB records.

Mapping for Class A:

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" default-lazy="true" assembly="Core" namespace="Core.Models">
  
    <class name="ClassA" table="classA">
        <id name="Id">
            <generator class="guid.comb"></generator>
        </id>
        <set name="Matches" cascade="all-delete-orphan" lazy="true" inverse="true">
            <key column="ClassAId" />
            <one-to-many class="ClassAMatch" />
        </set>
    </class>
</hibernate-mapping>

Above ClassAMatch is the many-to-many class. The set is the one-to-many association to ClassAMatch.

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" default-lazy="true" assembly="Core" namespace="Core.Models">
    <class name="ClassAMatch" table="ClassAMatches">
        <id name="Id">
            <generator class="guid.comb"></generator>
        </id>
        <many-to-one name="ClassA" column="ClassAId" lazy="false" cascade="none" not-null="true" />
        <many-to-one name="ClassB" column="ClassBId" lazy="false" cascade="none" not-null="true" />
        <property name="MatchedOn" not-null="true" update="false" />        
    </class>
</hibernate-mapping>

Above, this sets up the many-to-one associations to ClassA and to ClassB. This will be enough to persist the relation, but remember it will leave orphaned records if ClassB records are deleted since ClassB doesn’t know about his relationship/association. To fix that add a similar set mapping to that shown for ClassA.


Warming up to MVC2, Castle, and Spark with Red Yawk

Red what? Red Yawk (silent W), as in Red27 Consulting’s Yet Another Web frameworK. I’m not sure I really like the name, but it’ll work for now.

I spent a good part of today trying to decide on what web framework to use for some upcoming projects. I spiked with FubuMVC, which I would have liked to use, but the lack of documentation and my lack of knowledge about it was too much to overcome right now. I also spiked MonoRail, which I’ve used in the past and generally like. The main thing here was the lack of portable areas. So, I settled on Asp.Net MVC 2. I like the idea of portable areas, I’ve been working with MVC 1, so I’m familiar with a lot of helpers and architecture. I like that n2cms works well with it. And companies will most likely feel better having there site built on in simply because Microsoft is behind it. Regardless, I had to pick something.

The goal is to have a solid base project to start with, without rebuilding everything every time a new project is started. Some requirements from me; Areas, Container (prefer windsor), Spark, and ultimately the ability to add on binary extension, portable areas. Also, it’s using Psake for build support, NUnit for testing, MongoDB for the document database.

I recently saw a post about Warmup, which seems like it would work well, and so far it has. I think I’ll have other warmups, that include NHibernate support and n2cms support later

Checkout the start of the project at http://github.com/candland/redyawk-warmups. Once, warmed up you can run the psake script to build and test, you’ll need to install psake or import the psake module in the tool directory.

Is there a directory of Warmup templates?

Is there a directory of Portable Areas?


Resolve Lists and Arrays with Castle Windsor

I’ve worked with the Castle Project for a long time, primarily with Windsor. However, I often forget there are Array and List dependencies resolvers build-in, but they need to be wired up. This is mostly for my memory and hopefully it helps someone else.

This sub resolvers are in this namespace;

using Castle.MicroKernel.Resolvers.SpecializedResolvers;

Before registering components, add the sub resolvers;

container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
  
container.Kernel.Resolver.AddSubResolver(new ListResolver(container.Kernel));

Use like this, where there are multiple IService implementations that are needed by the DependsOnArrayOrList class.

public class DependsOnArrayOrList
{
    public DependsOnArrayOrList(IService[] services)
    {
    }
  
    public DependsOnArrayOrList(IList<IService> services)
    {
    }
}
  
public interface IService
{
}

Not sure why these sub resolvers are not setup by default, but regardless they’re easy to setup and come in handy.


Brutalist Framework