codethinked (kōdthĭngked) adj. To be consumed by or obsessed with code.

Say Goodbye to NAnt and MSBuild for .NET Builds With IronRuby

Just the other day I put a tweet out on Twitter where I exclaimed that I am not a fan of XML based build systems. Yes, I understand their purpose, and yes they were great in their time, and yes I still use them on almost a daily basis, but I really think that we have better ways that we could be doing this. The most common response from my tweet was “but was is the alternative?” And I thought, yeah, one of the most important things that I have learned in my lifetime is that you never complain about something unless you have a solution. And so I am here today to propose to you a solution…

The Problem With XML Based Build Systems

Before we get into this entire discussion, let me ask you a question… what is it that developers do better than anything else? Got your answer? Well, I know what mine is, and that answer is “write code”. And if that is the case, then why are we so intent on shoving things into giant xml files? Why can’t we write code? The usual argument is that XML based applications allow us to more easily make changes without recompiling, they allow for more flexibility, and they make it easier to write tooling since they are based on a format that everyone can parse. But personally, I don’t think that they offer much value, and instead are the project of the XML hysteria that swept through the programming world a few years ago. In fact, those of us who have been working with these XML based build tools for years probably forget just how ridiculous and obtuse they looked when we first saw them.

So while many people are quick to extol the virtues of XML, they often people forget to point out all of the things we lose when we start writing code in XML. For example, how about all of the tools that our industry has spent so many years crafting and refining. We lose our editors, debuggers, libraries, and all of the other tools that we use in order to get a few minor advantages that XML provides us. Those XML files limit us to the degree where we often find ourselves falling back to writing custom tasks in order to get around those limitations. Custom tasks which are not written in XML, but instead have to be written in code, since after all, the XML in these files is really just a hideously complex configuration system for the code which is actually running underneath.

Continue reading the rest of this post...

IronRuby Unleashed Is Out Now

As many of you may or may not know, I was the technical editor on Shay Friedman's book "IronRuby Unleashed". I am a huge fan of the Ruby language, and as you probably have guessed, I am also a big fan of the CLR. So when I found out that they were bringing the Ruby language over to the CLR, I was absolutely ecstatic. I spent quite a bit of time with IronRuby, leveraging it for little utilities, exploring a bit, and I even wrote up a fairly popular blog post series about using IronRuby. I was approached about the potential of writing the IronRuby Unleashed book for Sams, but I felt under qualified and way too busy to try to write an entire book on IronRuby. Now that I have the book in my hands, I can firmly say that I was definitely under qualified to write a book on IronRuby. I was amazed at Shay's depth of knowledge on a topic which is so young, as well as his thoroughness in explaining the topic. Shay was more than qualified to write this book, and you can tell that he poured his heart and soul into it.

Synopsis

While I may be a bit biased, I have to say that the book is great. :-) Shay definitely knows his IronRuby and shows it. He manages to write a book which delves into some deep technical content, but starts off high level enough that even someone who has never used Ruby could pick up the book and learn it. The book is very well organized, and starts off with a quick introduction to Ruby, the .Net Framework, and the DLR (Dynamic Language Runtime). He then immediately goes into getting IronRuby up and running on your system, along with a reference to how to use the IronRuby executable, and even how to get IronRuby to run inside some 3rd party IDEs.

Continue reading the rest of this post...

Bringing The Heat With Dynamic

For a little while now I have been feeling a bit restless when it comes to programming on the .net platform. I love C#, it is my current language of choice, but I get so jealous when I talk to the Java guys at work and see all of the freaking awesome tools that they have for free on their platform. Since I use the NUnit, NCover, NHibernate, NAnt stack when doing most .NET development, sometimes I feel like we are just a bunch of copycats. I want something neat and unique! (And to be fair, there actually is quite a lot of innovation going on in the .NET space!)

Well, tonight I went to see my good friend Kevin Hazzard talk about DLR/C# interop performance in VS2010 (the talk was great, go check it out) and he gave me a great “smack to the face” reminder of one huge thing that we have coming in C# 4/.NET 4.0 that is quite unique. And that is the dynamic keyword. In order to full appreciate its value, you have to see it used in terms of its interop with dynamic languages.

Continue reading the rest of this post...

Using IronRuby To Implement Dynamic Business Rules

The is part three of my three part series on Domain Validation. In the previous entry in this series I showed you how to store rules in the database and then have those rules dynamically compiled so that we can run them against our domain entities (business objects). We also saw that there was some issues with this approach, and so we came to the conclusion that what we really needed was a scripting language which would interact with C# so that we could use to build our rules. Well, thanks to the IronRuby team we have just that.

So, the first thing that we need to do is get IronRuby setup in our project. We can do that by simply adding references to IronRuby.dll, IronRuby.Libraries.dll, Microsoft.Scripting.dll, and Microsoft.Scripting.Core.dll. These will all be found in your \IronRuby\trunk\build directory after you grab and build the latest version of IronRuby. If you don't know how to do this, I wrote a post a while back on how to get IronRuby up and running.

So, now that you have built and referenced IronRuby, lets look at how we can get this running. I am going to first create a property to wrap the creation of the Microsoft.Scripting.ScriptEngine. This is the generic script engine that Microsoft is now using for the front-end of its two scripting languages (IronPython and IronRuby). This property looks like this:

private ScriptEngine scriptEngine;
public ScriptEngine ScriptEngine { 
    get
    {
        if (scriptEngine == null)
        {
            var setup = new ScriptRuntimeSetup();
            setup.LanguageSetups.Add(
                new LanguageSetup(
                    "IronRuby.Runtime.RubyContext, IronRuby",
                    "IronRuby 1.0",
                    new[] { "IronRuby", "Ruby", "rb" },
                    new[] { ".rb" }));
            var runtime = ScriptRuntime.CreateRemote(AppDomain.CurrentDomain, setup);
            scriptEngine = runtime.GetEngine("Ruby");        
        }
        return scriptEngine;
    }             
}

This is just a bit of boilerplate code for setting up IronRuby to run, and in fact, it can be done declaratively. Most of the info in this declaration we won't even need, since we won't be referencing any source files or anything, but we might as well do it correctly in case anyone decides to start copying and pasting. :-)

Now, just like before we are going to pull our list or RuleData classes out of the database. Our RuleData class just stores the info needed to build and report errors on our rules, and it looks like this:

internal class RuleData
{
    private readonly string[] property;
    private readonly string errorMessage;
    private readonly string rule;

    public RuleData(string rule, string errorMessage, params string[] property)
    {
        this.property = property;
        this.errorMessage = errorMessage;
        this.rule = rule;
    }

    public string Rule
    {
        get { return rule; }
    }

    public string ErrorMessage
    {
        get { return errorMessage; }
    }

    public IEnumerable<string> Properties
    {
        get { return property; }
    }
}

If you read the previous entry in this series you will have seen how much effort it took to read in and compile our rules in C# using the CodeDOM. Well, lets take a look at what it is going to take to get this working in Ruby. So, we first created our rules like this:

new RuleData("e.SomeValue > 1", "SomeValue Must Be Greater Than 1", "SomeValue");
new RuleData("e.SomeOtherValue < 1", "SomeOtherValue Must Be Less Than 1", "SomeOtherValue");

The first string is our rule, where "e" is the generic identifier for our entity. Our entity has two properties "SomeValue" and "SomeOtherValue" and the first one must be greater than 1 while the second one must be less than 1. We don't even need to change the syntax for our Ruby code, since the boolean operators are the same.

One thing to note is that here we are manually instantiating these rules, but since they are just three strings, you can store them in the database with the full type name as your key. Something like this would do:

Type type = typeof(T);
string rulesKey = type.FullName + ruleType;

So, now all we have left to do is turn our rules into something that we can execute from C# code. Well, hate to disappoint, but here is the code that does this:

foreach (RuleData rule in ruleData)
{
    string source = String.Format("Proc.new {{ |e| {0} }}", rule.Rule);
    ScriptSource scriptSource = ScriptEngine.CreateScriptSourceFromString(source);                
    var proc = (Proc)scriptSource.Execute();
    Predicate<T> predicate = p => (bool)proc.Call(p);
    result.Add(new StaticRule<T>(predicate, rule.ErrorMessage, rule.Properties.ToArray()));
}

Almost too easy, huh? In the first line we are inserting our rule into a bit of wrapper code that creates a Proc, which is the equivalent of a delegate in C#. So, our rule would look like this: "Proc.new { |e| e.SomeValue > 1 }". Notice we are using double curly braces since we have the code inside of a call to "String.Format". Next we create our script source from this code, and then we execute it, which returns our IronRuby.BuiltIns.Proc class. Then we create a predicate delegate to wrap this Proc and pass the parameter from the Predicate delegate into the "Call" method on the proc object. The final line just uses this Predicate to create a new "StaticRule" class and insert it into our result list.

We don't have any of the problems that we had with the dynamically compiled C# code, but since we are executing this code every time through we are taking a bit of a performance hit. We can speed this up a bit by calling "scriptSource.Compile()" instead of "Execute()" which would allow us to cache our compiled rules. The "Compile" method just returns a CompiledCode class which has its own "Execute()" method that we can use.

In this post we have seen how you can leverage IronRuby in order to save, load, and execute dynamic rules against business entities. We have not implemented anything close to a real rule engine here, but for many applications being able to save and load business rules on entities may be enough. The rules that you can construct in this manner can actually be quite complex. I hope that you find this useful!

RCC 2008.2 IronRuby Talk

I just finished giving my talk on IronRuby at the Richmond Code Camp 2008.2. It was titled "Microsoft and Ruby Sittin' in a Tree". I tried to cover a huge number of features in Ruby very quickly and then show off a few Ruby snippets that demonstrate many of its cool features. As usual you probably won't get a huge amount out of the slides without seeing the accompanying presentation, but you can still go through it if you would like. I have included the source for my demos in the zip as well, and that is probably the more interesting part. It has some basic language primer, which I didn't get to in the presentation, and it also has some more advanced "showy" demos.

I demonstrate 5 main things in the code samples:

1) A proxy class that allows you to pass an instance of a class to its constructor and then intercept method calls and do something. Just wanted to show how easy it is in Ruby with method_missing.

2) Second it shows off a recorder which lets you call a bunch of methods on a recorder object and then play those calls back against a target object. I wanted to implement this and search online and found an example of Jay Field's blog. I studied his implementation for mine, so I have to give props.

3) Third I showed off a bit of Meta-Programming which uses class_eval and define_method to create new methods on a class.

4) Fourth I showed off a bit of .net Interop which just displays a form with a field and a button. It shows assigning a block to use as an event handler.

5) Fifth I showed how to consume a WSDL file in Ruby and then call the web service. Then I use REXML to parse the resulting XML and display it in the console. This the only of the five demonstrations that won't run yet under IronRuby.

If you would like to see the presentation or accompanying source files, you can download it here.