Archive

Archive for the ‘IronPython’ Category

Patterns that cross borders - C# to IronPython

January 6th, 2010 Simon Segal 2 comments

Recent consideration of the Template Method Pattern got me to wondering about how I might achieve a little more dynamism with respect to declaration, definition and instantiation when using the template method pattern. Without delving too deep into the “classical” Template Method Pattern it can be described here in code with the most trivial of examples.

C# Classic Template Method Pattern

abstract class FootballMatch
{
    abstract void StartGame();

    abstract void EndGame();

    public virtual void PlayGame()
    {
        Console.Writeline("Players kick the ball around a field");
    }

    public virtual void CompleteMatch()
    {
        StartGame();
        PlayGame();
        EndGame();
        Console.WriteLine("Match completed thanks for attending!");
    }
}

public class AustralianRulesFootballMatch : FootballMatch
{
    public void StartGame()
    {
        Console.WriteLine("Siren blows to begin game….");
    }

    public void EndGame()
    {
        Console.WriteLine("Siren blows to end game….");
    }
}

public class SoccerFootballMatch : FootballMatch
{
    public void StartGame()
    {
        Console.WriteLine("Referee blows whistle to begin game….");
    }

    public void EndGame()
    {
        Console.WriteLine("Referee blows whistle to end game….");
    }
}

 

What about Functions? And how about runtime implementer?

As described above, the implementing classes are defined at design time as concrete derived classes. Doing this in Languages such as Python and Ruby seems a little more flexible in as much that I don’t really require the derivation through an abstract class.

An IronPython Implementation

class RestuarantEndToEndService:

    def __init__(self, servicename, m1, m2, m3, m4):
        self._serviceName = servicename
        self._greetAndQualifyCustomer = m1
        self._takeCustomerOrder = m2
        self._serveTheCustomerMeal = m3
        self._takePayment = m4

    def prepareTheMeal(self):
        print Chef prepares the meal

    def performService(self):
        print Doing %(svc)s Service % {svc : self._serviceName}
        self._greetAndQualifyCustomer()
        self._takeCustomerOrder()
        self.prepareTheMeal()
        self._serveTheCustomerMeal()
        self._takePayment()

def seatCustomer():
    print Greet and seat the customer at their table

def answerOrdersPhoneLine():
    print Answer the phone and take the customer details

def takeCustomerOrder():
    print Waiter / Waitress takes the customers order

def takeCustomerPhoneOrder():
    print Take the customers order by phone

def serveTheCustomer():
    print Waiter / Waitress serves customer their meal

def deliverTheCustomerPhoneOrder():
    print Driver delivers the customers phone order

def takeCustomerPaymentAtCounter():
    print Cashier takes customer payment

def takeCustomerPaymentOnDelivery():
    print Driver takes customer payment

inhouseService = RestuarantEndToEndService(In House,
                    seatCustomer,
                    takeCustomerOrder,
                    serveTheCustomer,
                    takeCustomerPaymentAtCounter)
deliveryService = RestuarantEndToEndService(Delivered,
                    answerOrdersPhoneLine,
                    takeCustomerPhoneOrder,
                    deliverTheCustomerPhoneOrder,
                    takeCustomerPaymentOnDelivery)

inhouseService.performService()
print ***********************
deliveryService.performService()

The DLR, Interop and shifting the code around

What’s a little more interesting is using this pattern in interop scenarios when the templated class is defined in a statically typed language and the template method is supplied by a dynamic language created for the DLR. This can be demonstrated here with the given abstract class and by using my IronPython WPF interactive console control.

public abstract class TemplateClass
{
    public abstract void Operation1();
    public abstract void Operation2();

    /// <summary>
    /// The Tempate Method
    /// </summary>
    public void TheTemplateMethod()
    {
        Operation1();
        Operation2();
    }
}

ip_swap_abstract_from_csharp

Using the Python Help function we can examine the abstract template class and see how it’s been defined. Looking at the printed help on the class it’s clear that the two abstract methods have ‘tagged along for the ride’ as expected. You wont be able to execute them until you provide an implementation, just as you would expect given it’s an abstract class.

ip_swap_abstract_from_csharp_help

The other scenario involves moving some statically typed code (a method) to the IronPython runtime and using an Action / Delegate to  ‘fill in’ the template algorithm in a dynamically typed class. For example in the EndToEndRestuarantService class defined in Python above, we could push the actions (delegates) over from C# to the IronPython runtime. Given a set of Functions defined in managed C#:

var actions = new Dictionary<string, object>();
actions.Add("seat", seat_customer);
actions.Add("order", take_customerOrder);
actions.Add("serve", serve_the_customer);
actions.Add("pay", take_customer_payment_at_counter);

When you push these functions over the Script Scope running the IronPython code, then you can pass those functions around to any other code running within the same scope. With our Restaurant example we can take our named functions from the C# code at runtime and push them into the constructor of our IronPython class:

ip_swap_abstract_from_csharp_func_constructs

When is this pattern useful?

These patterns can be useful in scenarios where you might be considering scripting your managed C# application and providing DLR supported scripting functionality to the application as well. It can also be quite useful when you want to expose some technology that does not currently support full interop (Entity Framework for example) or perhaps you want to make our application model visible to IronPython or IronRuby. There are of course a plethora of patterns that can be implemented in code that can traverse both environments; its really a matter of what we can devise with some imagination.

Share/Save/Bookmark

Categories: DLR, IronPython, IronRuby Tags: , ,

Do I qualify as a polyglot programmer? A matter of distinction.

January 3rd, 2010 Simon Segal No comments

If I could teach myself to write hello world in twenty languages that would not do it! Clearly a ridiculous way of measuring isn’t it. But seriously how do we go about qualifying whether our knowledge in a given language is of any value (to anyone, including ourselves).

A common mantra of the polyglot programmer (as espoused by some) is to learn a new language every year. This is an interesting idea, however in isolation it sounds perhaps somewhat of a generalisation without a clear purpose. It’s my experience that we human beings have an equally strong capacity to forget as we do learn (not in equal measure), and without 3-heads_langs exercise we can easily lose some our fluency and dexterity when working with languages. If I were to learn a language every year I would no sooner forget much about them without regular usage. Can we really be expected to employ a host of languages in our day to day work and is that even the goal? I think a specialised meaning for the word ‘learning’ is what’s missing here but let’s come back to that later.

I must profess that I am extremely interested in learning new programming languages, I find it stimulating for a variety of reasons; someone (I forget who – sorry) remarked on twitter recently about how fabulous it is to feel totally unknowing at the outset of learning something totally new. Over the course of the past year I have invested significant personal time in learning both Ruby and then Python and did enjoy some small opportunity to put IronPython into practice commercially in 2009. I do not consider myself a strong Python or Ruby Developer, far, far, far from it; C# continues to enjoy my most significant attention and depth of knowledge, a reasonable outcome given it is the language I spend most days plying my trade. I do however consider myself strong enough as a developer to leverage my existing knowledge in programming and capacity to be resourceful, to employ new languages to my benefit if they are the right tool for a given job. No doubt over time and with more experience my rating with Python will increase but I am happy with where it is right now, it’s somewhat in line with my planning, expectations and requirements.

My interest in Python at this point is quite singular, it is a window to the Dynamic Language Runtime and specifically one of the languages which can be leveraged to script the more significant C# projects I am engaged in. Do I need to become equally knowledgeable in Python to leverage it in this manner? Must one exercise mastery of all chosen languages with proportionate levels of precision? My current mode of thinking on this point is we don’t need to, however, as always I am open and curious to hear other points of view.

How does one choose which language to learn next. I don’t think developers should pressure themselves into making hasty decisions in this regard. My own approach was to sample them both first – study a reasonably significant language guide (from each) and spend some time (1 hour a day) writing code (in each) – then make up my mind. After going through the ‘sampling’ exercise, I chose to Python initially however that doesn’t mean I wont one day decide to invest more time into Ruby, I like Ruby. One of the most commonly touted value propositions in learning a new language, is that it helps us become more rounded as developers opening our minds to a broader range of programming techniques and design possibilities. I think we are mature enough these days (as a profession) that the religious language wars are becoming consigned to the past, part of our less enlightened and evolved communal selves.

Most recently I have emerged myself in learning Erlang. Erlang’s established position in the world of highly concurrent distributed systems is the key to driving my interest here, I want to better understand the wider implications and possibilities in the language and platform. A secondary motive is that it will give me a good opportunity to learn a functional language after having now tasted the fruits of statically typed and dynamic languages. Does this mean I will tie myself to the Erlang banner now? Not at all, it’s just the starting place for me, I will look at AXUM and F# over the coming twelve months. AXUM may never get out of MS Research, who knows, but going on what Luke Hoban said at the PDC09, F# may reap some of the benefits from AXUM’s research, making distributed message passing a part of the language.

Will I become an advanced user of Erlang – I don’t know, for now all I plan to do is read Joe Armstrong’s book and type of bit of code at the Erlang Shell, but that doesn’t preclude the possibility that I will use Erlang in a professional capacity at some point in time.

So am I a polyglot programmer? Does it require commercial implementation or does personal study aimed at greater understanding qualify. What level of command of languages does one ascertain to become a true polyglot programmer? What languages qualify for polyglot distinction – what about JavaScript, CSS and XML, surely most web developers must find themselves in a default position of being a Polyglot just to survive in their jobs?

Share/Save/Bookmark

Entity Framework, IronPython and PODO’s – Can it be done? - Part 1

December 31st, 2009 Simon Segal 5 comments

Let’s go on a journey that takes two interesting technologies that have been to date, confined to an interoperability argument that left them barely on speaking terms. Of course I am speaking figuratively but what I’m trying to convey here is that, languages built to run on the DLR are currently limited in ways that preclude them from working seamlessly with the LINQ based ORM technologies from Microsoft, namely the Entity Framework and LINQ To SQL. This of course does not mean that languages such as IronPython are stuck in some ADO.NET void, that is not the case at all. In fact if you want to check how to use ADO.Net Data Readers etc, from IronPython I suggest check out chapter 13 of IronPython in Action (in fact if IronPython is of interest I can highly recommend the book).

Before we continue lets touch on some background. An important part of getting IronPython entities working alongside the Entity Framework, required that the Entity Framework would be calling back into our IronPython code. In recent times, a new feature was added to IronPython 2.6 which accommodated this requirement. The __clrtype__ feature allows customization of the classes that constitute the underlying CLR types for IronPython classes. If you want to find out more about this you should read the series of posts by Harry Pearson on the subject.

So with a fistful of interest in the DLR and the dynamic languages built on it, I became curious about whether the new advances and features in the Entity Framework version 4.0 combined with the addition of __clrtype__ meta class for IronPython, would bring these two technologies any closer to working together. After some pointers in a recent discussion with Michael Foord, I was willing to bet that some form of interop between the two (EF and IronPython) would now be possible; I was gambling on the added support for POCO in the Entity Framework and the customising of CLR types generated for IronPython to provide the neccessary hooks to effectively create PODO’s (Plain Old DLR Objects) that would map successfully as Entity Framework entities. Here is what I was hoping a PODO might look like.

class Customer(object):

    __metaclass__ = clrtype.ClrClass
    _clrnamespace = EntityFramework.Podo
    _clrfields = {  _customerId:str,
                    _companyName:str,
                    _contactName:str
                 }

    @property
    @clrtype.accepts()
    @clrtype.returns(clr.GetClrType(str))
    def CustomerID(self):
        return self._customerId

    @CustomerID.setter
    @clrtype.accepts(clr.GetClrType(str))
    @clrtype.returns()
    def CustomerID(self, value):
        self._customerId = value

    @property
    @clrtype.accepts()
    @clrtype.returns(str)
    def CompanyName(self):
        return self._companyName

    @CompanyName.setter
    @clrtype.accepts(str)
    @clrtype.returns()
    def CompanyName(self, value):
        self._companyName = value

    @property
    @clrtype.accepts()
    @clrtype.returns(str)
    def ContactName(self):
        return self._contactName

    @ContactName.setter
    @clrtype.accepts(str)
    @clrtype.returns()
    def ContactName(self, value):
        self._contactName = value

First up, I guess that in a pure sense this is not so compliant in the P part of PODO right? The Decorators on our functions do bleed out the technology a little but I am not going to let the goal get hung up on this point.

My initial thoughts also considered that with Code Only mapping I might be able to do away with any need to provide any supporting infrastructure code created in a statically typed language (C# or VB.NET).

In Part 2.0 of this series of posts we will start the journey in earnest and see what successes and hurdles we hit along the way. Rather than keep you waiting to find out whether this is all going to end well and keep you dangling under false pretences, let me just say that it partially works. The fact that it partially works gives me hope the rest of this series might help uncover or encourage a way to make these two technologies work together in a more complete way.

Share/Save/Bookmark

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