Rails AJAX Posts Session Reset

Notes regarding AJAX post requests being logged out on Rails. Seems the problem is not adding the CSRF data.

The problem was that AJAX post requests resulted in a redirect to the login page. Further inspection showed the cookie was being passed, but the session on server was empty. Rails wasn’t getting the correct CSRF value and as a result, resetting the session data.

This StackOverflow post has some useful info Rails not reloading session on ajax post.

This lead to a post by Jason Weathered CSRF vulnerability in Ruby on Rails 2.3.10 & 3.0.3.

Which ended up at the jQuery UJS project. Installing this fixed the problem!

Moving My Blog to the Toto Ruby Blog

I’ve decided to switch this blog off wordpress and go w/ something closer to the metal. Toto is a rack based blogging engine that uses markdown and basic test files. This is a good approach because you get complete control, but also an editing environment that’s close to normal coding. Heres some links that helped me get up and running.

Getting Started With toto

XmlRPC UTF-8 Fix

Blogging With Toto

require 'rubygems'
require 'fastercsv'
require 'xmlrpc/client'

USERID = '<userid>'
PASSWORD = '<password>'

# http://www.eggheadcafe.com/microsoft/Ruby/36270580/xmlrpc-rexml-incorrectly-handles-utf8-data.aspx
# http://tedwise.com/2010/05/25/blogging-with-toto/
module XMLRPCWorkAround
    def do_rpc(request, async=false)
        data = super

def getPages(blog)
  blog.call("wp.getPages", 0, USERID, PASSWORD, 1000)

def getPosts(blog)
  blog.call("metaWeblog.getRecentPosts", 0, USERID, PASSWORD, 1000)

def slugify(title)
  title.downcase.gsub(/[ \._]/, '-')

blog = XMLRPC::Client.new3(:host => "<your-wordpress-blog.com>", :path => "/xmlrpc.php")
  puts "Logging into blog and getting the list of posts..."
  posts = getPosts(blog)
  puts "  response received, found #{posts.size} posts"
  `mkdir articles`
  posts.each do |post|
    permaLink = post['permaLink']
        puts permaLink
    dateAndName = permaLink.gsub(/http:\/\/your-wordpress-blog\.com\//, '').split('/')
    postFilename = 'articles/' + dateAndName.join('-') + '.txt'
    postDate = dateAndName[0] + '/' + dateAndName[1] + '/' + dateAndName[2]
    escapedTitle = post['title'].gsub(/"/, '\\"')
    File.open(postFilename, "w") do |postFile|
      postFile.puts("title: \"#{escapedTitle}\"")
      postFile.puts("author: dusty candland")
      postFile.puts("date: #{postDate}")
      postFile.puts("slug: #{dateAndName[3]}")
      puts "#{post['title']} - #{postDate}"
      postFile.puts("categories: #{post['categories']}")
      postFile.puts("keywords: #{post['mt_keywords']}")
      postFile.puts post['description']
rescue XMLRPC::FaultException => e
   puts "ERROR: Code: #{e.faultCode}"
   puts "ERROR: Msg.: #{e.faultString}"

Rails No Data Model

Take advantage of ActiveModel without a database backend.

class NoDataModel
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value) if respond_to? "#{name}="

  def persisted?

Notes On Capistrano to Windows 2008


install openssh via cygwin, include vim and git.

setup git in cygwin not windows

if git for windows is installed, do not include use the git unix commands (remove from PATH if you installed that way)

Change the .bashrc file to prepend /usr/local/bin:/usr/bin to path

export PATH=/usr/local/bin:/usr/bin:$PATH

If not running interactively, don’t do anything

[[ “$–” != i ]] && return

debug path issues

cap shell

cap> echo $PATH



Savon.rb client for .Net web service.

This is a quick post to help anyone looking for info on consuming a dotNet based webservice using the savon gem for ruby. The main issue is that .net expects a namespace on the action element in the soap body. This can be done easily in the call to client#request as shown in the following gist. Hope this saves someone, maybe future me, some time!

No, I can’t build Facebook for $500!

I’ve been freelancing full time for over a year now and have found that finding and bidding for new work takes a ton of time! The perception of what something should cost has moved far for reality. I’m wondering if other freelancers have run into this problem?

I have some ideas to help alleviate some of the problems related to freelancing, if you’re interested in any way, please contact me.

AWS EC2 NodeJS, Forever, HAProxy Setup

Sign up for EC2

Create an instance, I used one from here, Alestic, paste in the ami-xxxxxx value to find the one you want.

Create an security group with at least SSH and HTTP.

Save your private key and connect like:

ssh -i your_key.pem ubuntu@ec2-instance-location.amazonaws.com

Update and install the needed packages:

sudo apt-get update
sudo apt-get install git-core g++ make curl libssl-dev

Install node, get latest url at NodeJS.org

curl -O http://nodejs.org/dist/node-v0.2.6.tar.gz
tar -xvzf node-v0.2.6.tar.gz
cd node-v0.2.6
sudo make install

Node Package Manager

Install Node Package Manager.

sudo chown -R $USER /usr/local/{share/man,bin,lib/node}
curl http://npmjs.org/install.sh | sh


This will be used to keep your node process running, forever. Restarting as needed.

keep NodeJS running with Forever

npm install forever

HA Proxy

HA Proxy

HA Proxy Logging

Quickly setup a load balanced high availability cluster

ACL Proxy Config for HAProxy


    log   local0
    log   local1 notice
    #log loghost    local0 info
    maxconn 4096
    #chroot /usr/share/haproxy
    user haproxy
    group haproxy


    log global
    mode    http
    option  httplog
    option  dontlognull
    retries 3
    option redispatch
    maxconn 2000
    contimeout  5000
    clitimeout  50000
    srvtimeout  50000

frontend http-in

    bind *:80
    acl is_domain_com hdr_end(host) -i domain.red27.net

    use_backend domain_com if is_domain_com
    default_backend hello

backend domain_com

    option httpchk HEAD /check.txt HTTP/1.0
    option httpclose
    option forwardfor

backend hello

    option httpchk HEAD /check.txt HTTP/1.0
    option httpclose
    option forwardfor

change /etc/default/haproxy

# Set ENABLED to 1 if you want the init script to start haproxy.
# Add extra flags here.
#EXTRAOPTS="-de -m 16"


sudo /etc/init.d/haproxy start

sudo forever start path-to-app.js


NOTE: don’t forget to create and EBS AMI Image so your stuff is saved.


NodeJs for server newbs


EC2 Getting Started

Alestic AMI’s

NodeJS on your own AMI

Node as a service

HA Proxy Setup

Node JS Notes

Getting Node Setup

Node JS

How To Node

Download the latest package from Node JS

tar -vxzf node-v0.2.6.tar.gz

cd node-v0.2.6

make install

Package Manager

How To Node NPM




npm install express
npm install connect
npm install jade

Get the express samples to see how things work

git clone https://github.com/visionmedia/express.git

If you follow the hello world example, you might see the following error

    throw e;
Error: session requires the "secret" option string for security
    at Object.sessionSetup (/usr/local/lib/node/.npm/connect/0.5.5/package/lib/connect/middleware/session.js:45:13)
    at Server.<anonymous> (/Users/dustycandland/projects/smsbet/app/app.js:18:19)
    at Server.configure (/usr/local/lib/node/.npm/express/1.0.3/package/lib/express/server.js:332:8)
    at Object.<anonymous> (/Users/dustycandland/projects/smsbet/app/app.js:12:5)
    at Module._compile (node.js:462:23)
    at Module._loadScriptSync (node.js:469:10)
    at Module.loadSync (node.js:338:12)
    at Object.runMain (node.js:522:24)
    at Array.<anonymous> (node.js:756:12)
    at EventEmitter._tickCallback (node.js:55:22)

FIX: add the { secret: 'some random text' } to the app.js configure section

app.use(express.session({ secret: 'some random text' }));

Hearding Code Podcast

How To Node NPM

Mongo DB OSX Install

Mongo DB with Express

Express JS

Building Web Applications

I’ve been working on a series of posts on my consulting site, Red27.net, about building web applications. These posts are really focused toward less technical folks. However, I wanted to post about it here to get any additional feedback people might have. Also, feel free to forward on to people that might find the info useful. Here’s a summery of the first few posts.

Internet Basics: Websites

This targets the basics of websites, like domain names, hosting, DNS, the basic connectivity of the web.

I know we’re starting at a really basic level, but I want to build a solid foundation for the coming information. The internet is comprised of servers, large computers, and users, you.

Internet Basics: Email

This one is short and just talks about the importance of having an email with your domain and the power of Google App for your Domain.

What makes web applications work?

This post gets more into the programming aspects of web applications, HTML, CSS, JavaScript on the client and PHP, Python, Ruby, C#, Java on the server.


Web applications are a client/server based model. The client is your web browser and the server is the web application server. There are a lot of technologies that make web applications work, but there are a few primary ones that we’ll talk about here.

There will be more coming in the next few weeks and I’ll do another post here in a month or so. Please do forward on and post any feedback.

Setting Up My Fujitsu ScanSnap S300 in Ubuntu 10.10

Mostly a post to help my future self and others trying setup a ScanSnap S300 in Ubuntu

Things should mostly be setup by default, but there is one tricky bit. You need a file from the windows drivers. I had an old hard drive w/ my previous install to copy from. You might need to set it up in a virtual machine or another windows machine to get the file.

Make a directory for the file at /usr/share/sane/epjitsu/

Copy from C:\Windows\SSDriver\S300\300_0c00.nal to /usr/share/sane/epjitsu

chmod 755 /usr/share/sane/epjitsu/300_0c00.nal

Make sure you scanner is found using


If it is you can do scanimage -L or sudo scanimage -L to see if things are working.

HTH someone


Tips from the MountainRB ruby on rails workshop

Yesterday I was at the MountainRB ruby workshop, which was basically an intro to rails class. It was a really good workshop and here are some tips I picked up.


Change the config/cucumber.yml file to display pretty output, making it easier to see the failed step.

default: -format pretty

use Background: in cucumber features for tasks that need to happen for every scenario. Use just like Scenario

Background: Make sure that we have a topic
  Given I go to the topics page
  And I follow "New Topic"
  And I fill in "Title" with "Rails Fixtures" 
  And I fill in "Description" with "Introduce how to add test data with fixtures."
  And I press "Create"

Rails templates

When you create a new rails application you can specify a template that runs after the initial generation. It can handle a lot of the initial setup. Here’s the one used used in the workshop http://gist.github.com/609269.txt


View a models attributes

From inside the rails console you can view a models attributes by calling class on an instance of the Model.

ruby-1.9.2-p0 &gt; (User.new).class


rake routes will show the routes defined for the application.

        login        /login(.:format)          {:action=>"new", :controller=>"user_sessions"}
         logout        /logout(.:format)         {:action=>"destroy", :controller=>"user_sessions"}
user_sessions GET    /user_sessions(.:format)  {:action=>"index", :controller=>"user_sessions"
user_sessions POST   /user_sessions(.:format)  {:action=>"create", :controller=>"user_sessions"}


Rails will cascade saves in a transaction by default

The resource generation option will create the model and migration, while adding a blank controller and empty views directory.

rails generate resource

heroku open shows the current heroku app in the browser.


http://bit.ly/ruby-resources – Resources from DevChix

http://railsapi.com – Rails documentation

http://boulderruby.org – Boulder user group

http://groups.google.com/group/derailed – Denver user group

http://RailsBridge.org - an inclusive and friendly Ruby on Rails community

Resize/Clone a VirtualBox hard disk with the current snapshot

After wasting a ton of time, I’m noting this here to hopefully help myself or someone else in the future.

Making the new virtual hard disk

In VirtualBox open the virtual media manager and create a new disk with the larger size. Note it’s location.

Open a command prompt to c:\program files\oracle\virtualbox and run

VBoxManage showvminfo <Machine Name>

Find the primary master line, and note the UUID.

Clone that using your UUID and the path to the new disk

VBoxManage clonehd 73880a2b-ba46-459e-b71b-816ceadecb5a c:\users\dusty.virtualbox\harddisks\CloneDisk.vdi –existing


There may be better instructions elsewhere, but this worked for me.

  1. Attach a Linux live cd to the cdrom of the machine.

  2. Change the hard disk image to your new image file.

  3. Boot

  4. Start GParted

  5. Right click the swap and select swapoff, note the size and delete.

  6. Delete the extended partition.

  7. Resize the primary partition.

  8. Add an extended partition back.

  9. Add a swap partition back.

  10. Apply the changes.

  11. Shutdown, remove the live image from the machine, restart.





WordPress Quick Install and Setup On Ubuntu

Here’s some quick notes for installing WordPress on Ubuntu 10.

Official install doc: http://codex.wordpress.org/Installing_WordPress

I choose hosting on Linode, which has been an awesome experience so far, they have really good help guides too.


You’ll need MySql, PHP, Apache installed.

apt-get install apache2 apache2-doc apache2-utils

apt-get install libapache2-mod-php5 php5 php-pear php5-xcache php5-suhosin php5-mysql

apt-get install mysql-server

Run MySql Secure Installation


Enable Rewriting

a2enmod rewrite

Enable image support for php.

sudo apt-get install php5-gd

/etc/init.d/apache2 restart

Get It

wget http://wordpress.org/latest.tar.gz > tar -xzvf latest.tar.gz


mysql -u adminusername -p

CREATE DATABASE databasename;
GRANT ALL PRIVILEGES ON databasename.* TO "wordpressusername"@"localhost"
IDENTIFIED BY "password";

Setup Apache

Create the web root directories

mkdir /var/www/red27.net/public_html -p <br />mkdir /var/www/red27.net/logs

Create an apache virtual host config

See what’s there in the sites-available

ls /etc/apache2/sites-available/

Copy an existing config

cp /etc/apache2/sites-available/candland.net /etc/apache2/sites-available/red27.net

Edit to match the correct location.

vim /etc/apache2/sites-available/red27.net

Copy the WP files to the site root

cp downloads/wordpress/* /var/www/red27.net/public_html/ -r

Change owner

chown -R www-data /var/www/red27.net/public_html/

Config WordPress

Rename the wp-config.php file

mv /var/www/red27.net/public_html/wp-config-sample.php /var/www/red27.net/public_html/wp-config.php

Edit the wp-config.php, set the correct db connection values, and replace the security lines from here

vim /var/www/red27.net/public_html/wp-config.php

Enable the site

a2ensite red27.net

Restart apache

/etc/init.d/apache2 restart

Visit the site and configure WordPress!

AutoTest Powershell Script

This script will watch a source directory for changes, just *.cs files in this case and then execute a script when a change is detected. This handles the issue of the change event being triggered twice for one change. I’m just calling my default Psake script, but you can put any build/test script call in place of it.

function watch-folder {
    param([string]$path, [string]$filter = "*.*", $command)
    get-eventsubscriber -force | unregister-event -force
    $global:lastGen = [datetime]::Now
    $expandedPath = convert-path $path
    write-host "Watching" $expandedPath\$filter
    $fileSystemWatcher = new-object System.IO.FileSystemWatcher
    $fileSystemWatcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite
    $fileSystemWatcher.Path = $expandedPath
    $fileSystemWatcher.Filter = $filter
    $fileSystemWatcher.IncludeSubdirectories = $true
    $action = {
        $timeGenerated = $event.TimeGenerated

        if ($timeGenerated - $global:lastGen -gt (new-timespan -sec 1)) {
            write-host ***************************************** -foreground Green
            write-host $eventArgs.FullPath -foreground Green
            write-host $eventArgs.ChangeType at $event.TimeGenerated -foreground Green
            write-host TESTING $event.MessageData -foreground Green
            $result = &amp; $event.MessageData | out-string -stream
            if ($LastExitCode -gt 0) {
                $result | select-object -last 70 | out-host
                write-host FAILED -foreground Red
                write-host ***************************************** -foreground Red
            else {
                write-host SUCCESS -foreground Green
                write-host ***************************************** -foreground Green

        $global:lastGen = $timeGenerated
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Created -SourceIdentifier ThisFileWatcher -Action $action -MessageData $command)
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Changed -SourceIdentifier ThisFileWatcherA -Action $action -MessageData $command)
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Deleted -SourceIdentifier ThisFileWatcherB -Action $action -MessageData $command)

watch-folder ".\src" "*.cs" {

wait-event "ctrl-c"

Thanks to this post PowerShell, events and file watcher.

ViEmu + ReSharper + VS2010 Review

I’ve been using the ViEmu plugin with ReSharper in VS2010 for a couple of weeks now. Overall, I really like combo. However there are a few things that annoy me with ViEmu. The selections modes are not the same between ViEmu and selecting text with the mouse, looks like a licensed copy might fix that. The replace function is missing the ‘c’ confirm option. The other things are mostly key bindings that ViEmu overrides, this can be changed with the _viemurc file. You need to create that file in the c:\users[username] directory, then add the bindings you’d like. I’ve added some for ReSharpers goto type command, and changed Ctrl+V back to paste.

map <C-n> gS:vsc ReSharper.ReSharper_GotoType<CR>
imap <C-n> gS:vsc ReSharper.ReSharper_GotoType<CR>
map <C-v> gS:vsc Edit.Paste<CR>

BYW, You can find the commands you’re looking for from the VS toos:options:keyboard menu.

I’m think I’m going to get a license for ViEmu, anyone else have any tips for it?

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" />


  • 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.


  • 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


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.


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>
        <set name="Matches" cascade="all-delete-orphan" lazy="true" inverse="true">
            <key column="ClassAId" />
            <one-to-many class="ClassAMatch" />

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>
        <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" />        

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.

Psake Builds and TeamCity Integration

Psake is a powerful build system, build on Powershell for a lot of functionality and familiarity. And TeamCity is a really nice continuous integration server, checkout the CodeBetter TeamCity install for a good demo. Hooking the two up was not a easy as using just Msbuild or Nant, but it’s not really too bad.

First, your Psake script needs to check the exit codes of the applications it calls. This is important to do regardless because Powershell doesn’t error out based on the exit code. The trunk version of Psake has a convenience function to execute a command and check it’s exit code is greater than 0, called exec:

You can also pass a message as the second argument.

With this checking in place, next is a bat script to use from the TeamCity command line build option.

@echo off
powershell -NoProfile -ExecutionPolicy unrestricted -Command "& {Import-Module &lsquo;.\tools\psake\psake.psm1&rsquo;; invoke-psake -t %1; if ($Error -ne &lsquo;&rsquo;) {write-host "ERROR: $error" -fore RED; exit $error.Count} }"`

This executes a Powershell prompt which imports the Psake module and then calls the provided Psake task. Finally, it checks the $Error variable and sets the exit code to the number of errors returned by the script. This will fail the TeamCity build and allows any error thrown by Powershell to break the build.

Last is to have TeamCity run the bat file with the desired target.

psake.bat Compile

One thing to note is that some things return exit code other then 0 but that are not errors. In that case you can check the Powershell variable $LastExitCode and throw errors based on that.

Thanks to the psake users group for all their help!

Brutalist Framework