Archive

Archive for the ‘Languages’ Category

Curried Event Handlers or - Lazy Event Handling in Functional C#

April 15th, 2009 Simon Segal 1 comment

There has been a lot of buzz lately about the ‘other’ styles of programming that exist outside of our warm and cosy statically typed imperative world. Dynamic and Functional programming languages are starting to generate some deep interest in the community and anyone who reads this blog from time to time would know that I too have been dragged in by the gravity of IronRuby.

F#, whilst interesting to me, alas must take a back seat to IronRuby as it’s going to have to be one language at a time for this little polyglot, however I keep coming across interesting information that promotes a Functional approach in C# and VB.NET. The approach leverages some of the newer (3.5) language features syntactically but really the core of what’s possible lies in the what became available in C# 2.0. There is of course always a ubiquitous example so lets stick with that - a function that takes an integer as an argument and returns a function that also takes an integer as an argument and returns an integer that adds the two together. Consider this code:

[Test()]
public void CurryInTwoDotZeroFramework()
{
    FuncInTwoZeroStyle two_zero_func =
        new FuncInTwoZeroStyle(delegate(int x)
            {
                return delegate(int y)
                {
                    return  x + y;
                };
            });

    var first_func_has_10 = two_zero_func(10);
    var second_func_has_another_10_makes_20 =
        first_func_has_10(10);

    Assert.AreEqual(20,
        second_func_has_another_10_makes_20);
}

functional_delegates_watch 

What’s happening here is that we get a kind of closure behaviour where 10 gets stored away with the function. From the compilers point of view we know that delegates at runtime have a class generated with a target and a method and in our example we have 10 as the object instance being the target and the returned function is the “Method” that gets wrapped up in our runtime generated class. For a good discussion on how delegates work under the hood it’s worth reading this post.

Currying – a style of cooking or programming practice?

Something that Functional devotees often talk about is the ability to write functions that return functions, often referred to as “currying”. Interestingly the Wikipedia definition includes the following:

The practical motivation for currying is that very often the functions obtained by supplying some but not all of the arguments to a curried function (often called partial application) are useful; for example, many languages have a function or operator similar to plus_one. Currying makes it easy to define these functions.

Our .NET 2.0 example above can be redefined in 3.5 with some syntactic sugar like this:

public void basic_add_Curry()
{
    Func<int, Func<int, int>> curry_add_ten =
        x => y => x + y;

    var add_to_10 = curry_add_ten(10);

    var should_be_20 = add_to_10(10);
    var should_be_30 = add_to_10(20);
    var should_be_40 = add_to_10(30);

    Assert.AreEqual(20, should_be_20);
    Assert.AreEqual(30, should_be_30);
    Assert.AreEqual(40, should_be_40);
}

 

You mentioned Events?

I don’t want to go over ground already largely covered elsewhere so let me focus in what I thought was a slight deviation that offered up an interesting possibility. What about event subscriptions? Can we ‘curry’ event handlers? The answer is yes of course we can. Let me demonstrate.

internal class MyObjectWithAnEvent
{
    internal event EventHandler subscribe_with_action_event;

    internal void on_subscribe_with_action_event()
    {
        if(subscribe_with_action_event != null )
            this.subscribe_with_action_event
                ("’an event subscribed to by Action<>’",
                    new EventArgs());
    }
}

and we can subscribe to the event in this class like this:

public void event_handling_curry()
{
    //simple Action delegate
    Action<int, int> takes_two_ints =
        (x, y) => Console.WriteLine(x + y);

    takes_two_ints.Invoke(2,3);

    //Action matching signiture of EventHandler delegates
    Action<object, EventArgs> a_standard_event_delegate =
        (x, y) => Console.WriteLine(String.Format("{0}:{1}", x, y));

    //new up an object that has an event to subscribe to
    MyObjectWithAnEvent obj_to_subscribe_on =
        new MyObjectWithAnEvent();

    //subscribe to the event that implements 
    //an EventHandler delegate
    obj_to_subscribe_on.subscribe_with_action_event +=
        new EventHandler(a_standard_event_delegate);

    //call a method to raise the event
    obj_to_subscribe_on.on_subscribe_with_action_event();

    //declares a function that returns an event handler
    Func<int, Action<object, EventArgs>>
        func_that_returns_event_delegate =
        x => (y, z) => Console.WriteLine(
            string.Format("The values passed to the function was {0} " +
            "and the sender was {1}", x, y));

    //store the value of 100 with the returned event handler
    var action_with_int = func_that_returns_event_delegate(100);

    //subscribe to an event with the delegate 
    //returned by the function
    obj_to_subscribe_on.subscribe_with_action_event +=
        new EventHandler(action_with_int);

    //raise the event
    obj_to_subscribe_on.on_subscribe_with_action_event();
}

What is evident here is that we have returned a delegate that also has access to the contextual data that we had available at runtime when the delegate was computed. This delegate along with the the contextual data (x being equal to 100) might subsequently be used in a further computation at such time as any event is raised in which that delegate in question has been applied as a handler in any such events invocation list. I call this ‘contextual delayed subscription’. Perhaps I want to get a reference to a handler for an event that has not yet occurred and upon certain conditions or actions I will subscribe to that event at a later time or perhaps Just in Time. For example you might choose to store away the delegates and their contextual state until a user of your application indicates that they are interested having an event subscribed where actions occurring in the past are also of interest.

Share/Save/Bookmark

Categories: C#, F#, Languages Tags: ,

IronRuby with LINQ To SQL (kinda)

October 16th, 2008 Simon Segal No comments

I have been playing around with IronRuby a bit just of late and I was curious to see whether it was at a stage where it was working with LINQ To SQL. It was clear from the outset that using LINQ To SQL in the most common way (with full UI experience) in VS.Net was simply a silly thing to expect and it became immediately apparent that any benefit of IEnumerable<T> or IQueryable<T> was out the window also. Given that that any attempt to access IEnumerable<T> from any instance of Table<T> was for now a journey into folly, I tried briefly to circumvent that approach and see if I could POCO my way to an outcome with Mapping files. Listing 1.0 shows this unfortunately doomed venture.

Attempt No # 1.0

First the C# POCO Entity class required in the RubyCustomer library.

using System;

namespace Org.TechAvalanche.Orm.Tests.Domain
{
    public class Customer
    {
        private string _CustomerID;
        private string _CompanyName;
        private string _ContactName;
        private string _ContactTitle;
        private string _Address;
        private string _City;
        private string _Region;
        private string _PostalCode;
        private string _Country;
        private string _Phone;
        private string _Fax;

        public Customer() { }

        public string CustomerID
        {
            get {return this._CustomerID;}
            set {this._CustomerID = value;}
        }

        public string CompanyName
        {
            get {return this._CompanyName;}
            set {this._CompanyName = value;}
        }

        public string ContactName
        {
            get {return this._ContactName;}
            set {this._ContactName = value;}
        }

        public string ContactTitle
        {
            get {return this._ContactTitle;}
            set {this._ContactTitle = value;}
        }

        public string Address
        {
            get {return this._Address;}
            set {this._Address = value;}
        }

        public string City
        {
            get {return this._City;}
            set {this._City = value;}
        }

        public string Region
        {
            get {return this._Region;}
            set {this._Region = value;}
        }

        public string PostalCode
        {
            get {return this._PostalCode;}
            set {this._PostalCode = value;}
        }

        public string Country
        {
            get {return this._Country;}
            set {this._Country = value;}
        }

        public string Phone
        {
            get {return this._Phone;}
            set {this._Phone = value;}
        }

        public string Fax
        {
            get {return this._Fax;}
            set {this._Fax = value;}
        }
    }
}

coupled with the following LINQ To SQL Mapping file

<?xml version=”1.0″ encoding=”utf-8″?>
<Database Name=”Northwind”
    xmlns=”http://schemas.microsoft.com/linqtosql/mapping/2007″>
  <Table Name=”Customers” Member=”Customer”>
    <Type Name=”Org.TechAvalanche.Orm.Tests.Domain.Customer”>
      <Column Name=”CustomerID” Member=”CustomerID” DbType=”NChar(5) NOT NULL”
          IsPrimaryKey=”true” CanBeNull=”false” UpdateCheck=”Never” />
      <Column Name=”CompanyName” Member=”CompanyName”
          DbType=”NVarChar(40) NOT NULL” CanBeNull=”false” UpdateCheck=”Never” />
      <Column Name=”ContactName” Member=”ContactName”
          DbType=”NVarChar(30)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”ContactTitle” Member=”ContactTitle”
          DbType=”NVarChar(30)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”Address” Member=”Address”
          DbType=”NVarChar(60)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”City” Member=”City”
          DbType=”NVarChar(15)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”Region” Member=”Region”
          DbType=”NVarChar(15)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”PostalCode” Member=”PostalCode”
          DbType=”NVarChar(10)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”Country” Member=”Country”
          DbType=”NVarChar(15)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”Phone” Member=”Phone”
          DbType=”NVarChar(24)” CanBeNull=”true” UpdateCheck=”Never” />
      <Column Name=”Fax” Member=”Fax”
          DbType=”NVarChar(24)” CanBeNull=”true” UpdateCheck=”Never” />
    </Type>
  </Table>
</Database>

and now our IronRuby attempt to talk DIRECTLY LINQ To SQL.

require ‘mscorlib’
require ‘System.Core, Version=3.5.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089′
require ‘System.Windows.Forms, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089′
require ‘System.Data.Linq, Version=3.5.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089′
require ‘RubyCustomer, Version=0.0.0.0,
  Culture=neutral, PublicKeyToken=c1aba19d9dedea39′

begin

  #get the mapping into a stream
  stream = System::IO::StreamReader.new(“C:\\Users\\simon.segal” +
    “\\Desktop\\IronRuby\\ironruby\\bin\\DomainMapping.xml”)
  mapping_file =
    System::Data::Linq::Mapping::XmlMappingSource.
      FromStream(stream.BaseStream)
  #new up a DataContext with our mappings
  db = System::Data::Linq::DataContext.new(“server=localhost;initial “+
    “catalog=Northwind;user id=sa;password=supremo”, mapping_file)
  #new up a POCO customer from my C# library
  cust = Org::TechAvalanche::Orm::Tests::Domain::Customer.new
  #not sure if typeof works in IronRuby
  cust_type = cust.GetType()
  #load the table of customers from northwind
  custs = db.GetTable(cust_type)
  #tried to get enumerator but .Current gets a method error 
  #and so ends our journey
  list = custs.GetEnumerator()
  puts “The call to GetEnumerator returned a “ +
    list.GetType.ToString()
  currentCust = list.Current
  rescue Exception => ex
    puts “someone is missing a method!” + ex.to_s
    #just to prove that it’s a Table<Customer>
    puts “Just to show that we did get as far as “ +
           “getting the Table<Customer> : “ +
           custs.ToString()

end

Which yields the following output from standard IO (click to see full view):

ironLinqToSqlFailedOutput

So as you can see here, we get close but no cigar. Ready to give up - damn, not yet! Lets move all the LINQ To SQL code into our custom library and call it from IronRuby - that should work? We already had a POCO in our library referenced above (see the require ‘RubyCustomer’). So here we go.

Attempt No # 2.0

As a jumping off point for attempt # 2, I thought it might be time to check out Ruby In Steel, a third party integrated UI platform for VS.NET and IronRuby. I wanted to be able to keep my C# library with the LINQ To SQL code and the IronRuby consumer code in a single solution if possible and I was looking for a bit of holiday from writing Ruby Code in SciTE and NetBeans, therefore looking at Ruby In Steel had been on the agenda for a while so I figured now was as good a time as any. This gave me a more instantly gratifying experience in developing a Windows Form to present my LINQ To SQL data as well:

Ruby In Steel

As you can see I have my C# project and my IronRuby project coupled together in a single VS.Net solution and whilst Ruby in Steel is not quite as stable or fully featured as you would expect it to be when IronRuby makes it’s official debut, it certainly helped speed things up quite a bit.

The LINQ To SQL code consisted of a run of the mill repository, POCO and mapping file (the entity itself remained as is - see above Customer Class).

using System.Data.Linq;
using System.Linq;

namespace CsharpLinqToSqlForIronRuby
{
    public class CustomerRepository
    {
        private readonly DataContext _context = null;

        public CustomerRepository(DataContext ctx)
        {
            _context = ctx;
        }

        public Customer[] All()
        {
            Customer[] retCustomers = null;
            using (_context)
            {
                retCustomers = _context.GetTable<Customer>().ToArray();
            }
            return retCustomers;
        }

        public Customer FindById(string custId)
        {
            Customer retCustomer = null;

            using (_context)
            {
                retCustomer = _context.GetTable<Customer>().
                    Where(c => c.CustomerID == custId).Single();
            }
            return retCustomer;
        }
    }
}

On the IronRuby side of things, we dialled up a class to handle calling our C# Repository library:

require ‘mscorlib’
require ‘System.Core, Version=3.5.0.0, ‘ +
    ‘Culture=neutral, PublicKeyToken=b77a5c561934e089′
require ‘System.Windows.Forms, Version=2.0.0.0, ‘ +
    ‘Culture=neutral, PublicKeyToken=b77a5c561934e089′
require ‘System.Data.Linq, Version=3.5.0.0, ‘ +
    ‘Culture=neutral, PublicKeyToken=b77a5c561934e089′
require ‘D:/simon.segal/LocalWorking/IronRubyProofs/’ +
    ‘IronRubyWithLinqToSqlForms/IronRubyWithLinqToSqlForms/’ +
    ‘CsharpLinqToSqlForIronRuby.dll’

class CustomerController

    def GetAllCustomers

        #get a stream of the mapping file
        stream = System::IO::StreamReader.new(“D:\\simon.segal\\” +
            “LocalWorking\\IronRubyProofs\\” +
            “IronRubyWithLinqToSqlForms\\” +
            “IronRubyWithLinqToSqlForms\\DomainMapping.xml“)
        #set the mapping source
        mapping_file = System::Data::Linq::Mapping::XmlMappingSource.
            FromStream(stream.BaseStream)
        #new up a DataContext with our mapping
        db = System::Data::Linq::DataContext.new(”server=localhost;initial ” +
            “catalog=Northwind;user id=sa;password=supremo”, mapping_file)
        #new up our repository
        cust_repos = CsharpLinqToSqlForIronRuby::CustomerRepository.new(db)
        #get all the customers
        custs = cust_repos.All()
        #print customers to the console window (in debug)
        custs.each {|cust| puts cust.CompanyName}

        return custs

    end

end

And what we needed now was an IronRuby WinForm to do the presentation work and data binding for us:

ironrubyForm

with the following code behind:
require ‘Form1.designer.rb’
require ‘CustomerController.rb’

class Form1

    #form load
    def Form1_Load(sender, e)
    end

    #button click event handler
    def button1_Click(sender, e)

        controller = CustomerController.new
        self.comboBox1.DisplayMember = “CustomerID”
        self.comboBox1.ValueMember = “CustomerID”
        custs = controller.GetAllCustomers.each {|customer|
            self.comboBox1.Items.Add(customer)}
        self.lstCustomer.DataSource = custs
        self.lstCustomer.DisplayMember = “CustomerID”
        self.lstCustomer.ValueMember = “ContactName”

    end

    #combo box selected index changed handler
    def comboBox1_SelectedIndexChanged(sender, e)
        cust = self.comboBox1.SelectedItem
        self.textBox1.Text = cust.CompanyName
        self.textBox2.Text = cust.ContactName
    end

    #list customer selected index changed handler
    def lstCustomer_SelectedIndexChanged(sender, e)
        cust = self.lstCustomer.SelectedItem
        self.textBox1.Text = cust.CompanyName
        self.textBox2.Text = cust.ContactName
    end

end
So unfortunately right at this moment there is no IronRuby to be had with LINQ To SQL unless it’s via one of the other .NET languages that support it. I would have been more than happy if I had been able to leverage my own custom Repository Framework to do the data access but that isn’t possible with the current limitations either.

Share/Save/Bookmark

Categories: IronRuby, Languages, ORM, POCO Tags: , , ,

Preparing for IronRuby

October 7th, 2008 Simon Segal No comments

I decided to share my experiences on the path to IronRuby so far and perhaps it might be useful to others who wish to travel that road.

Not so long ago I posted about choices in front of me regarding learning a new language. After having programmed in C# for some 7 or so years I wasn’t going to choose another statically typed language, I wanted to add a dynamic language to my arsenal and with the DLR on it’s way and a key interest and stake in the Silverlight, the choice as obvious.

After having decided to dedicate the time and effort to IronRuby, the next question was how to address the learning. Clearly picking up IronRuby as the first pit stop was going to come with some difficulties borne out of the fact that the documentation isn’t great yet and the toolset way of being close. Based on this, I decided that learning Ruby first was the best way to progress this goal for two main reasons, one it allowed me to learn in the comfort of an IDE (NetBeans) to write ‘do as you learn‘ code and also gave me a perspective on IronRuby that is not indifferent to its genealogy.

So after downloading NetBeans (Ruby Edition) and installing Ruby 1.8.6, I got my hands on the excellent free online book by Jeremy McAnally, the title of which is “Mr Neighbourly’s Humble Little Ruby Book“. This book is a nice little quick starter to get you comfortable with the absolute basics of Ruby, but needs to be followed by something with a bit more industrial strength such as Matz very own offering The Ruby Programming Language.

DLR PadOnce having navigated this far, I decided that it was time to pull down the IronRuby bits and start to have a play. A while back now, Hanselman and Gu both posted some early pieces on getting started with IronRuby. Most people seem intent on making XAML based applications the focus of their IronRuby attention, which in turn lead me to DLR Pad (see the image above) which provides the ability to interactively script IronRuby (and IronPython) against a statically set window that contains a XAML UI layout (interesting). From there I found my way to Ivan Porto Carerro’s blog and book on IronRuby. Ivan’s book is not yet released but is available as early access, so I decided to avail myself of it.

And if your wondering what code looks like (see below) for something that you might have been routinely doing (as I was), it doesn’t take long to knock something (trivial in this case) together to begin to get the picture, in the case of having gone down the path I described above.

require ‘mscorlib’
require ‘System.Windows.Forms,
  Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089′

begin

    #alias the forms namespace
    Windows = System::Windows::Forms
    #new up a form & set it’s text
    first_ruby_window = Windows::Form.new
    first_ruby_window.Text = “Simons first Ruby Form”
    #new up a button
    first_ruby_button = Windows::Button.new
    #subscribe to the buttons click event
    first_ruby_button.click {|sender, args| first_ruby_button.Text =
                                    “I got clicked!”}
    #add the button to the form
    first_ruby_window.Controls.Add(first_ruby_button)
    #show my new form
    first_ruby_window.ShowDialog()

end

And we get the following:

first_ruby_form

So that’s my story (to date) and perhaps it offers some help in getting you underway with your IronRuby / DLR journey.

Share/Save/Bookmark

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