Using IronPython to extend your .NET applications

One of the interesting new things on the .NET platform is the recent addition of Python and Ruby to the CLR. Both versions for .NET are called IronPython and IronRuby respectively, and they provide some new and good things to the platform.

Python and Ruby lovers will see now that they can use all the library and features of the .NET platform programming in their favorite scripting language. Since both of them are object oriented, you can now write fully fledged apps using either of them.

However, there’s another interesting application for IronPython and IronRuby: adding scripting support for your existing .NET applications. This can be a very useful and powerful way to extend your applications and give the user freedom to program their own mini programs, scripts or whatever in your applications. It could be good for defining rules, assigning and calculating values, etc.

I’ll provide a simple class you can use to add scripting to your application. I’ll use IronPython in this example.

First of all, you have to download IronPython and install it, and add the references to the assemblies on your project references.

The usual way to proceed in those cases is to provide the user of some local variables you give them access to, execute the script, and then recover the values of those or new variables. To do so, You can use a class similar to this one:

using System;
using System.Collections.Generic;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;
 
namespace Scripting
{
	internal class PythonEngine
	{
        ScriptEngine m_engine;
        ExceptionOperations m_exceptionOperations;
        SortedDictionary<string, object> m_inputVariables;
        string m_script;
 
        internal PythonEngine()
        {
            m_engine = Python.CreateEngine();
            m_exceptionOperations = m_engine.GetService<ExceptionOperations>();
        }
 
        internal SortedDictionary<string, object> ScriptVariables
        {
            set { m_inputVariables = value; }
        }
 
        internal string Script
        {
            set { m_script = value; }
        }
 
        internal ExceptionOperations ExceptionOperations
        {
            get { return m_exceptionOperations; }
        }
 
        internal SortedDictionary<string, object> Execute()
        {
            //Create structures
            SourceCodeKind sc = SourceCodeKind.Statements;
            ScriptSource source = m_engine.CreateScriptSourceFromString(m_script, sc);
            ScriptScope scope = m_engine.CreateScope();
            //Fill input variables
            foreach (KeyValuePair<string, object> variable in m_inputVariables)
            {
                scope.SetVariable(variable.Key, variable.Value);
            }
            SortedDictionary<string, object> outputVariables = new SortedDictionary<string, object>();
            //Execute the script
            try
            {
                source.Execute(scope);
                //Recover variables
                foreach (string variable in scope.GetVariableNames())
                {
                    outputVariables.Add(variable, scope.GetVariable(variable));
                }
            }
            catch (Exception e)
            {
                string error = m_exceptionOperations.FormatException(e);
                //Do something with the pretty printed error
                throw;
            }
            return outputVariables;
        }
	}
}

Usage of this class is pretty simple. You have to provide the object the script you want to execute and the input variables the script will have available as local variables. Once this is done, you have to call the Execute method, and this method will either return the output variables of the execution of the resulting script, or throw an exception.

  • Share/Bookmark

Killing all rails logs with one Ctrl+C?

Well, this is my first post after holidays and it won’t be very long.

Imagine you are developing a rails application. Usually you have:

  • a terminal with the server to see what petitions are received.
  • a terminal with a tail of development.log to see what happens with the database.
  • a terminal with a tail of test.log if you are testing something.

This are a lot of windows… And the other day one friends was very happy and after asking for a while I discovered that the reason was the simple line showed above… With only one Ctrl+C you can kill all this processes :-)

script/server & tail -f log/development.log & tail -f log/test.log & tail -f ; jobs -p | awk '{print "kill -2 " $0}' | sh
  • Share/Bookmark

Ruby Quiz

Maybe one of the best ways to learn a new programming language is playing with it. Nowadays if you don’t code in Ruby you aren’t cool. I have to recognize that programming in Ruby is funnier than in other language and for the moment I don’t have anything bad to say about it.

Well, I want to introduce Ruby Quiz. It is a collection of minigames prepared to learn Ruby (or to improve your skills). Every week they publish one game, and if you are brave you can send your solution to them and it will be public. I think it’s one of the best ways to learn because you can compare solutions and find were you are weak in Ruby and redo your solution doing it smarter.

  • Share/Bookmark

Customizing IRB

While developing a Ruby application or while learning ruby, one of the things you must use is IRB (interactive ruby). As in its man page is said “irb is a tool to execute interactively ruby expressions read from stdin.”. In this tool you can type and execute directly ruby code. It’s very useful but like most other programs like ViM (Vi IMproved) the real power is its customization.

Here I post my .irbrc and to make things clear there are some explanations on each line.

# autocompletion of methods when pressing TAB
require 'irb/completion'
# Wirble is a plugin to colorize your irb, it's installed from a gem (gem install -y wirble)
require 'rubygems'
require 'wirble'
 
# Make use of readline library
ARGV.concat [ "--readline" ]
 
# autoindent of code while typing it
IRB.conf[:AUTO_INDENT]=true
 
# wirble initializations
Wirble.init
Wirble.colorize

As I said before, IRB is very powerful and a proof is that in Ruby Lang they encourage you to try ruby in your browser with an embedded IRB.

Also in rails the console for debugging your application is an irb instance preloaded with all rails configuration. In RailsCasts there is a screencast that shows you some tricks about it.

  • Share/Bookmark