Sunday, December 27, 2009

Using an IronPython object from C#

The new keyword “dynamic” added to C# (.Net 4.0) allows you to interoperate with any dynamic language such as IronPython or IronRuby.

This new feature bypasses any static type checking at compile time, assuming that any operation is allowed. But, if it is not allowed, an error will be showed at run time.

For example, the following Customer “IronPython Class” is invoked from the C# code as a dynamic object:


IronPython code (Sample.py)

# Function (method) that creates a new Customer
def CreateCustomer(firstName, lastName):
    return Customer(firstName, lastName)

# Customer object
class Customer(object): 

    # Initialization (constructor)
    def __init__(self, firstName, lastName):
        self._firstName = firstName
        self._lastName = lastName

    # Function (method) that print the customer
    def printNames(self):
        print self._firstName + ' ' + self._lastName


C# code (Program.cs)

using Microsoft.Scripting.Hosting;
using IronPython.Hosting;

class Program
{
    static void Main(string[] args)
    {

        ScriptRuntime py = Python.CreateRuntime();
        dynamic sample = py.UseFile("Sample.py");
        dynamic customer = sample.CreateCustomer("Paul", "Smith");
        customer.printNames();
    }
}


You can download the source code here.

Tuesday, December 22, 2009

Using PLINQ to improve performance

The version 4.0 of .Net has a new feature called “Parallel LINQ” or PLINQ. If you use LINQ to filter or process a large amount of objects in memory and/or it is required a high-cost evaluation, PLINQ is for you.

PLINQ segments the source in parts and it uses different threads in order to process each segment.

var validCustomers = allCustomers.AsParallel()
  .Where(c => c.IsValid())
  .ToArray();

PLINQ

Here you can download the sample code.

For more details I recommend you to watch the Igor Ostrovsky presentation in the PDC 2009 webpage.