Archive

Posts Tagged ‘IronPython’

The IronPython standard libraries dilemma – [a learning strategy]

August 5th, 2009 Simon Segal 4 comments

The choices facing any programmer wanting to start working with IronPython or IronRuby for that matter, contain some interesting questions. Working with Dynamic languages in .NET prompts us to consider whether to use Python / Ruby native standard library method and functions or directly work against the BCL? If your programming in a statically typed language on top of the CLR, then it’s just different syntax but the same platform libraries. If you want to try your hand with IronPython or IronRuby you need to consider that both these languages have evolved on different platforms. For example, should I consider using Python standard library functions to interpolate some strings or should I use the BCL? Consider these two approaches:

Classic Python Version

print should I use python functions or .Net? +
                    Ans = %(yes)s % {yes: yes}

BCL Centric Version

print String.Format(should I use python functions +
    or .NET? Ans = {0}, BCL Functions)

So that was pretty trivial. What about File access?

Classic Python Version

 rdrp = open(r”c:\Document1.txt)
 rdrp.read()

BCL Centric Version

 rdr = StreamReader(r”c:\Document1.txt)
 print rdr.ReadToEnd()

Any clearer on a choice? The pragmatist in me says use the BCL and the purist says use the python standard libraries. So how heavy should our BCL wielding hand be? This leads me nicely to the next question, how exactly should we go about learning a Dynamic .NET Language? Surely this process will help us make up our minds about when to use the BCL and when not to? Something tells me that the answer lies pragmatically somewhere in the middle ground? The kind of meat and potato stuff like that demonstrated above is likely going to have me opt for the classic Python approach as my default position, however I am not going to put myself to the trouble of working with databases for example without the help of ADO.Net. To help myself form my own opinions I decided that the best learning path for me was as follows:

  1. Read the Python 2.5 (CPython) documentations PDF Tutorial and re-type it’s code examples and follow with my own experimenting.
    • This allowed me to get a fairly good overall feeling for the language.
  2. Read IronPython in Action to get a good overall point of relevance to .NET and see how the power of .NET as a platform would impact the Python experience and visa versa.
  3. Read Python is a Nutshell and get a grasp on Python’s roots and how the language is best put to use on it’s original platform (the C implementation).

Some people will surely think that points 2 and 3 should be reversed? Perhaps, but my rationale for taking this approach is that Python is not likely to become a daily instrument in my work and I want to understand as much as possible about it in the .NET world first. I do believe however that to truly understand the power of Python I will need to learn deeply about its roots and oddly I suppose that step in the process will come last.

Share/Save/Bookmark

Categories: DLR, IronPython, IronRuby, Languages Tags:

Configuring, Testing and Probing NServiceBus with IronPython

July 6th, 2009 Simon Segal 1 comment

I have recently been working with NServiceBus quite a bit and whilst I was working on a WPF IronPython Console - User Control / Window, it occurred to me that it would be a useful tool in testing and monitoring behaviour of my services whilst running under NServiceBus. Let’s have a look at the simplest of examples by configuring up an IBus and publishing messages using Udi’s PubSub sample.

The first change to Udi’s sample code comes in the publisher where the main method’s body no longer contains any configuration code whatsoever.

using System;
using Common.Logging;
using NServiceBus;
using Messages;
using System.Collections.Generic;
using System.ComponentModel;
using Org.TechA.Wpf.Controls;
using NServiceBus.Unicast.Transport.Msmq.Config;
using NServiceBus.Unicast.Transport.Msmq;
using NServiceBus.ObjectBuilder;

//register the extensions for configuration
//so IronPython can see the extension methods

[assembly: Microsoft.Scripting.Runtime.ExtensionType(
    typeof(Configure),
    typeof(ConfigureSpringBuilder))]

[assembly: Microsoft.Scripting.Runtime.ExtensionType(
    typeof(Configure),
    typeof(ConfigureMsmqSubscriptionStorage))]

[assembly: Microsoft.Scripting.Runtime.ExtensionType(
    typeof(Configure),
    typeof(ConfigureXmlSerializer))]

[assembly: Microsoft.Scripting.Runtime.ExtensionType(
    typeof(Configure),
    typeof(ConfigureMsmqTransport))]

[assembly: Microsoft.Scripting.Runtime.ExtensionType(
    typeof(Configure),
    typeof(ConfigureUnicastBus))]

[assembly: Microsoft.Scripting.Runtime.ExtensionType(
    typeof(Configure),
    typeof(ConfigureUnicastBus))]

namespace Server
{
    class Program
    {
        static IBus bus = null;

        [STAThread]
        static void Main()
        {
            LogManager.GetLogger(“hello”).Debug(“Started.”);
            var ir_window = new ConsoleWindow();
            ir_window.ShowDialog();
        }
    }
}

What’s been added here is the decoration of the assembly with a set of ExtensionType attributes from the DLR to allow us to program against the NServiceBus fluent interfaces extension methods from IronPython. The other thing to note in the code above is that the configuration code from the PubSub sample is removed and what now remains is to create and run an instance of the IronPython Application Shell, effectively embedding IronPython into my NServiceBus publisher. Once this is done we are all set to start scripting our services and NServiceBus. If I run this code above I expect to see the the IronPython Application Scripting Window pop up ready for action.

click to open in another window

Configure the Bus and Send a message

Here’s a look at a sample script typed at the console window (see above) to configure the bus and start sending some messages.

#import the relevant libraries
from System import *
from NServiceBus import *
import clr

#add a reference to the messages
#library from the pubsub sample
#and import it
clr.AddReference(“Messages”)
from Messages import *

#configure the IBus 
#NOTE: type this line as a WHOLE in the 
#IronPython Console Window
bus = Configure.With()
                .SpringBuilder()
                .MsmqSubscriptionStorage()
                .XmlSerializer().MsmqTransport()
                .IsTransactional(True).PurgeOnStartup(False)
                .UnicastBus()
                .ImpersonateSender(False)
                .CreateBus()
                .Start()

#create some messages
msg1 = EventMessage()
msg1.EventId = Guid.NewGuid()
msg1.Duration = TimeSpan(99999)
msg1.Time = DateTime.Now 

msg2 = EventMessage()
msg2.EventId = Guid.NewGuid()
msg2.Duration = TimeSpan(99999)
msg2.Time = DateTime.Now.AddYears(-1)

#prove that the messages have values
print msg1.EventId.ToString()
print msg2.EventId.ToString()

#put the messages in an array 
msgs = Array[EventMessage]((msg1, msg2))

#publish the messages
bus.Publish[EventMessage](msgs)

Running the Code

After running this script above we can expect our subscribers to start receiving the messages and we can check to see if indeed the Guid and DateTime property values in the messages match up once being received by the subscribers.

click to see full size

As you can see, our EventId values and other properties all match those created using a REPL experience with IronPython embedded as our publisher. The Dynamic languages turn out to be useful in other places when it comes to NServiceBus but we will leave that for another post soon.

Also, I would like to point out that you could leave the configuration code in the C# code that starts up the publisher and push the IBus instance as a variable into the scope of the IronPython runtime and then execute a similar (smaller) script against it. The IronPython Application Shell has a method that allows you to add variables into the scope ad-hoc from the statically typed side of the publisher. Here’s how to achieve that:

[STAThread]
static void Main()
{
    LogManager.GetLogger(“hello”).Debug(“Started.”);

    bus = NServiceBus.Configure.With()
        .SpringBuilder()
        .MsmqSubscriptionStorage()
        .XmlSerializer()
        .MsmqTransport()
            .IsTransactional(true)
            .PurgeOnStartup(false)
        .UnicastBus()
            .ImpersonateSender(false)
        .CreateBus()
        .Start();

    var ir_window = new ConsoleWindow();

    var vars = new Dictionary<string, object>();
    vars.Add(“bus”, bus);
    ir_window.ctlIronPythonConsole.OnVariablesAdded(vars);

    ir_window.Title = “NServiceBus IronPython Publisher”;
    ir_window.ShowDialog();
}

You can find the full code here and if your interested in downloading The IronPython Application Shell, it can be found here.

Below is the link to the full sample including the the NServiceBus PubSub sample, however you should remember to setup the queues that are required (by the NServiceBus samples themselves) by running the VbScript that comes with the download of NServiceBus itself.

NServiceBus-Pub/Sub Example with IronPython Application Shell

Share/Save/Bookmark

An IronPython REPL Console in a WPF User Control

July 1st, 2009 Simon Segal 2 comments

Recently I posted an IronRuby Console, purpose built as a WPF user control. The basic reasoning was to allow me drop in scripting into any given application or User Interface. In more recent times (with some help from Michael) I decided to ‘jump ships’ and move to IronPython as my choice DLR language. Given the change in direction I was obviously going to need my console window to support the language of my choosing.

The New IronPython Version

tipas_public_intro

So to move forward with the WPF user control console project I decided to refactor it to support IronPython. Mark has jumped in just recently and started to contribute by adding the new “cached commands”, which offer up / down arrow repeat command behaviour such as found on a DOS console. You will also notice from the screenshot above I have imported the entire System namespace to demonstrate that it is possible (using the environment menu) to print the entire state of the default scopes current set of variables.

Now it’s true I could have done this in a way that allowed for switching between the languages, however I have delayed that decision until IronRuby reaches it’s version 1.0 official release. In the meantime you can now use the IronPython version or the IronRuby Version seperately.

I am going to follow up shortly with an example of how this little window can be become quite useful in a practical way.

Downloads

IronPython Console Window Project

IronRuby Console Window Project

Share/Save/Bookmark

Categories: DLR, IronPython Tags: ,
Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia