Living in the Tech Avalanche Generation

A practitioner’s introspective on technology

Archive for the 'DLR' Category

An IronPython REPL Console in a WPF User Control

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

2 comments

A WPF - IronRuby Scripting Console User Control

One of the clear value added possibilities with IronRuby and IronPython (or any DLR language) has to offer is making applications scriptable. This opens the possibility for enabling scripting of your application, it’s types and potentially objects running in memory in your application at runtime. I recently went looking for an IronRuby console / shell window control written natively in WPF and turned up nothing. I did however come across some examples implemented for Windows Forms and the one that got my attention was Orion Edwards Embedded IronRuby Interactive Console.

Whilst Orion’s project provided the basis of what I was after, I was under no illusion that I would find exactly what I was after and would therefore have to build out the rest of the functionality I required.

The Basic Requirements List

  • Reusable WPF User Control
  • The Console should allow users to write script against in memory objects of the host application.
  • Should persist (to a log) the state of variables in the IronRuby runtime scopes.
  • Extensible Application Design and easily maintained and Testable.

So rather than re-invent the wheel I started out with Orion’s code and worked it into a WPF User Control that followed the MVP pattern. This version supports printing of all scope variable state to the console window, clearing of the console window text and all the out of the box access to the IronRuby runtime from the console itself. The IronRuby Console User control also allows the consumer application to pass through in memory variables from your managed CLR hosting application.

ir_console_for_wpf

Finally I need to also make mention that some of the classes used to stream the STD/IO came directly from Ben Halls wonderful IronEditor. And before I forget, the code can found here on my blogs subversion repository.

Share/Save/Bookmark

3 comments

Entity Framework Profiler with IronRuby and IronPython Scripting

ir_console_ef_profilerBecause I would like to write my Repositories and monitor their behaviour in the Profiler I decided that I could kill two birds with one console (so to speak). The first bird to kill involved my spending as much time as possible in the pursuit of both learning IronRuby and gaining better understanding of the more interesting problems that can be solved with dynamic languages implemented on top of the DLR. I can see the possibilities of hosting the DLR to provide scripting support to applications and after having implemented my own hosted IronRuby consoles I eventually decided to reuse one that was more fully featured, saving me quite a bit of time by best fitting the Profiler’s needs. The console I chose in the end was IronEditor which is available on codeplex. IronEditor is implemented as a Windows Forms application and so I did have to refactor it a little to make it work as User Control and have the UI behave correctly for asynchronous updates to the UI. Hosting the Windows User Control in the WPF Profiler was of course simple enough by leveraging the WindowsFormsHost.

I had already posted about what to expect from the next iteration of the Profiler and I won’t repeat it here, so if your new to the tool I suggest you look here. One further change I flagged was to remove WCF from the application and have the messaging occur via sockets. I decided against that change and chose instead (see below) to take the opportunity to demonstrate how to use WCF UnTyped Messages with a bit of IoC to achieve a more loosely coupled approach to handling messages. This approach requires writing specific handlers for specific messages that are not in any way coupled to the signature of any RPC / CRUD looking ServiceContract or the shape of any DataContract, and it is a style somewhat (largely) borrowed from NServiceBus. Here’s the code from the WCF Service and I will have more to say on that a bit later with a more detailed post.

Messaging

public void SendAny(Message message)
{
    object msg_in_body = null;

    var container =
        new Castle.Windsor.WindsorContainer();

    //get all the potential handlers in the assembly
    //NOTE: could load all these up at startup and call
    //to find one that matches from memory rather than
    //in the same iteration that adds the components
    //to the container.
    var libTypes = from a in Assembly.GetExecutingAssembly().GetTypes()
                   from i in a.GetInterfaces()
                   from ii in i.GetInterfaces()
                   from g in i.GetGenericArguments()
                   from gi in g.GetInterfaces()
                   where ii.IsAssignableFrom(typeof(IMessageHandler))
                   where gi.IsAssignableFrom(typeof(IMessage))
                   select new
                   {
                       TheType = a,
                       TheIface = i,
                       TheGeneric = g,
                       TheGenericIface = gi
                   };

    //iterate all the handlers
    foreach (var gen in libTypes)
    {
        container.AddComponent(gen.TheType.Name, gen.TheType);
        //attempt to deserialize using the current
        //handlers generic argument (the message)
        msg_in_body =
            MessageSerializer.DeserializeMessage
            (message, gen.TheGeneric);
        if (msg_in_body != null)
        {
            //resolve the message handler in the container
            var the_handler =
                container.Resolve(gen.TheType);
            var handle_method =
                the_handler.GetType().GetMethod(“Handle”);
            if(handle_method != null)
                handle_method.Invoke(the_handler,
                    new[] { msg_in_body });
        }
    }
}

The Messages And Message Handlers

public interface IMessage
{
    Guid MessageID { get; }
}

public interface IMessageHandler {  }

public interface IMessageHandler<TMessage> :
                 IMessageHandler where TMessage : IMessage
{
    void Handle(TMessage message);
}

public class EntityInterceptMessage : IMessage
{
    [XmlElement(Order = 1)]
    public Guid MessageID
    {
        get { return _id; }
        set { _id = value; }
    }

    [XmlElement(Order = 2)]
    public string SqlQueryText
    {
        get { return _sql; }
        set { _sql = value; }
    }

    [XmlElement(Order = 3)]
    public string ProcessID
    {
        get { return _processId; }
        set { _processId = value; }
    }

    //….message members etc

}

public class EntityInterceptMessageHandler :
             IMessageHandler<EntityInterceptMessage>
{
    public void Handle(EntityInterceptMessage message)
    {
        ProfilerModel.EntityMessages.Add(message);
        Console.WriteLine(message.EntityModelName);
    }
}

Running the Application

You can run this code and test it using a supplied IronRuby script named “run_profiler_script.rb”, just make sure you have the Northwind database installed , that the script gets the required changes to match your database details and that the the test projects DLL is ‘required’ from the appropriate location on your hard drive.

require ‘D:/simon.segal/Local Working/Org.TechA.EF.Profiler’ +
    ‘/Org.TechA.EF.Profiler.Tests/bin/Debug’ +
    ‘/Org.TechA.EF.Profiler.Tests.dll’

By downloading you will be accepting the code project open license for the SQL CodeBox control and the Apache License 2.0 for IronEditor, both of which have been integrated into this solution. You can download the Profiler from here.

UPDATE: (Sunday April 19th)

Apologies for having an earlier link to the code being incomplete. The problem has now been rectified.

Share/Save/Bookmark

5 comments

« Previous PageNext Page »

Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia