Hello rake-world

by DotNetNerd 27. May 2010 16:31

Rake is a quite popular build framework, that has its strengths in the fact that it is code (no more xml), and it is very simple to get started with. Actually setting it up is a 3 step process.

  1. Make sure the path environment variable is set to point at your ironruby/bin folder.
  2. Run “igem install rake” from the commandline
  3. Write a Rakefile.rb like the following and place it at the root of your site

require 'rake'

task :default => [:say_hi]

desc "Does quite a bit of greeting"
task :say_hi_to_me do
    puts "Hello me. Now that was easy."
end

task :say_hi_to_world do
    puts "Hi world!"
end

task :say_hi => [:say_hi_to_me,:say_hi_to_world] do
    puts "I’m, all hellowed out"
end

This really all it takes, so now you are ready to run your tasks from the commandline by writing: “rake” or “rake say_hi_to_me”.

Now for this to get really interesting you will need albacore which makes it easy to do all kinds of basic tasks.

This is installed with the command “igem install albacore”, and makes it possible to do builds and run unittests like this:

require 'rake'
require 'albacore'

task :default => [:full]

task :full => [:clean,:build_release,:run_tests]

task :clean do
    FileUtils.rm_rf 'build_output'
end

msbuild :build_release do |msbuild|
  msbuild.properties :configuration => :AutomatedRelease
  msbuild.targets :Build
  msbuild.solution = "TestApp/TestApp.sln"
end

nunit :run_tests do |nunit|
    nunit.path_to_command = "tools/nunit/nunit-console.exe"
    nunit.assemblies "build_output/TestAppTests.dll"
end

rakemonkey

Tags: ,

Silverlight and IronRuby – a match made in heaven

by DotNetNerd 25. April 2010 10:31

A couple of months ago I was starting to read about IronRuby, and while thinking about what my first little pet project should be I saw a tweet from a guy who was enjoying the combination with Silverlight. I gave the idea some thought and liked the idea of using a dynamic language to make a rich internet application. So after reading IronRuby UnleashedI started out doing a version 2 of my dotnetnerd.dk site – which is just a little toy selfpromotion site.

Getting started was pretty straight forward because with IronRuby there is a small webserver called Chiron, which can make a project template. All you have to do is open a cmd, and go to the library where IronRuby is installed and type script\sl.bat ruby <projectpath>

Armed with my starter template I began playing around and got my layout in place. I also tried using some 3rd party components by referencing some dll’s and all that basic stuff. Most of it went smoothly, but I did run into an assembly (Flickr.net) that threw an exception when used with Silverlight/IronRuby. Using it from a console project in IronRuby worked fine, so I quickly decided to just go directly against the flickr api using the .NET WebClient class. Running the site from chiron was as easy as calling script\chr.bat /d:<projectpath> /b:index.html

When I had the first couple of pages ready and had written a picturegallery showing the last 5 pictures I have uploaded to flickr I wanted to get the site deployed, so I would no longer depend on chiron. From my book and by looking at blogs it seemed to be smooth sailing, because chiron has a function that makes a .xap file which is all you need. To my surprise when I referenced the .xap file from the html file in my my project it looked like it loaded, but then just stopped at 100% without showing my actual site. I felt pretty stuck, because I had no exception or anything to go on, and my site ran fine when I was using chiron.

I then wrote an email to “Iron” Shay Friendman, who wrote the book that I was using as my inspiration. I thought it was worth a shot, and that I could not be the only one with that problem. Later that day he wrote back, and (as the nice guy he is) told me that he did not know the solution off the top of his head but he would look at it as soon as he had a couple of available hours. A few days later he had found a solution, and it turnes out a few things need to be done differently when running it outside of chiron. So this is basically what I want to share with this post :)

What you need to do is:

1) If your .rb files contain references like “app.xaml” it should be changed to app\app.xaml – in other words the references should be from the root of the solution and not from the app folder where the file is located.

2) Make the .xap file using the command script\chr /d:<projectpath> /z:<projectpath>\app.xap

3) In the index.html file where the .xap file is referenced find the like starting with <param name="initParams".
Change its value attribute to "start=app\app.rb,reportErrors=errorLocation".

And easy as 1-2-3, your site should work when running the index.html file.

Shortly put it really has been a fun project, and I really like the IronRuby and Silverlight combination, so it is definately not my last project where I will combine the two.

ironrubylogo

IronPython – add scripting to you application

by DotNetNerd 5. December 2009 16:43

Last time I looked at how IronPython is integrated with .NET which makes it possible to use all of the good stuff that we know and love from .NET. The obvious next thing to look at is doing the inverse and see how it is possible to run IronPython code from within a .NET app written in this case in C#.

The main scenario for this is to allow advanced users to write their own scripts that can extend the behavior of the application, or allow them to express complex logic. An example that comes to mind for me is a system I am working on at work, where we are doing payroll processing for any kind of company. Here a viable option could be to allow the rules for the processing to be expressed with scripts – since the tax laws have a tendency to change frequently it would be a valuable extensibility point.

The most basic way to run IronPython code from C# is to do like this:

var engine = new PythonEngine();
engine.ExecuteToConsole(@"print ""Sweet dude!""");

As you can see it is pretty simple to get code to run in the first place. It is not of much use however if it is not possible to pass in variables to the context in which the IronPython code is run. This is accomplished by passing in a module and a dictionary of variables like so:

engine.ExecuteToConsole(@"print ""Cool: "" + str(2+val)",
    engine.DefaultModule, new Dictionary<string, object>() { { "val", 6 } });

Again, this is pretty straight forward. Besides passing variables it would also be nice to be able to define global variables that can be used and accessed again after the script is run. This example shows how to do just that:

engine.DefaultModule.Globals["val"] = 6;
engine.ExecuteToConsole(@"val = ""Cool: "" + str(2+val+2)",    engine.DefaultModule, null);
string modifiedValue = (string)engine.DefaultModule.Globals["val"];

One thing to note here is that i set the global variable to a value of 6 which is an integer but I end up getting a string back. This is because IronPython is a dynamic language which allows the type to be changed which is done in the script because it is added with a string.

Now my guess is you might be thinking that there must be other ways to run scripts than to execute them to a console. Well of course there is. The PythonEngine has several overloads and alternate methods that can be used to run scripts. I wont go over them all but I’ll finish up with a sample that I think will probably be one of the ways I will end up using most often. In this case I simply evaluate a script that returns a value. This way a script could be used to define some logic and simply return the kind of result I need:

string myResult = engine.EvaluateAs<string>(@"str(2+2)");

Mainly there are two groups of methods to run IronPython code – you can either execute or evaluate the code, with the difference being that evaluating it returnes a value. There are also methods to execute code from a file, which might be convenient.

280px-python_logo_2

Tags: ,

IronPython – integrating with .NET

by DotNetNerd 25. October 2009 18:04

One of the great things about IronPython compared to other Python implementations is that is running on the .NET platform and was written in C#. This lets the developer use all the stuff he already knows from using .NET and he will have the possibility of writing components in C# that can extend or be used from IronPython. I regular Python writing extensions would be done I C which is enough to scare a big part of the developer community away. On top of that the IronPython syntax and type system is pretty close to C#, so if you are already programming in C# you will have a fairly easy time getting started with IronPython.

Doing integration of an existing language into a framework is always going to be a challenge. Some concepts in Python map fairly well to the existing .NET languages, while others require that you learn how to get about doing things from IronPython as they will require a little deeper understanding. A good deal of these challanges are covered in “The dark corners of IronPython”. The most basic thing you need to know though, is how to access classes and navigate namespaces from IronPython.

Namespaces are a concept that maps pretty well between C#/VB and IronPython, because Python has a similar concept which is called modules. In Python a module is a file which can contain any number of classes and which can be grouped into packages, which are actually just folders on the file system.

To gain access to using a class it is imported by writing an import statement - in roughly the same way as namespaces are used to group classes in C# and VB. This means that doing a import in IronPython that allows us to access a .NET class is very straight forward. (Iron)Python does have differences though. One difference is that a package contains a file named __init__.py, where you can write code that is run when the package is imported. Secondly and probably more importantly in Python the import allows you specify exactly which classes to import instead of the whole namespace/module.

from System.IO import Directory, File

This line of code will allow us to use the Directory and File class of the System.IO namespace. Writing a * instead of the filenames will mean that all classes in the namespace are imported. This is regarded as somewhat of a bad practice in the Python community though. This is basically what you need to know to start accessing .NET classes from IronPython like this:

from System.IO import File, Directory, FileInfo 
from System.Text.RegularExpressions import Regex

files = Directory.GetFiles("D:\MyFiles")
for i in range(0,files.Length):
    file = files[i]
    fileInfo = FileInfo(file)
    reg = Regex("^\d\d[\s-]+")
    res = reg.Replace(fileInfo.Name, "")
    print res

Tags: ,

IronPython - high order functions as decorators for AOP

by DotNetNerd 20. September 2009 13:58

One of my favorite features from when I was playing around with F# was high order functions. A high order function is quite simply a function that takes a function as an argument and returnes a function. A basic sample just to get the point accross could be:

def Outer():
    innerText = "Hey dude! "
    def Inner(text):
        print innerText + text
    return Inner

myfunc = Outer()
myfunc("My function was called successfully")

This technique can be quite useful when composing functions, but also to wrap code and handle cross cutting concerns (e.g. like logging) through Aspect Oriented Programming. IronPython takes this concept a bit farther through what is called decorators. A decorator is to some extent similar to an attribute, and can be used to do AOP. Using decorators is as simple as defining a high order function and decorating the method that should be wrapped with @myHighOrderFunction like this:

def logging(function):
    def inner():
        print "Do pre call logging"
        function()
        print "Do post call logging"       
    return inner

@logging
def myfunc():
    print "Could do what interesting stuff you like"   
   
myfunc()

As you can see from the code it makes for a very straight foreward and elegant way og doing AOP.

UPDATE: I stumbled across this video with DevHawk where he actually shows a similar example during his talks here in DK.

Tags: ,

IronPython – multiple inheritance and monkey patching

by DotNetNerd 16. July 2009 18:16

Multiple inheritance 

Besides the basic OOP stuff that I covered in my last post there are some things that you can do in IronPython which is not possible in languages like C# and java.

One nice thing that I have heard people moan about not having in other languages is multiple inheritance. Working with it is very straight forward in Python as the following sample illustrates:

class MyFirstClass:   
    def MethodOne(self, arg):
        print "1 " + arg

class MySecondClass:   
    def MethodOne(self, arg):
        print "1 Overwritten " + arg         
    def MethodTwo(self, arg):
        print "2 " + arg

class MyThirdClass(MySecondClass, MyFirstClass):
    def MethodThree(self, arg):
        print "3 " + arg

class MyFourthClass(MyFirstClass, MySecondClass):
    def MethodFour(self, arg):
        print "4 " + arg

Multiple inheritance is obtained simply by listing the classes that are to be inherited, where the order dictates the precedence of the members. This means that if the classes inherited have methods with the same signature, the first class takes precedence.

The following code can be used to test the above classes, and it also illustrates that a variable name can be reused for different types, which is a very basic feature of dynamic languages. Basic as it may be it is also one of the things that can make code really messy!

t = MyThirdClass()
t.MethodOne("MethodOne")
t.MethodTwo("MethodTwo")
t.MethodThree("MethodThree")

t = MyFourthClass()
t.MethodOne("MethodOne")
t.MethodFour("MethodThree")

Monkey patching

I wrote in my last post that it is possible to modify objects and add methods to the instance itself. Besides that it is also possible to add methods to the class in the same way. Adding or overriding methods in this way is sometimes referred to as monkey patching. As with multiple inheritance it can get really messy, but used wisely it can also make code really simple and elegang. An obvious place to use this is for mocking when writing unittests. A simple way to illustrate the technique is to first create a class and two methods:

class MyFirstClass:   
    def MethodOne(self, arg):
        print "1 " + arg
def MethodTwo():
    return "Monkey patched to instance 2"
def MethodThree(self):
    return "Monkey patched to class 3"

Now the methods can be monkey patched onto the instance and class as the following code illustrates.

t = MyFirstClass()
t.MethodTwo = MethodTwo
MyFirstClass.MethodThree = MethodThree

t.MethodOne("MethodOne")
print t.MethodTwo()
print t.MethodThree()

As the observant reader will notice it is required that MethodThree which is added to the class takes the self argument, where MethodTwo which is added to the instance does not.

monkey-thinking

Tags: ,

IronPython – OOP basics

by DotNetNerd 1. July 2009 14:12

A while ago I heard a podcast where it was discussed that some believe that languages like C#/java etc are actually not object oriented but that they are really oriented. This provoked my thinking quite a bit, since OOP was the corner stone during my education, and we wrote all code in Java.

As the discussion went on I ended up seeing their point – even though I (of course) would never admit that C# is not object oriented :) The key point is that everything in C# is based around classes because the language is statically typed around classes. In a language like IronPython it is actually possible to manipulate each object, add methods, fields etc.

Manipulating objects in this way is also known as monkey patching, and it is something I will look into in a later blogpost. Today I will start off with a basic example of how to write a class in IronPython.

The following piece of code shows a basic class with a private field, constructor, property and a public method:

from System import Console

class Customer(object):   
    "This class contains info about a customer"
    #Private field
    _saysText = " says: "     
    #Constructor
    def __init__(self, name = "Christian"):
        self._name = name  
    #Property
    def _getName(self):
        print "From within property getter"
        return self._name
    def _setName(self, value):
        print "From within property setter " + value
        self._name = value
    def _delName(self):
        print "From within property delete"
    Name = property(_getName, _setName, _delName) 
    #Indexer
    def __getitem__(self, index):
        return self.Name[index]
    #Private method   
    def _Write(self, text):
        print self.Name + self._saysText + text
    #Public method
    def Say(self, text):
        self._Write(text)

There are a few things that are worth noticing here. First of all you see that import statements explicitly state which classes are imported. A * can be used to import all classes, but this is seen as bad practice in IronPython.

Private is not a keyword in IronPython, but when a member is prefixed with an underscore (_) it is private by convention. The constructor and indexer is also named in a special way, which is what is know as magic methods. Magic methods are used instead of implementing interfaces like IComparable and for constructors, indexers and the like. Magic methods are easy to spot as they are pre- and postfixes with a double underscore. The constructor is defined with a default value for the name parameter, in the same way as you can use default in params in VB and in C# from vNext.

All methods start by taking a parameter called self. As you can probably guess, this is so it can access members located on itself – so it is used like “this” in C#, but here it is required to use it when accessing members from the object itself.

The biggest thing to notice is the way the property is constructed. Properties are quite special in IronPython compared to C#. Because the language is dynamic properties do not have to be declared up front, and this means that properties are only created when you want to do something when the property is actually called. Because this is the case there is also a delete part, which is called when the property is removed from the object.

Note that the class inherits object – this is required to use properties! This is no big issue though, because IronPython supports multiple inheritance.

When we have this in place we can use the class like you see here:

print Customer.__doc__
help(Customer)

obj = Customer(name = "Jens")
obj.Say("I'm the king of the world!")
obj.Name = "Hans"
obj.Say("I'm the king of the world!")
print obj[0] + obj[1] + obj[2]
del obj.Name
Console.ReadLine()

Functions and statements do not have to be contained within a class, so this can be written directly beneath the code above where we declared the class.

The first two likes show how you can access information about the class. The first line writes out the string that I put directly under the constructor – which is how documentation can be added and introspected directly in IronPython. The second like prints an overview of which members exist on the class, which is something you will use a lot to examine new classes as you work with them.

The rest should be pretty straight forward. A few things to note are that named parameters are used in the constructor, and that you could actually set and print any property on the object – name is only used here to illustrate that the code in the get/set/delete functions is run when the property is used.

 

Tags: ,

IronPython – kom godt igang med dynamiske sprog til .NET

by DotNetNerd 15. June 2009 10:30

Jeg besluttede mig for nylig for at kigge nærmere på IronPython, da det virker til at være et interessant sprog, som jeg kan lære noget af. Jeg anskaffede mig derfor bogen IronPython in Action, som jeg har et godt indtryk af indtil videre.

Hvorfor IronPython?

Personligt opstod min interesse for IronPython igennem at jeg havde set en del videoer og læst blogposts om DLR, som Microsoft har bygget for at .NET platformen kan understøtte dynamiske sprog. Et hvert paradigme har naturligvis sine forcer, så en helt oplagt pointe er at man kan vinde noget ved at lære et sprog der hovedsageligt har fokus inden for hvert paradigme.

Der er mere konkret to emner hvor jeg synes dynamiske sprog virker interessante, og det er i forhold til testframeworks og som scriptsprog der kan embeddes og bruges som DSL. Begge dele bliver dækket i IronPython in Action – om end jeg ikke er nået helt så langt endnu.

Noget der meget vel kan vise sig at være en stor bonus er desuden at Python sproget findes i en række forskellige implementationer (f.eks. CPython, PyPy, Jython og tinypy), og kan derved bruges på flere forskellige platforme, samtidig med at eksisterende frameworks vil kunne anvendes fra .NET applikationer.

Derudover blev jeg gjort opmærksom på af Søren Skovsbøll at Boo syntaksmæssigt ligner Pyton en hel del, og det kan derfor være et godt trinbræt til også at prøve det af.

Installation

For at komme igang skal man umiddelbart bruge to links – henholdsvis til selve IronPython installationen og til at få understøttelse i Visual Studio med IronPythonStudio. Installationen er rimeligt selvforklarende, så man er hurtigt igang. Derudover er her en god OOP guide, hvor man kan lære syntaksen og basal objekt orienteret programmering I IronPython.

python

Tags: ,

Dynamic Language Runtime

by DotNetNerd 3. November 2007 23:36

DLR - Dynamic Language Runtime.

Jeg fik for et stykke tid siden øje på en blogpost der omhandlede endnu et tiltag Microsoft arbejder på til .NET frameworket - nemlig en Dynamic Language Runtime. Umiddelbart tænkte jeg "fint nok men hvad skal jeg bruge det til". Det spørgsmål fik jeg så besvaret nu her da jeg faldt over en video fra MIX07 omkring dette emne. Jeg vender tilbage til videoen senere, da den indeholdt et temmeligt fedt eksempel som jeg vil gengive.

Kort fortalt er styrken ved dynamiske sprog at de "bare er tekst" ligesom en aspx- eller xaml-fil. Derved giver de nogle muligheder for især webudviklere ved egentlig at vende en smule tilbage til webudviklingens barndom. Idet sprogene er fortolkede, og altså "bare tekst" der ikke skal kompileres for at kunne afvikles, kan man arbejde uden konstant at skulle igennem en code-compile-review cyklus.

Dette kan især være rart hvis man skal udgive rettelser til en webapplikation, men også under selve udviklingen da man kan sidde med browseren fremme på den ene skærm imens man retter i koden på den anden og ser ændringerne slå igennem med det samme.

Hvilke sprog kan man så kode i?

Til at at starte med arbejder Microsoft på at udvikle implementationer baseret på sprogene:

  • IronRuby
  • IronPython
  • JavaScript
  • Dynamic VB

Ligesom med den almindelige CLR er det meningen at det skal være muligt at udvide med flere sprog hen ad vejen. De 4 sprog der er med til at starte med er valgt ud fra at de for det første er meget udbredte, og så for JavaScripts vedkomne fordi det giver mulighed for at man meget let kan genanvende sine eksisterende Ajax scripts i f.eks en Silverlight applikation. VB er som altid representeret af hensyn til Microsofts eget Office team. IronRuby og IronPython er enormt populære sprog der er svære at komme uden om - og de har en force i at de begge har en lækker syntaks der er meget lidt verbos.

Mix and Match

Der før omtalte eksempel fra MIX07 synes jeg gav en virkelig god idé om hvilke muligheder der vil være for at lege "Mix and Match" i fremtiden, da det illustrerer hvor enkelt man kan blande forskellige sprog - hvad end det er CLR eller DLR sprog, og hvad enten det er ASP, Silverlight eller helt almindelig HTML.

Eksemplet er en Silverlight applikation skrevet i Ruby og benytter en knap skrevet i C#, som kører et animationsscript skrevet i DLR JavaScript der viser tekstelementer der floater rundt. Teksterne er hentet fra en service skrevet i VB, udfra et ord der er indtastet i en HTML textbox som tilgås via Silverlights HTML DOM.

require 'Silverlight.Samples.Controls.Version=0.0.0.0'

Controls = Silverlignt.Samples.Controls
Document = System.Windows.Browser.HtmlPage.Document

JS = require '3dText.js'
VB = require 'technorati.vbx'

def initialize(s, e)
    button = Controls.Button.new
    button.Text = "Click me"

    JS.initialize

    root.children.add button

    button.click do |s, e|
        JS.clearList
        term = Document.txtSearchTerm.Value
        items = VB.GetTitles(term)
        items.each { |item| JS.initializeName(item)}
        JS.playAnimation
    end
end

Som man kan se er Ruby meget letvægts, og hvis man tænker over antallet af komponenter skrevet i forskellige sprog fra forskellige miljøer der arbejder sammen her kan man ikke undgå at blive lidt imponeret over hvor smertefrit CLR og DLR sprog taler sammen.

Det er værd at bide mærke i de første 5 linier fra eksemplet hvor man ser hvor let det er at importerer komponenter fra serveren, samt at referere til dynamisk kode skrevet i andre sprog. Det er ganske enkelt bare at bruge en simpel require statement.

Derefter viser eksemplet en initialize metode, som det er defineret i den tilhørende XAML fil skal kaldes ved init. I initialize instantieres så en knap, og en tilsvarende initialize metode på JavaScript komponenten kaldes. Knappen tilføjes så til et canvas der er navngivet root. Knappen for derefter tildelt en anonym eventhandler, der clearer den liste af tekster og tilføjer nye ord hentet fra VB servicen. Til sidst er det blot at starte animationen og så er koden kørende.

Hvordan platformen blev til.

En sjov historie fra videoen er at en af dem der har været med til at lave det oprindeligt startede med at ville skrive en artikel for at lave grin med Microsoft, da han havde hørt at .NET var elendigt at bygge dynamiske sprog oven på.
Han skrev så en implementation af Python oven på CLR'en - og til hans store overraskelse sparkede den røv på den originale Python. Med andre ord viste benchmarks at hans implementation performede dobbelt så godt! Derefter endte han så med at arbejde for Microsoft og har været med til at bygge denne platform til at hoste dynamiske sprog.

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List