Starting rails & booting a Raspberry Pi to browser

So I got a Raspberry Pi at home that I use as a dashboard, it shows me all family calendars, train status for my stop etc. To get it to work as good as possible I made the following tweaks to my installation.

To keep the screen allways on & auto start midori

$ sudo nano /etc/lightdm/lightdm.conf
# add the following lines to the [SeatDefaults] section
# don't sleep the screen
xserver-command=X -s 0 dpms
$ sudo nano /etc/xdg/lxsession/LXDE/autostart
# comment everything and add the following lines
@xset s off
@xset -dpms
@xset s noblank
@midori

from http://www.niteoweb.com/blog/raspberry-pi-boot-to-browser

Unclutter
To hide the mouse pointer when it’s not used install unclutter, sudo apt-get install unclutter

Script to autostart rails on startup

#! /bin/sh
### BEGIN INIT INFO
# Provides:          rails
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start a Rails instance
# Description:       Do the simplest thing possible in keeping with
#             upstart to spin up a single Rails instance.
### END INIT INFO

# Author: Sam Pointer & Fredrik Leijon
#
# Do NOT "set -e"

PATH=/sbin:/usr/sbin:/bin:/usr/bin:/home/pi/.rvm/bin
USER="pi"
PORT=3000
RAILS_ROOT="/home/pi/path_to_app"
COMMAND="rails s -d"
DESCRIPTION="Rails instance"
RVM_PROFILE="/home/pi/.rvm/environments/default"

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started
    su -c "source $RVM_PROFILE && cd $RAILS_ROOT && $COMMAND" $USER
}

case "$1" in
  start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESCRIPTION"
        do_start
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
esac

from http://blog.sam-pointer.com/2011/03/24/starting-a-rails-instance-automatically-on-boot-on-ubuntu-server.html, slightly modified to support rvm. Script is also available here as a gist.

Posted in Hacks | Tagged , , | Leave a comment

Nonhttp WCF services in IIS and Castle Windsor

If you have a wcf service hosted in IIS that is using a binding that isn’t based on http wiring (like net.tcp) it with your IoC container requires some additional steps. For this example i’m using Castle Windsor, first install the Castle Windsor WCF integration facility from nuget, that will pull Castle Windsor & their extensions for wcf.

If the binding used for the wcf service isn’t based on http then the Applicaton_Start method in global.asax.cs won’t be called before the service is invoked. This will cause a problem if our serivce has dependecies that need to be injected. To setup the container used to resolve dependencies we create a class in the App_Code folder under the website that has a method with the following signature: public static void AppInitialize() this method will be called before our service is invoked the first time so it is a perfect place to setup our IoC container.

A simple registration would look like this

public class AppInit
{
  private static IWindsorContainer _container;
  public static void AppInitialize()
  {
    _container = new WindsorContainer();
    _container.AddFacility();
    _container.Register(Component.For().ImplementedBy());
  }
}

The last thing to do is in the Serivce.svc markup add the castle factory attribute: Factory=”Castle.Facilities.WcfIntegration.DefaultServiceHostFactory, Castle.Facilities.WcfIntegration”.

Posted in Code | Tagged , , , | Leave a comment

dotLess, VirtualPathProvider & Embedded Resource

In some cases it can be quite useful to share static content between different web applications. A way of achieving this is to include the files in a dll as embedded resources and serve them using a custom VirutalPathProvider, for most things this will work without any additional work. However if you are using dotless to make your css more maintanable you need to do reconfigure dotless to work with files served from a VirtualPathProvider.

The 2 small changes you need to do in your web.config are, under system.webServer > handlers change the value resourceType attribue from File to Unspecified.


And in the dotless configuration section add a source attribute with the value dotless.Core.Input.VirtualFileReader.


Also make sure that there’s no static added under system.webServer > handlers for the less extension.

Posted in Code | Tagged , , | 2 Comments

Sinatra on Heroku

Steps to get a sinatra/datamapper site running on heroku.  First do git init in a directory then you need 3 files:

A Gemfile with the gems used, make sure to group them since sqlite isn’t available on heroku.

source :rubygems
gem 'sinatra'
gem 'thin'
gem 'haml'
gem 'datamapper'
gem 'dm-postgres-adapter', :group => :production
gem 'dm-sqlite-adapter', :group => :development

A Procfile, simply tells heroku which file to start with, note the -e production to put the site in production mode (in case you load different dependencies depending on environment)

web: bundle exec ruby demo.rb -p $PORT -e production

And a simple Sinatra site

require 'sinatra'
require 'haml'
require 'datamapper'

class Item
  include DataMapper::Resource

  property :text, String,:key => true
end

configure do
  DataMapper.setup(:default, ENV['DATABASE_URL'] ||
                             "sqlite3://#{Dir.pwd}/demo.db")
  DataMapper.finalize
  DataMapper.auto_migrate!

  Item.create(:text => "hi")
end

get '/' do
  @demo = Item.all

  haml :view
end

Install heroku toolbelt, then do the following:

heroku login
heroku create
heroku addons:add heroku-postgresql:dev
heroku pg:promote HEROKU_POSTGRESQL_BROWN

The last command sets the DATABASE_URL environment variable to point to the added postgres instance, the name depends on the added instance type use heroku config to get the correct one. Once all these things are done you can push the site to heroku.

git push heroku origin

For local testing start the site with this command

bundle exec ruby demo.rb

I’ve put a demo repo for the sinatra site in a github repo here

Posted in Code | Tagged , | Leave a comment

How to use IProcessHostPreloadClient

With .Net Framework 4.0 an interface called IProcessHostPreloadClient was added, it has one method called Preload. With a correctly configured application pool and Website this method will be called as soon as IIS has started, this allows you to run code in your website before the first visitor has arrived causing application_start to kick in. This can be used to prewarm your website cache, to magic stuff during site start up (register with a loadbalancer maybe?) or well anything else that can’t wait until someone visits the website.

Assuming you have a application pool and website in your IIS you first need to add a class implementing the IProcessHostPreloadClient interface that does some magic. Once that is done you need to edit the applicationHost.config (full path C:\Windows\System32\inetsrv\config\applicationHost.config)

First find the applicationPool under the applicationPools node and add the following attributes to it:

  • autoStart=”true”
  • startMode=”AlwaysRunning”

Then under the system.applicationHost node add a registration for your PreloadClient

<serviceAutoStartProviders>

  <add name="RegisterApplicationHandler" type=X.RegisterApplicationHandler, X" />

</serviceAutoStartProviders>

The name can be anything you want, the type needs to be the full name of the class implementing the IProcessHostPreloadClient (that namespace and class name)  comma the name of the assembly the class is in. Could be something like: WebApplication1.PreloadClient, WebApplication1

When the provider is added you need add it to the website, this is done by adding the these attributes:

  • application tag: serviceAutoStartEnabled=”true”
  • serviceAutoStartProvider=”RegisterApplicationHandler”

The value of serviceAutoStartProvider should be the same as the name of the provider you added. When everything is added save the file, this will cause IIS to reset since the applicationHost.config was altered. If everything is setup correctly your IIS should automatically spawn a w3wp.exe process as soon as it’s started.

Some things to think about

  • It’s hard to debug this code since it’s run before your debugger has a chance to attach to it.
  • If the configuration is incorrect your website and/or IIS won’t start, check the event log for info
  • If Preload throws an exception then your site won’t start, use pokemon exception handling if you must ;)
  • If you setup an IoC container in Application_start then that won’t be available in Preload, so you either need to load it there too or find ways to do your work without it.

Posted in Code | Tagged | Leave a comment