Planet IronPython

July 02, 2009

Jimmy Schementi

IronRuby 0.6 Released!

The IronRuby team is pleased to announce a new release of IronRuby: IronRuby 0.6!

Download IronRuby 0.6

You can also get the source code for this release

Staying true to our "Conference-driven development schedule," this release is in conjunction with ... wait, there is no conference this time! Just a good ol' monthly release of IronRuby, chock full of awesomeness. And just so happens to be the 4th of July weekend, so hopefully you have some downtime this weekend and can give the new release a spin.

What's in the Release?

Performance has been a major focus to this release, getting startup time quicker and optimizing built-in types. There has been more progress with Ruby compatibility (Cucumber works!) and .NET interop. Silverlight binaries are back in the release, and there are a couple of samples to help you learn IronRuby.

Most of these descriptions are from Tomas's very detailed code review emails, so thanks Tomas! For more detailed information, please see the CHANGELOG (which includes all commit messages for the release ... not just "syncing to head of tfs")

Lazy method compilation

Last release adaptive compilation was enabled for IronRuby, which uses a fast-to-start-up interpreter to start up the program, while code which gets run a lot is compiling on a background thread. This gave IronRuby significant performance improvements for large apps like Rails, which has improved startup by 2.5 times.

This release we've added "lazy method transformation" to the bag of startup performance tricks. In IronRuby 0.5, a method was transformed to the DLR AST as soon as it was defined. IronRuby 0.6 postpones the transformation until the first time the method is called. This significantly improves startup time. For example (not NGEN'd):

This has made Rails startup time 30% faster, coming in approximately 20 seconds on my dual-core laptop running Windows 7.

CLR member enumeration

Now methods like Module#instance_methods, etc, include CLR member names. Though it's a lot cooler than that. The array of methods returns contains strings for Ruby methods, and objects of type IronRuby::Clr::Name to represent CLR methods that can be called by either the actual CLR name or a mangled (Ruby-esk) name. ClrName has methods to_s, to_sym, to_str, <=>, inspect, and dump so that it can be used wherever a string can be used. The display string for the name uses single quotes so that you can easily distinguish CLR (dual) names from regular names (plain mutable strings). CLR strings display themselves as single quoted strings, so this fits nicely.

Even cooler, this works well for meta-programming:

A new set of define_method overloads, strongly typed to ClrName, have been added to enable this. They define the real method using the ruby_name and alias it using the clr_name. So both CompareTo and compare_to calls are intercepted.

Generic-Method Parameters-Inference

Thanks to some work by the IronPython team, IronRuby now has parameter inference for generic methods.

This needs some more TLC before it works perfectly, but this lets you use simple LINQ methods from IronRuby.

Testing C# with Cucumber

This release of IronRuby runs the Cucumber testing framework rather well. Try out Cucumber against some C# code.

Given a feature file (this being the addition.feature)

A step_definition file (calculator_steps.rb)

And a DLL:

Cucumber will test the addition feature:

3 scenarios (3 passed)
12 steps (12 passed)
0m0.753s
Silverlight building and updated binaries

This release re-adds Silverlight binaries to IronRuby, contained in the "silverlight" directory of the release. These bits have been integrated from the AgDLR project, and will be maintained in the IronRuby and IronPython source code repositories from now on. The AgDLR GitHub project will redirect to one of those for binaries for both languages in Silverlight. In addition, the SDLSDK CodePlex site will be redirecting to the IronRuby and IronPython CodePlex sites, for downloads, discussion, and issue tracking. AgDLR was a little side project to add new features to DLR Silverlight applications, and play around with Git. I'm very happy to see it merged back in with the languages.

Note: IronPython Silverlight assemblies are included directly in the release. They may be moved out to the separate package that contains IronPython desktop DLLs in the future.

See the integration commit for more information

Another notable change is that you can now build Silverlight binaries out of IronRuby's GitHub repository very easily. Given that you have Silverlight installed at C:\Program Files\Microsoft Silverlight\2.0.40115.0, this will build IronRuby for Silverlight:

msbuild Merlin/Main/Languages/Ruby/Ruby.sln
  /p:Configuration="Silverlight Release
  /p:SilverlightPath="C:\Program Files\Microsoft Silverlight\2.0.40115.0

You can also build IronPython for Silverlight in a similar manner. Aliases for this will be added soon, but if you need a custom build of the DLR languages for Silverlight, this is the way to do it.

Samples

Six samples are included in this release. The first three are desktop samples in the “/samples” directory. The last three are Silverlight samples in the “/silverlight/samples” directory:

Tutorial - An interactive IronRuby tutorial
IronRuby example - Tutorial

DiskUse - A small WPF application which visualizes the disk usage for a particular directory
IronRuby example - Disk Usage

IRPowerShell - a small library and sample applications showing how to interact with PowerShell from IronRuby
IronRuby example - minsysreq

Clock – a simple Silverlight sample
IronRuby Silverlight example - Clock

Photoviewer – do AJAX programming with IronRuby (ARAX =P)
IronRuby Silverlight example - photoviewer

REPL – Interactive console in the browser.
IronRuby Silverlight example - REPL

Some more interesting changes:
  • Improved DLR Interop: adds support for GetMember/SetMember with method_missing, Binary/Unary operators, and indexers.
  • Handling of CLR protected and private methods and properties
  • Reimplemented File.expand_path such that it does not use System.IO.Path.
  • This allows us to get better compatibility with MRI. The motivating reason was
  • that RSpec does File.expand_path("filename:linenumber")
  • Improves the implementation of singleton method dispatch.
  • These changes improve running time of specs significantly (2x)
  • Renames Method, UnboundMethod#overloads (plural) to
  • Method, UnboundMethod#overload (singular).
  • The old name is still available for now and throws an exception.
  • Implements adaptively compiled rules
  • Improves performance of Array#- from quadratic algorithm to linear.
  • Improves implementation of RubyArray
Bugs closed

Here are all 37 bugs closed since the last release (2009-05-19). You can see more information about each one on CodePlex.

1521  Access is allowed to internal fields
1502  alias_method fails for :do
821   File.expand_path does not support a line number after filename
1509  Proc.to_s should include line number where the block was declared
1501  WinForms broken
1400  $? is not always Process::Status	
1345  load_assembly() should work
1344  System.Action.new does not work
1306  Cannot call CLR constructor of builtin type
1184  public(:foo) does not work correctly for mixed-in methods
1085  Cannot call new on subtypes of builtin classes whose "new" method has optional arguments
1060  visibility of send :define_method
917   Passing a Ruby array to a .NET method that expects an IEnumerable derivative fails with GetEnumerator call
783   Assert in SetMethodBasesNoLock when calling #== on Ruby class inheriting from CLR class which overrides Equals
761   Wrong behavior when calling redefined methods on object instances
1470  Can't call the BigIntegerOverload of a method with a DefaultProtocol Attribute on the BigInteger attribute
1426  The located assembly's manifest definition does not match the assembly reference. (ctp dev10 beta1)
1441  Error with cyrillyc text in Sharepoint	
1352  Test Defects	
814   Allocator underfined for  (TypeError)
572   Error when running Cucumber examples with IronRuby
718   IronRuby ignores RUBYLIB environment variable
727   to_proc not working
1351  redist-libs should have rubygems-1.3.1	
466   ''.split(//, -1) returns [""] instead of []	
940   Can't inherit from abstract classes	
1028  Missing conversion from Duration to Fixnum (ActiveSupport)?
374   irails Foo: undefined method for OpenSLL::Random.random_bytes
459   throw FileNotFoundException => rescue Errno.NoEntryError
499   Pathname#cleanpath messes up the pathname
467   "igem install rails" fails
375   "ir script\server" causes a YAML parser error
461   Generic type conversion from Fixnum to Integer
674   autoload does not use File::SEPARATOR
1021  Time class instance
578   yield fails in eval'd code
605   Array#hash should properly handle recursive arrays
Enjoy!

Please test out IronRuby 0.6 and let us know if you have any issues. We hope you enjoy this release!

-- The IronRuby team

by Jimmy Schementi (jschementi@gmail.com) at July 02, 2009 07:08 PM

The Voidspace Techie Blog

Open Source Licensing and Contributions

There have been discussions on the issues of licensing and accepting contributions to open source projects on the Python-dev and the testing in Python mailing lists. This is an area that can be very confusing, and potentially problematic for open source projects. ... [376 words]

July 02, 2009 03:59 PM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0: Removing URL Warts

The normal procedure for configuring NWSGI leaves an unsightly URL wart: the URL must contain the .wsgi file. There are two ways to get rid of that wart: URL rewriting and wildcards.

URL Rewriting

When using URL rewriting, the web server changes ("rewrites") the incoming URL into something NWSGI can understand. IIS 7 has a URL rewriting extension to do just that. It's quite easy to use, too:

<rewrite> 
    <rules> 
        <clear /> 
        <rule name="Redirect Warty Requests" stopProcessing="true"> 
            <match url="simple.wsgi/(.*)" /> 
            <conditions logicalGrouping="MatchAll" /> 
            <action type="Redirect" url="{R:1}" redirectType="Permanent" /> 
        </rule> 
        <rule name="Remove WSGI Wart"> 
            <match url="^(.*)$" /> 
            <conditions logicalGrouping="MatchAll" /> 
            <action type="Rewrite" url="simple.wsgi/{R:1}" appendQueryString="true" /> 
        </rule> 
    </rules> 
</rewrite>

Replace simple.wsgi with the name of the .wsgi file you would normally use. Now, http://example.com/simple/simple.wsgi/Products/Widgets can be accessed as http://example.com/simple/Products/Widgets. The first rule ("Redirect Warty Requests") will redirect any uses of http://example.com/simple/simple.wsgi/Products/Widgets to http://example.com/simple/Products/Widgets to ensure that only one set of URLs is used (which is important for search engines). However, most modern applications expect to have their URLs rewritten and can be configured to generate the "clean" URLs by default.

If you are using IIS 6, you'll need to use something like ISAPI_Rewrite to achieve the same effect. The following should have the same effect as the above rules:

RewriteEngine On
RewriteRule ^hello.wsgi/(.*) $1 [NC, R=301]
RewriteRule ^(.*)$ hello.wsgi/$1 [NC]

Wildcards

Normally, IIS dispatches requests by extension; this is why we have the .wsgi file in the first place. However, it can be configured to pass all requests to a specific handler by configuring a wildcard extension. Unlike URL rewriting, which is transparent to NWSGI, NWSGI needs to know that it has been configured as a wildcard handler. To do this, add a <wildcard> element to the configuration:

<wsgi>
    <wildcard physicalPath="C:\simple\simple.wsgi" callable="simple_app" />
</wsgi>

The physicalPath and callable attributes have the same meaning as on the <scriptMapping> element. If the configuration includes a <wildcard> element, any <scriptMapping> elements are ignored.

Ultimately, the effect is the same as URL rewriting: http://example.com/simple/simple.wsgi/Products/Widgets can be accessed as http://example.com/simple/Products/Widgets.

Which to Choose

If possible, you should prefer URL rewriting, as it should be faster than using wildcard mappings; however, it requires support from the application. If you're on IIS 6 or IIS 7 without a URL Rewrite extension installed, or your application doesn't support rewritten URLs, then wildcard mappings are available.


by jdhardy (jdhardy@gmail.com) at July 02, 2009 03:00 PM

July 01, 2009

The Voidspace Techie Blog

Exception handling and duck typing

Exceptions are one of the great features of high level languages that making coding less tedious. Instead of manually checking for possible errors and returning error codes we can use exceptions. ... [675 words]

July 01, 2009 05:50 PM

IronPython URLs

IronPython in Action Goes to College

Thanks to the wonder of Twitter I've heard about two different college courses that will be using IronPython in Action as course material next semester. One is Sargeant Reynolds College in America, with a course taught by Kevin Hazzard, and the other is Northtec in New Zealand with a course taught by Tony Meyer.

IronPython is an ideal language for learning programming, it has the great combination of an easy to learn general purpose programming language (Python) with a programming environment which is widely used in commercial development (the .NET framework). Not only these factors, but it is easy to teach good programming practise with Python; things like well structured code, testing, computer science theory including elements of functional programming and so on.

I exchanged emails with Tony who explained why he is using IronPython in Action:
The course is (unimaginatively) titled "Programming" (not my doing!). It's at NorthTec at the Whangarei campus (a couple of hours north of Auckland). It's the second programming course in their Bachelor of Applied Information Systems degree. We switched the first course from VB to Python a couple of years ago, but left this one as VB (because it's their introduction to Visual Studio and .NET).

Early last year I started work convincing people that IronPython would be a good choice, since they can continue with a language they (somewhat) know, but still get the intro to the Microsoft toolchain (plus, I hate VB, and dislike teaching in a language I never use in practice). I was expecting that I'd have to continue on without a textbook, until I saw that IronPython in Action was coming out.

BTW, while it's not like there is much choice in the way of books, yours is an excellent fit. The first section is a good Python refresher and .NET introduction. I introduce unit testing to them in the course, and the book handily has a chapter on that. They do a lot of sysadmin work later in their degree, so the chapter on using IronPython / PowerShell is great. They do ASP.NET stuff later on as well, so that'll be a good reference at that time (I don't expect I'll have time to cover that myself). I introduce them to databases and (since a couple of years ago) web services, and there's a chapter on that. Silverlight is an interesting example, and something I expect they'll be interested in given the later web development work, and there's an introduction to that.

Basically, you couldn't have done a lot better if I'd commissioned it! Thanks! - it certainly has made redoing the course material much simpler than if I was working completely from scratch.

As I mentioned in my tweet, I'll put my course material online at some point in the next couple of weeks (it's not quite finished) in case anyone else is interested in it.


by Michael Foord (noreply@blogger.com) at July 01, 2009 05:20 PM

June 30, 2009

ASP.NET for IronPython

T4MVC 2.2 update: Routing, Forms, DI container, fixes

To get the latest build of T4MVC: Go to download page   This post is a continuation of various recent posts, most notably: A new and improved ASP.NET MVC T4 template The MVC T4 template is now up on CodePlex First, I’d like to thank all those who are using the MVC T4 template and sent me suggestions and bug reports.  Most issues have been addressed, and most suggestions have been integrated.  I’m up to the 8th CodePlex drop, and it’s only been a week! You can see the history of changes at the top of the .tt file. Frankly, when I started playing with this, I just thought it’d be a fun thing to spend the afternoon on.  Instead, I have probably spent close to half my time working on it in the last week.  And I do have other...(read more)

by Angle Bracket Percent : ASP.NET at June 30, 2009 11:42 PM

Miguel de Icaza

MonoSpace Conference Announced

Scott Bellware has announced the MonoSpace Conference in Austin Texas on October 27-30th.

Scott has made a Call for Speakers:

The Monospace Conference is looking for teachers to give tutorials on the Mono framework, tools, languages, and platforms supported by Mono.

Some tutorials are aimed at .NET developers with little experience with operating systems other than Windows, and others are geared to experienced Mono developers with exposure to the various Mono platforms.

The tutorials are two hour to three hour interactive sessions that can be any combination of follow-along examples, labs, and lecture.

We're looking for tutorials on subjects such as Linux, Mac, Windows, web, desktop, servers, message queues, databases, iPhone, Android, Amazon's EC2, among others.

You can track the progress of the conference at the MonoSpace Conf Blog.

You can also follow the progress on twitter.

Scott was one of the founders of the Alt.Net series of conferences.

by Miguel de Icaza (miguel@gnome.org) at June 30, 2009 08:50 PM

Miguel de Icaza

Some Cool Mono Announcements

Yesterday we shipped Mono 2.4.2, our long-term supported version of Mono. It ships Microsoft's opensourced ASP.NET MVC stack for the first time (you could get it before on your own, but now it is integrated) and fixes over 150 reported bugs.

Chris Toshok announced M/Invoke a tool to port applications that use P/Invokes on Win32 to Linux and MacOS.

What Chris does not talk about on his post is that he was trying to use some .NET software that interfaces via USB to his glucose meter and was trying to get this to run on Linux. The tool is mostly .NET with the usual handful of P/Invokes to Win32. And this is how M/Invoke was born: a tool to retarget P/Invoke happy applications into becoming pure managed applications.

This opens new doors to forcefully port more apps to Linux.

Alan McGovern released a new version of Mono.Nat one of the libraries used by MonoTorrent.

Jordi Mas released a new version of Mistelix a DVD authoring tool for Linux:

Jordi's GBrainy brain teaser game was picked up by MoLinux, a regional Linux distribution, and shipped it translated to Spanish:

Joe Audette's mojoPortal was being installed four times as much when it got included in in Microsoft's Web Platform Installer site (more stats here).

For years I have loved the Joel on Software rules for software engineering. And one of those rules is "Build in one step". We have not always succeeded, but we have always tried. Lluis delivers the one step to build and run for MonoDevelop on Windows: Load solution, Hit F5, up and running.

Google Chrome really lead the way here, and I want very badly to have all of Mono building in Visual Studio with one keystroke, but we are not there yet.

Stephane reports on some nice startup performance improvements for F-Spot. Loading time for 10 images from Stephane's own image collection went from 1.2 seconds to .5 seconds.

MonoDevelop got some enhanced support for autoconf integration.

Jeremy Laval released another version of ZenComic a desktop Comic reader:

David Siegel announced a new release of Gnome Do on behalf of the Gnome Do team. In particular, it is now easier to write "Docklets" for the Gnome Do panel and for those of us that like the Emacs keybindings, it is now possible to use C-N and C-P for navigation

And of course the Google Summer of Code is in full swing:

And we have various very exciting projects brewing.

Jonathan Pobst has been exploring integration points for Mono and Visual Studio 2010:

Guadec: I will sadly not be attending the Guadec/Akademy conference in Canaria next week. This is going to be a busy summer for us as we are shipping a lot of code in the next few months: Moonlight 2.0, Mono for Visual Studio, MonoTouch 1.0 and Mono 2.6.

by Miguel de Icaza (miguel@gnome.org) at June 30, 2009 08:41 PM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0: Advanced Dispatching

Function Callables

Let’s say we’re dealing with a much larger Python application, coolapp, that is installed at C:\coolapp-1.1\. Unfortunately, coolapp doesn’t provide a ready-made .wsgi file for us, but it does provide a function(coolapp.dispatchers.wsgi_application) that we can use by writing a little wrapper that looks something like:

import sys
sys.path.append("C:\coolapp-1.1")
import coolapp.dispatchers.wsgi_application
application = coolapp.dispatchers.wsgi_application

We could save this as coolapp.wsgi and follow either of two methods from last time, but since we’re not doing anything fancy in the wrapper, NWSGI provides a shortcut:

<wsgi>
    <pythonPaths>
        <path path="C:\coolapp-1.1" />
    </pythonPaths>
    <scriptMappings>
        <scriptMapping scriptName="coolapp.wsgi" callable="coolapp.dispatchers.wsgi_application" />
    </scriptMappings>
</wsgi>

First, we add C:\coolapp-1.1 to Python’s path so that we can import it. Next, we tell it that any requests for coolapp.wsgi should be dispatched to the function coolapp.dispatchers.wsgi_application. This is completely equivalent to the wrapper file, but saves us from creating it. Visiting http://example.com/coolapp.wsgi/ will run coolapp.

Class Callables

Functions aren’t the only things in Python that are callable; classes are also callable (it creates an instance of the class). Let’s say we upgrade coolapp to version 2.0 (installed in C:\coolapp-2.0). The team has made some changes, and their WSGI application is now a class, WsgiApplication. This class has a __call__ method (making its instances callable as well!), so our WSGI application is an instance of the WsgiApplication class. We could use a coolapp.wsgi wrapper again:

import sys
sys.path.append("C:\coolapp-2.1")
import coolapp.dispatchers.WsgiApplication
application = coolapp.dispatchers.WsgiApplication()

Again, our little wrapper doesn’t do much, so NWSGI provides a shortcut:

<wsgi>
    <pythonPaths>
        <path path="C:\coolapp-2.0" />
    </pythonPaths>
    <scriptMappings>
        <scriptMapping scriptName="coolapp.wsgi" callable="coolapp.dispatchers.WsgiApplication()" />
    </scriptMappings>
</wsgi>

This time, NWSGI will create an instance of WsgiApplication, and then call the instance and return the result to IIS. This shortcut will only work if the class doesn’t require any arguments; if it does, it needs to be wrapped in a .wsgi file (when in doubt, you can always use a wrapper file). Again, visit http://example.com/coolapp.wsgi/ to run the application.

There’s actually one more case: Python classes that implement the iterator protocol, but I don’t think two many applications are implemented that, so I’ll skip it. PEP 333 gives an example if you’re really interested.


by jdhardy (jdhardy@gmail.com) at June 30, 2009 03:01 PM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0: Dispatching

NWSGI has a fairly simple task: given a URL, call some Python code that produces some output. The devil, as always, is in the details.

What is WSGI?

NWSGI is an implementation of the Python WSGI specification (PEP 333). WSGI is the Web Server Gateway Interface, “a simple and universal interface between web servers and web applications or frameworks”, as defined in PEP 333.

OK, so what does that mean?

The purpose of WSGI is to define how web servers (i.e. Apache, IIS, etc.) talk to Python web application or frameworks (i.e. Trac, Django, etc.). In theory, a web server with a WSGI implementation (such as mod_wsgi for Apache, or NWSGI for IIS) should be able to run any web application that is implemented as a WSGI application (prior to WSGI, many applications/frameworks were server-specific). Of course, that doesn’t always pan out in practice, but it’s a start.

What is a WSGI application?

A WSGI application is surprisingly simple:

def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return ['Hello world!\n']

The simple_app function is the entire application! A WSGI application is a callable (a function, mostly) that takes two arguments and returns an iterable (a list or generator, mostly). There’s some extra goo in there as well (start_response, for example) that’s not really relevant as far as dispatching is concerned. Writing WSGI applications is probably a book’s worth of content, so I’ll leave it at that for now.

Finding Callables in .wsgi Files

Local Files

Now that we have a callable for our application, NWSGI needs to know how to find it. The simplest way is to simply drop the file (let’s call it simple.wsgi) into the application root (i.e. C:\inetpub\wwwroot\, next to web.config). If you make a request to http://example.com/simple.wsgi/, IIS will see that .wsgi is associated with NWSGI and pass the request to it. NWSGI will then open simple.wsgi, try to find a variable called application (which is, by convention, the name of WSGI callables), call it, and return the result to IIS.

In this case, however, our callable is named simple_app, not application. To be able to run our app, NWSGI needs to know this! To do this, there needs to be a script mapping telling NWSGI how to run simple.wsgi.

<wsgi>
    <scriptMappings>
        <scriptMapping scriptName="simple.wsgi" callable="simple_app" />
    </scriptMappings>
</wsgi>

This configuration tells NWSGI that for the script simple.wsgi, it should use simple_app as the callable instead of application. (NOTE: This exact syntax requires 2.0b2 or later).

Other Files

Best practices for WSGI applications say that you should not put your application files in the web-exposed directory. This means that simple.wsgi should really live somewhere else; let’s say C:\simple\simple.wsgi. Of course, now NWSGI doesn’t have the slightest clue where it is, so we have to tell it:

<wsgi>
    <scriptMappings>
        <scriptMapping scriptName="simple.wsgi" physicalPath="C:\simple\simple.wsgi" callable="simple_app" />
    </scriptMappings>
</wsgi>

There is no longer a .wsgi in our application folder, but IIS doesn’t care. If you visit http://example.com/simple.wsgi/ with this configuration, IIS still happily passes the simple.wsgi script onto NWSGI. NWSGI looks at the script mappings and finds that simple.wsgi maps to C:\simple\simple.wsgi, so it loads that file instead (without looking for simple.wsgi in the application directory), looks up simple_app, and calls it.

Using .wsgi files is the simplest way to deploy an application, but NWSGI has a couple of shortcuts to make things easier for certain applications.


by jdhardy (jdhardy@gmail.com) at June 30, 2009 03:00 AM

June 29, 2009

Miguel de Icaza

Jimmy Schementi

Simple Python testing in Silverlight with unittest

Since doing a post about Ruby testing of Silverlight applications, I’ve felt a bit guilty about leaving Python fans in the dark. However, like Ruby, it takes very little work to run Python unit test frameworks in Silverlight, since IronPython is a very compatible implementation of Python. Though my results aren’t as exhaustive as the IronRuby examples, here’s one simple example:

http://github.com/jschementi/europycon2009

zip download

unittest-sl

The original example is from the Python website’s unittest documentation. Very little bootstrapping is required to get this running in Silverlight; this is u1.py code that is the start-script for the Silverlight app, which runs the tests:

I did have to make a modification to unittest.py; removing a call to sys.exit since Silverlight doesn’t support that, and just returning the exit code.

There’s also a GUI test runner (http://pyunit.sourceforge.net/pyunit.html#GUI), so it might be interesting to port that to Silverlight to get a nicer test run graphic along with the console, but it’s great that the REPL enables this to just work =) It also helped me find some bugs with the REPL, which will make their way to the IronPython source code shortly.

Let me know how it works for you. The next step is to tackle testing Silverlight C#/VB apps with Python.

Technorati Tags: ,

by Jimmy Schementi (jschementi@gmail.com) at June 29, 2009 07:55 AM

June 27, 2009

Jeff Hardy's Blog (NWSGI)

Solving the Zlib Problem – IronPython.Zlib

IronPython 2.0 does not include an implementation of the zlib module, which handles data compression. In CPython the zlib module is a C module, which it can't be used from IronPython. It is also required by several standard Python modules, include tarfile, gzip, and zipfile, all of which handle compressed archives. Thus, for setuptools - particularly, easy_install and zipimport (Eggs) - to work, there must be a fully working zlib module.

FePy includes a partial implementation built on .NET's DeflateStream, but it is missing support for the decompressobj API that is used by gzip and zipfile. Supporting this API using DeflateStream appears to be impossible, as it expects a few implementation details of the zlib implementation.

That left two options for implementing zlib: P/Invoke, and ComponentAce's zlib.net. P/Invoke had a couple of issues: first, native-managed interop is hard; second, handling 32-bit and 64-bit systems seamlessly adds a lot of extra code (I use Vista x64, so I ran into this almost immediately). Zlib.net is an open source (BSD-style license), pure .NET implementation of zlib; this avoids both native-managed interop and 32/64-bit issues. It has an interface nearly identical to zlib, which means that it could be used to mimic the Python C library, which is exactly what I've done.

IronPython.Zlib is an implementation of the zlib module for IronPython using zlib.net. Both binary and source are available under the MS-PL license. To use it create a "DLLs" directory under your IronPython implementation and drop IronPython.Zlib.dll into it.

It passes most of the Python zlib tests and all of the gzip tests. There are a few issues with the CRC-32 implementation that the tests didn't catch but real-world usage did, but I haven't figured out how to fix them yet.

There are still some issues with setuptools (the zipfile module uses binascii.crc32, which is not yet implemented) that I'll detail in a later post, but it almost works.

Update June 27, 2009: Uploaded a new version that fixes crc32 bugs by forwarding to the now-implemented but 2.6-only binascii.crc32.


by jdhardy (jdhardy@gmail.com) at June 27, 2009 06:30 PM

IronPython URLs

The IronRuby Tutorial

Jimmy Schementi, program manager for the dynamic languages and Silverlight integration plus IronRuby developer, has pushed a new update to the IronRuby github repository.

One of the major changes is improvements to the IronRuby tutorial app.
As you can see from the screenshot this is a WPF (Windows Presentation Foundation - which means it won't run on Mono) application which combines a tutorial with an integrated interpreter (REPL) for actually trying out the code:
Isn’t he/she/it a bute!? This app makes Ruby-based tutorials interactive, guiding you through the material with a IronRuby REPL console and other visual aids such as another window, or whatever the tutorial writer sees fit. There is also a tutorial runner for the command-line, and a exporter for static HTML.

The IronRuby tutorial included covers topics such as using the interactive window, built-in libraries, exploring .NET libraries, generics, events, Windows Forms, and Windows Presentation Foundation.
I'm highly envious of this for IronPython and it was always my intention to turn TryPython into something similar, but using Silverlight. With Silverlight 3 / Moonlight it could run in the browser or out of it. Who knows, I may still do it...


by Michael Foord (noreply@blogger.com) at June 27, 2009 01:52 PM

IronPython URLs

OS Jam at Google London: C# 4 and the DLR

Jon Skeet, author of the well regarded C# in depth, did a five minute talk on C# 4.0 and the Dynamic Language Runtime at a recent Google Open Source Jam in London. The 'innovative' slides are online, and they touch on details like the dynamic keyword, binders and IDynamicMetaObjectProvider.
The fundamental point of the DLR is to handle call sites - decide what to do dynamically with little bits of code. Oh, and do it quickly. That's what the caches are for. They're really clever - particularly the L0 cache which compiles rules (about the context in which a particular decision is valid) into IL via dynamic methods. Awesome stuff.
I'm sure the DLR does many other snazzy things, but this feels like it's the core part of it.

At execution time, the relevant binder is used to work out what a call site should actually do. Unless, that is, the call has a target which implements the shadowy IDynamicMetaObjectProvider interface (winner of "biggest mouthful of a type name" prize, 2009) - in which case, the object is asked to handle the call. Who knows what it will do?


by Michael Foord (noreply@blogger.com) at June 27, 2009 01:42 PM

June 26, 2009

IronPython URLs

New JavaScript Implementation for the DLR

The Dynamic Language Runtime was announced at the same time as Silverlight. Along with IronPython and IronRuby a third, Silverlight only, language was announced that ran on the DLR.

This language was Managed JScript, an ECMA compliant version of Javascript that was touted as an easy way to port AJAX applications to run on Silverlight.

Unfortunately as IronPython and the DLR developed Managed JScript stagnated. It was only ever released as binaries and hasn't been kept up to date with recent versions of the DLR. Someone called it the Bastard, red-headed step-child in the DLR.

However, there is now an alternative implementation of JavaScript for the DLR:
RemObjects Script for .NET is an embeddable engine for .NET applications that allows developers to let their users introduce written scripts that influence the behavior of the application.

The RemObjects Script engine is built in a language-agnostic way, so that different concrete language implementations can be created on top. It currently supports most of ECMAScript 262 version 1.5 (also known as JavaScript). There are also plans to support Pascal Script.

It's based on the Microsoft DLR runtime for simplicity and ease of inter-operability with other dynamic languages and .NET 4.0 languages with support for dynamic operations, but can be run on any version of .NET 2.0 or later, as well as Mono.

Currently supported features:
  • Objects
  • Prototypes
  • Functions
  • Arrays
  • Booleans
  • Regular Expressions
  • Numbers
  • Build-in classes: Object, String, Function, Array, Number, RegExp, Date, Boolean
  • Interopability with non-ECMAScript types
  • Interopability with other DLR-based language types
ECMAScript is a dynamic language and is weakly typed. It uses a prototype based object model (no classes). It is a flexible language that due to its lack of types is ideal for scripting purposes. EMCAScript has a very simple model for object oriented programming, where objects are property bags with a "prototype" model to allow for a way of inheritance. It supports closures (nested functions) and every function is an object on it's own.

Note: RemObjects Script is in early development stages, and currently only available from its SVN source control repository at code.remobjects.com. It is implemented using Delphi Prism and the Oxygene language.


by Michael Foord (noreply@blogger.com) at June 26, 2009 08:24 PM

IronPython URLs

Twisted on IronPython

One of the big new features coming in IronPython 2.6 is optional support for Python stack frames (with a ~10% performance hit tracking the frames if it is enabled).

With this in place Seo Sanghyeon, maintainer of FePy the community distribution of IronPython, has been looking at getting Twisted working with IronPython. Twisted is an open source event-driven networking engine written in Python.

Seo posted this email to the IronPython mailing list:
I have started porting Twisted to IronPython.

Progress is to be tracked on this Trac ticket.

There is a Buildbot running the Twisted tests with IronPython.

Just in case you don't know, Twisted is an event-driven networking engine written in Python licensed under MIT license, which aims to destroy the American currency system. See following links for more details.
Having frame support in IronPython opens up the possibility for Python debugging APIs, like sys.settrace, being implemented in IronPython.

A recent checkin to the public source code repository had this in the commit message from Dino Veihland:
Adds the in-proc debugging support that Igor as been working on. This adds a new DLL to the IronPython MSI and to the IronPython and DLR CodePlex releases.

This is just adding their source code and updating our build and packaging infrastructure to include their new DLL. The only changes to their code were some #ifdef’s to support Silverlight builds and some updates to the .csproj files to support our numerous builds. This code is owned by them and has been reviewed by their team so I’m not looking for a code review for the new DLL.

Once this is in I’ll be updating Igor’s prototype for sys.settrace support for IronPython and adding that.
Cool...


by Michael Foord (noreply@blogger.com) at June 26, 2009 06:25 PM

tech-michael

Keep an eye on a reference.

When debugging I often find myself wishing I could just watch a single object throughout its life cycle. This is especially useful for debugging state problems (I’m thinking detached row error). Someone is modifying the state of your object and you need to figure out who. The problem lies in scoping. Every time you step in you have to change the watch window statement to track your objects state.

What you end up with is a nasty watch window.

The immediate window comes to the rescue!  Simply declare a variable with a globally unique name (DataRow watchMyRow=_dr;) for example. Then go to the watch window and add a watch for watchMyRow.  watchMyRow is always in scope. So now step through at your leisure and find the offending entry point and step deeper. Its that easy!

 

So we will start with a simple test program that calls methods with several different names and types.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MyObject val = new MyObject();
Method1(val);
Method2(val);
Method3(val);
}

static void Method1(MyObject obj)
{
obj.state = 1;
}

static void Method2(MyObject myobj)
{
myobj.state = 2;
}

static void Method3(object obj)
{
((MyObject)obj).state = 3;
}
}

public class MyObject
{
public int state = 5;
}
}


We set our break points.



image



And at the end of the cycle our watch window looks like this! 



image 



All to track the same value on the same object!



 



The real problem is that with events thrown into the mix it becomes impossible to track state on some foreign object (Detached Row I loathe you!).



Now lets do the same example with the immediate window.



Our first break point gets hit. We type MyObject WATCHMYOBJECT=obj; into the immediate window.



image



Next I add that variable to the watch window.



image



Finnally after the many function calls this is the result.



image



 



I only had to watch one object the entire time! Now if I can only build a VSADDIN to automate this process (evil grin)!

by Michael (noreply@blogger.com) at June 26, 2009 05:38 PM

ASP.NET for IronPython

The MVC T4 template is now up on CodePlex, and it does change your code a bit

Short version : the MVC T4 template (now named T4MVC) is now available on CodePlex, as one of the downloads in the ASP.NET MVC v1.0 Source page .   Poll verdict: it’s ok for T4MVC to make small changes Yesterday, I posted asking how people felt about having the template modify their code in small ways.  Thanks to all those who commented!  The fact that Scott Hanselman blogged it certainly helped get traffic there :) The majority of people thought that it was fine as long as It’s just those small changes: make classes partial and action methods virtual. Don’t mess with ‘real’ code! It asks for permission, or at least tells you what it’s doing I started looking for a way to pop up a Yes/No dialog, but ended up going with a slightly...(read more)

by Angle Bracket Percent : ASP.NET at June 26, 2009 05:23 PM

Dave Fugate (Testing IronPython)

And now for something completely different

I believe I'm not really allowed to comment on the European Commission complaining that Microsoft is unbundling Internet Explorer from Windows 7 in the EU, so I'll comment on something else entirely...  It goes without saying that the opinions expressed here are entirely my own.

Seeing as Toyota is now the world leader in automobile sales, I'd like to see the US Federal Trade Commission file an anti-trust suit against them for the unfair bundling of GPS units in their cars.  You see...due to these GPS's being physically attached to the interior of the vehicle I'm hurt as a consumer because:
  • I can't install a portable unit from a different GPS manufacturer inside the vehicle.  Err...now that I think about it the portable units install on the windshield or the dash and get powered by cigarette lighter outlets so this is not actually an issue
  • The vehicle doesn't come with a map of local electronics stores where I could buy my own portable GPS unit.  Oh...now that I think about it I Toyota's built-in GPS unit will actually HELP me to find these stores selling competing GPS units.  Darn again
  • My car insurance won't cover the theft of Toyota's GPS unit because it's physically attached to the vehicle.  No, wait...that's not right either.  It's the other way around which actually provides a huge benefit to me
  • Ten years ago no cars came with GPS units pre-installed on them and I don't want to pay whatever extra money Toyota is adding to the base vehicle price to cover this GPS.  On that note, I don't want to pay for the heater or useless things like seat belts and parking brakes either
Hopefully you realize the absurdities above are intended as pure sarcasm.  My wife and I love the Toyota Rav4 we bought a couple years ago and WISH they bundled all Rav4s with GPS units.  Maybe if they did our car wouldn't have been broken into for the portable unit last year.

June 26, 2009 04:10 PM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0: Configuration Details

For the most part, NWSGI can be used without any configuration. All you have to do is create a .wsgi file, throw it in a directory, let IIS know what’s going on, and you’re good to go! Of course, if it was always that easy, configuration wouldn’t exist. To really work with NWSGI, you need to understand its configuration. It helps if you’re already familiar with web.config files; if not, check this out (but hurry back!).

First Things First

NWSGI uses .NET’s built-in configuration system (System.Configuration), so the first thing that needs to be done is to let the .NET Framework know about the custom NWSGI configuration section:

<configSections>
    <section name="wsgi" type="NWSGI.WsgiSection" />
</configSections>

This must be the first entry in web.config, directly under the <configuration> element.

The <wsgi> element

All of the configuration options for NWSGI are under the <wsgi> element. The first ones we will look at are specified as attributes of the <wsgi> element: enableExtensions, adaptiveCompilation and frames.

enableExtensions
Enable extensions to NWSGI. Relying on these will make your application nonportable to other WSGI implementations. Required to use ASP.NET's built-in Session support, for example. Choices: true, false.
compilation
Control how IronPython compiles code. Choices: Adaptive, Compiled.
frames
Control sys._getframe. Enabling sys._getframe causes a performance hit. Choices: Off, On, Full.

Example:

<wsgi adaptiveCompilation="false" frames="Full" />

Adding Python Search Paths

If your application needs to access Python modules that are not in the default NWSGI search paths (~/, ~/Bin/ and ~/Bin/Lib/), you can use the <pythonPaths> element to add them. The <pythonPaths> element contains a set of <path> elements that are added (in order) to sys.path before the application is run. The <path> element has one required attribute – path – that contains the full path to a folder on disk containing the modules you want to use.

Example:

<wsgi>
    <pythonPaths>
        <path path="C:\django" />
    </pythonPaths>
</wsgi>

Adding WSGI Environment Variables

Most applications will require some configuration of their own; these options are passed in the environ parameter of the WSGI application. You can add entries to this list by using the <wsgiEnviron> element, which contains a set of <variable> elements. Each <variable> element has two required attributes, name and value.

Example:

<wsgi>
    <wsgiEnviron>
        <variable name="trac.env_path" value="C:\trac\projects" />
    </wsgiEnviron>
</wsgi>

Advanced Script Usage

There are cases where you may need to configure how NWSGI handles a particular script file. In these cases you need a virtual script mapping; NWSGI will always check script mappings before looking for a file on disk. Not surprisingly, these are stored in the <scriptMappings> element, which contains a set of <scriptMapping> elements. There are three parts to a script mapping:

scriptNamerequired
The name of the virtual script; overrides any scripts on disk.
physicalPath
The path to the actual file to execute. This can be a full path (i.e. C:\myapp\myapp.wsgi) or an app-relative path (i.e. ~/scripts/myapp.wsgi).
callable
If physicalPath is set, the name of the callable object in that file; if it is not set, an entry point for the application.

Entry points are used to specify a particular function in a Python module on sys.path (see the <pythonPaths> element above for how to control sys.path). For example, for Django the entry point would be "django.core.handlers.wsgi.WSGIHandler()". This mimics the standard Python syntax for creating an object; it is this object that is used as the application. If, instead, the application provides a function (like trac), the entry point would be "trac.web.main.dispatch_request".

Example:

<scriptMappings>
    <scriptMapping scriptName="myapp.wsgi" physicalPath="C:\myapp\myapp.wsgi" callable="myapp" />
</scriptMappings>

Wildcard Settings

When IIS is configured in wildcard mode, all requests for an application are passed to NWSGI, instead of only requests for .wsgi files. You can enable this by setting path="*" in the handler/httpHandler definition. Because NWSGI normally expects there to be a .wsgi file in the URL, but in wildcard mode there isn't one, the <wildcard> element is required to tell NWSGI what script to execute. The available settings – physicalPath and callable – have the same meaning as the same settings for script mappings (above). If the <wildcard> element is present, the <scriptMappings> element is ignored.

Example:

<wildcard physicalPath="C:\HelloWorld\hello.wsgi" callable="hello" />

Conclusion

NWSGI is extremely configurable; in many cases, you don't even need a .wsgi file. That said, the configuration can be complex, so please ask if you run into any problems. A later post will go into more detail on the mechanics of callables.


by jdhardy (jdhardy@gmail.com) at June 26, 2009 03:00 PM

June 25, 2009

IronPython URLs

NWSGI: New release and big improvements

NWSGI is "a .NET implementation of the Python WSGI specification for IronPython. It is implemented as an ASP.NET HttpHandler for use with IIS 6 and 7" created by Jeff Hardy. The goal is to be able to run Python applications like Django, Trac and Pylons on IronPython. It can also be used on the Microsoft Azure (cloud computing) platform.

Jeff Hardy has just released a beta of version 2.0, and explained the new features:
This is a major update to NWSGI that makes it easier to install and use and dramatically improves the management story.

So, what happened to 1.1? Originally, NWSGI 1.1 was going to be a refresh of v1.0 that supported IronPython 2.6 and fixed a few bugs. NWSGI 2.0 was going to completely overhaul large parts of the management UI and make some deeper changes to the handler itself. However, I got a week off with some rain and v2.0 progressed much quicker than expected; v1.1 was obsolete before it was even released.

So, v1.1 was dropped and v2.0 will be the first IronPython 2.6-compatible release. It’s easy to make breaking changes when you have no customers.

What’s New
  • Easier configuration. In v1.0 there were different ways to configure NWSGI depending on your configuration. Now there is only one way to do it. Some of the more ambiguous options have also been cleaned up, and new ones added to support IronPython 2.6.
  • Better management UI. IIS 7 includes a rich UI framework for developing management extensions, but doesn’t have much documentation on it. Some spelunking with reflector showed me better ways to do pretty much everything; not much of the v1.0 management code is left.
  • Performance improvements. NWSGI will now cache the WSGI callable instead of reloading it each time.
  • Other misc. fixes. I really need to get into the habit of adding a Codeplex issue for each bug so that I can keep track of what I’ve fixed.
Jeff has also made two separate blog entries explaining the major changes.
There are two ways to use NWSGI: by installing it or by using xcopy deployment. Each method has its advantages and disadvantages, but their functionality is the same.
One of the two areas to see the most changes in NWSGI 2.0 was its configuration. Some of the options in v1.0 were overloaded in strange ways; even I wasn’t entirely sure what some combinations would produce. There was also the small problem of where to put the configuration section; it varied depending on how NWSGI was installed. For v2.0, both problems needed to be fixed. Doing so required a re-think of how configuration was handled.


by Michael Foord (noreply@blogger.com) at June 25, 2009 02:11 PM

IronPython URLs

Choosing a DLR language: IronPython or IronRuby?

.NET developers interested in dynamic languages but still wanting to stay within the .NET ecosystem have an interesting choice - IronPython or IronRuby?

Simon Segal, who has been adding scripting support to his Entity Framework profiler, has been pondering this question:
For my part so far I have delved into IronRuby and started to employ it for scripting my C# applications. Why did I choose IronRuby over IronPython? It began with curiosity in the Ruby language in general and led inevitably to IronRuby. I quickly acquired a taste for Ruby but there is something nagging in the back of my mind and I can’t get to the bottom of it - “did I choose the right language” and really after all “does it matter which one I choose?”

Given Pythons relationship to C and my emotional connection to the C family of languages, would IronPython have been a better choice? Certainly IronPython is further down the track and more mature than IronRuby at this stage, but what does that count for at this early stage? All these questions make me curious for some other opinions which I would leave to hear right here, so please tell me – what do you think? What criteria would you use to make a choice?
Shortly after he chose IronPython over IronRuby:
After having spent a less than insignificant amount of time invested in IronRuby I decided to bite the bullet and invest the effort into IronPython instead and the reasons were entirely pragmatic. Microsoft seem to be putting more effort into IronPython, has already found it’s way into other stacks, such as Oslo’s Intellipad (which I plan to leverage) and it’s significantly more mature than IronRuby.

I am constantly finding uses for IronPython in my work and the list of problems that it’s going to help solve is growing quickly. As a side note, if you are looking to use IronPython and are ready to let the experience pass you by because of lack of IDE support then check out using NetBeans (for Python) and instead using IronPython.
Prior to writing these blog entries Simon contacted me by email and asked me what I thought.
I have been investing some time of late with IronRuby and have started several projects that incorporated scripting into applications written in C# and also have begun a project for a Entity Framework profiler that allows for scripting of my Repositories.

My question is regarding what I feel is a choice right now between IronPython and IronRuby. I am increasingly feeling a bit anxious that IR is slowing me down because of the projects maturity as compared to IP and I am also getting the impression that IP is somewhat preferred within Microsoft itself? I have no experience with Python but feel that if my chosen dynamic language in the .NET space needs to change it should be sooner and not later. I am not looking for a lengthy bullet point IR vs. IP evaluation, just a short high level opinion as to whether my concerns or any others should be heeded. If IP is the way to go I think I know of a good book!

My thoughtfully considered and entirely unbiased response...
I'm sure you don't expect an unbiased opinion from me, so I assume you have already made your decision and just need me to push you over the edge. ;-)

Actually IronRuby is approaching a 1.0 release soon, so it sounds like it is improving as regards maturity.

Despite this IronPython is more mature as regards .NET interop, performance and bugs. Version 2.6 will be a particularly good release (lots of work on performance) including features like __clrtype__ allowing the use of .NET attributes that I think will take a while before they show up in IronRuby.

Personally I think there are lots of reasons to prefer IronPython over IronRuby:

The Python object model is much closer to C# than Ruby. This means that it performs better and there are less issues around .NET interop - plus it is easier to learn for C# developers.

Python in general is a 'cleaner' language (a purely aesthetic judgement) with clearer namespacing, less use of sigils and no syntactic dependence on the casing of class / variable names. Although Ruby has anonymous blocks they are highly special cased in the language leading to various anomalies in the way they are handled. It is still annoying that Python can't have statements in its lambda functions but there is no clear way to add them to the language (due to using indentation for block structure which despite this disadvantage is still a stroke of genius).

Because Python is more widely used (still - despite all the publicity that Ruby has had through Rails in the last two years or so) there is wider community and more open source libraries available.

Having said all that, both Python and Ruby are great dynamic languages in which it is easy to be productive. They have different facilities for metaprogramming but as far as I can tell they are both equally powerful. Either choice would be a good one but naturally I think Python is the better choice...


by Michael Foord (noreply@blogger.com) at June 25, 2009 01:56 PM

ASP.NET for IronPython

Mind if my MVC T4 template changes your code a bit?

When working on my MVC T4 template , I was not able to use reflection to discover the Controllers and Actions, because the code that the template generates is itself in the same assembly as the controllers.  So that causes a bit of a chicken and egg problem. Instead, I had to get out of my element and learn something I was not familiar with: the Visual Studio File Code Model API.  It’s very different from using reflection, because instead of working at the assembly level, you work at the source file level. You have to first locate the source file you want to look into.  You can then ask for the namespaces that it contains, and the classes that they contain, and finally the various members in those classes.  To be honest,...(read more)

by Angle Bracket Percent : ASP.NET at June 25, 2009 06:45 AM

Aaron Marten's WebLog

Visual Studio 2010 User Interface Guidelines

One of the things you may notice is missing from the Visual Studio 2010 Beta 1 SDK (compared to 2008) are the user interface guidelines.

You can now find the Visual Studio 2010 User Interface Guidelines at the following location: http://code.msdn.microsoft.com/VS2010UX

by aaronmar at June 25, 2009 04:01 AM

June 24, 2009

The Voidspace Techie Blog

Movable IDLE for Python 2.5 on Windows

Movable IDLE is a standalone version of the IDLE Python IDE. Movable IDLE is part of the Movable Python project and can be run (Windows only I'm afraid) from a USB memory stick and without installing Python. ... [114 words]

June 24, 2009 08:38 PM

IronPython URLs

IronPython Performance: On Mono, on x64 and compared to C#

Everyone loves benchmarks, even though they are usually misleading at best. Of course I'm no exception. Here are three snippets of news on IronPython performance that have surfaced over the last week or so.

IronPython 2.0.1 and 2.6 Beta 1 compared to CPython and Jython (posted to Twitpic by felipez) on Mono revision 136556:


Using the pystones benchmark IronPython on Mono clocks in faster than CPython or Jython. Nice.

One particular bugbear of IronPython performance has been startup time. On 64bit Windows the startup time goes from being merely bad to positively ridiculous. This is because the .NET 64bit JIT is slow to do its job and IronPython generates a lot of code needing to be JITed at startup. A lot of work has gone into IronPython 2.6 to improve startup time (by reducing the amount of rule generation done on startup), and this blog entry Dave Fugate explains something they have done specifically to address startup perf on 64bit Windows - and shows off the results:
Allow me to elaborate on this perf gain...Dino made a change recently such that ipy.exe is now strictly a 32-bit only assembly. That is, it gets executed as a 32-bit CLR process on both x86 and x64 operating systems. ipy64.exe, despite what its name might imply, is a platform agnostic assembly matching the old behavior of ipy.exe in the sense that it gets executed as a 32-bit process on 32-bit OSes and 64-bit on 64-bit OSes. At least part of the perf gain here comes from the fact that my simple Hello World program is most definitely not consuming anywhere near 4 gigs of memory, and overall memory consumption goes up for 64-bit processes => remember the size of pointers gets doubled. Just checked and the physical memory working set of ipy.exe was 31K compared to 44K under ipy64.exe for the Hello World program. This ~30% difference in memory consumption helps explain why we get better perf under ipy.exe.
The next blog entry is in Chinese and compares performance of a few operations in IronPython and C#. As you might expect C# is faster in general, but interestingly IronPython is actually faster than C# for reflection.


by Michael Foord (noreply@blogger.com) at June 24, 2009 06:08 PM

IronPython URLs

Python Support in Visual Studio

Many .NET developers (all too many alas) are not willing (or not allowed) to use any language that isn't integrated into Visual Studio. As IronPython is a dynamically typed language it is much harder to build full support into Visual Studio - although there have been two attempts so far (the SDK for Visual Studio 2005 and IronPython Studio for Visual Studio 2008).

In this blog entry Dave Fugate (IronPython tester and infrastructure guy for Microsoft) explains the current state of VS support for Python and as Visual Studio 2010 approaches he looks to the future...
I think I speak for everyone on the IronPython Team when I say we’d love to see IronPython support in Visual Studio by default without the need for any language service addition. The thing is these types of decisions are made at a much higher level than us and are heavily influenced by business needs. What I’m getting at here is if enough people provided feedback via the proper channels that:
  • The next version of VS is great, but it’d be better if it supported Python development
  • You don’t currently use VS but you would if it had Python support
  • Ahem…you’d be willing to pay for IronPython support in VS
  • Etc
then the next version of VS could very well have Python support built into it. What are the proper channels for feedback you ask? The VS 2010 feedback page would be a great start.
If you're looking for an IDE for working with IronPython the best option currently is probably SharpDevelop, which has great IronPython integration.


by Michael Foord (noreply@blogger.com) at June 24, 2009 05:35 PM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0: Configuration Changes

One of the two areas to see the most changes in NWSGI 2.0 was its configuration. Some of the options in v1.0 were overloaded in strange ways; even I wasn’t entirely sure what some combinations would produce. There was also the small problem of where to put the configuration section; it varied depending on how NWSGI was installed. For v2.0, both problems needed to be fixed. Doing so required a re-think of how configuration was handled.

Configuring Wildcards

In v1.0, configuring NWSGI to operate in wildcard mode required setting options that were designed for other things in particular ways that made no sense. In v2.0, there is a special <wildcard> element under <wsgi> (replacing the wildcardModule option) that is specifically used for configuring these settings. If the <wildcard> element exists, then NWSGI will ignore the <scriptMappings> element.

The callable option has also been removed from the <wsgi> element as it is no longer necessary (it defaults to “application”). To specify a custom callable name for a script, create a <scriptMapping>.

Where to put it?

The first problem was to put the <wsgi> section in the same place all the time. In v1.0 it could be directly under <configuration> (if you were using xcopy deployment) or under <system.webServer> (if you installed it on IIS7). The two could not necessarily coexist in the same web.config file, either! IIS 7 uses a different configuration assembly (Microsoft.Web.Administration) than ASP.NET (System.Configuration), and they’re no compatible, to boot.

The fix is relatively simple: rather than trying to use the appropriate configuration system from the handler, v2.0 always uses System.Configuration. This means that the <wsgi> section is always directly under <configuration>. The only downside is that the section always has to be declared at the top of web.config:

<configSections>
    <section name="wsgi" type="NWSGI.WsgiSection, NWSGI, Version=1.99.1.0, Culture=neutral, PublicKeyToken=41e64ddc1bf1fc86" />
</configSections>

New Options

There are also two new options: compilation and frames. The compilation option controls how IronPython generates code. The frames option is used to control sys._getframe; as tracking frames incurs a performance hit, it must be explicitly enabled.

Wrapping Up

The changes to configuration (which will break any existing configurations) are the main reason for bumping the version to 2.0. The clean up of the options resulted in much cleaner implementations for the management and especially for the handler itself. As always, if you have any comments, let me know.


by jdhardy (jdhardy@gmail.com) at June 24, 2009 03:00 PM

June 23, 2009

Dave Fugate (Testing IronPython)

IronPython 2.6 Startup Time Now 34% Faster Under x64

DISCLAIMER
The performance numbers called out below were obtained using Ngen'ed IronPython/DLR assemblies with CPython's stdlib in sys.path.  It goes without saying that your (performance) mileage will vary greatly depending on your machine setup.

PS C:\SnapTempi> type hw.py
print "Hello World"

PS C:\SnapTemp> (measure-command {&"C:\Program Files (x86)\IronPython 2.6\ipy.exe" hw.py}).TotalSeconds
1.1590107

PS C:\SnapTemp\> (measure-command {&"C:\Program Files (x86)\IronPython 2.6\ipy64.exe" hw.py}).TotalSeconds
1.7733379
Allow me to elaborate on this perf gain...Dino made a change recently such that ipy.exe is now strictly a 32-bit only assembly.  That is, it gets executed as a 32-bit CLR process on both x86 and x64 operating systems.  ipy64.exe, despite what its name might imply, is a platform agnostic assembly matching the old behavior of ipy.exe in the sense that it gets executed as a 32-bit process on 32-bit OSes and 64-bit on 64-bit OSes.  At least part of the perf gain here comes from the fact that my simple Hello World program is most definitely not consuming anywhere near 4 gigs of memory, and overall memory consumption goes up for 64-bit processes => remember the size of pointers gets doubled.  Just checked and the physical memory working set of ipy.exe was 31K compared to 44K under ipy64.exe for the Hello World program.  This ~30% difference in memory consumption helps explain why we get better perf under ipy.exe.

June 23, 2009 07:43 PM

Jimmy Schementi

“The” IronRuby Tutorial

Hidden in yesterday’s commit to IronRuby’s GitHub repository is evidence of some polishing changes to the IronRuby tutorial app, which I’d like to introduce to you peoples:

ironruby-tutorial

To run yourself:

  1. Get IronRuby from GitHub and build it (in release mode preferably)
  2. cd Merlin/Main/Languages/Ruby/Samples/Tutorial
  3. ir.exe wpf_tutorial.rb

Isn’t he/she/it a bute!? This app makes Ruby-based tutorials interactive, guiding you through the material with a IronRuby REPL console and other visual aids such as another window, or whatever the tutorial writer sees fit. There is also a tutorial runner for the command-line, and a exporter for static HTML.

The IronRuby tutorial included covers topics such as using the interactive window, built-in libraries, exploring .NET libraries, generics, events, Windows Forms, and Windows Presentation Foundation.

While the tutorial is currently no where near a complete guide to IronRuby, it’s a great place to get started. Also, the first two chapters of the TryRuby tutorial is included as well for testing reasons, but may or may not be ever finished … unless someone wants to make it work, more on how to do that later.

But it can teach all by itself!

While the content of the tutorials can be awesome, and this app can teach the material very efficiently, it can never teach the real experience of building an app in IronRuby. So the IronRuby tutorial app is written in IronRuby as an example of doing all the things a tutorial can’t. Wow, very meta.

Currently, the tutorial app itself covers:

  • User Interfaces in Windows Presentation Foundation
  • Ruby as Data: the tutorial domain-specific language
  • Testing a Ruby application with test-spec
  • Developing a GUI application interactively
  • Anything else we can cram into it in the future :)

These area will be covered in a series of future posts, so keep an eye out for them!

Still plenty of work to be done

This app is far from done, so the exploration of IronRuby in WPF has just begun. Here are some known issues, so don’t complain about these =P

  • The REPL doesn’t have any history via up/down arrow keys.
  • The “Jump to another section” menu scrolls too much. This list can only be two items deep, so it's needs to change to arbitrary depth to have more nesting.
  • The content isn’t totally complete, though the IronRuby tutorial is in great shape. If you have suggestions on topics, please let me know.
  • Jumping between tutorials a bunch makes the memory usage increase to Rails-like proportions (160MB). Not sure why yet. :(
  • The code isn’t the best, but it works. =P I’ll be reorganizing it in future posts about client development, but it serves its purpose for now.

Of course there are a ton of other things that could be done. See the TODO file for some ideas.

Please try it out and let me know what you like about it, what you don’t like, and feel free to futz around with the code as well … contributions are welcome. Enjoy!

Technorati Tags: ,,

by Jimmy Schementi (jschementi@gmail.com) at June 23, 2009 08:49 AM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0: Installation & Usage

There are two ways to use NWSGI: by installing it or by using xcopy deployment. Each method has its advantages and disadvantages, but their functionality is the same.

Installation

The quickest way to get NWSGI up and running is to use the MSI installer. This will add NWSGI to the GAC, making it available for all applications. If you are running IIS 7, it will also install the IIS 7 management components. The installer will also put a copy of the NWSGI assembly along with the README and HelloWorld example in C:\Program Files\NWSGI. This is the preferred approach, unless you do not have administrator rights to the server and cannot convince the server administrator to install it.

xcopy Deployment

The term “xcopy deployment” refers to the Windows xcopy command, which is used to (among other things) copy entire directory trees. Using this method is useful if you can’t (or don’t want to) use the installer package. If this is the case, download the .zip package instead of the MSI installer. To use this method, simply copy NWSGI.dll into your application’s Bin/ directory, and then copy the whole application folder to the server.

Setting Up the Hello World Example

Once you have decided which method you are going to use, the easiest way to check that it is working is to use the HelloWorld example that is included with both packages. I’m only going to describe the most common configuration, and I’m also going to assume you have access to the server; if you have a custom setup (such as a hosted site), just ask.

  1. Copy the HelloWorld sample folder to C:\inetpub\wwwroot.
  2. Mark C:\inetpub\wwwroot\HelloWorld as an application.
    • IIS 6/7: From the IIS management UI, mark the folder as an application.
    • IIS 7: From an elevated command prompt, run: appcmd add app /site.name:"Default Web Site" /path:/HelloWorld /physicalPath:C:\inetput\wwwroot\HelloWorld
  3. Visit http://localhost/HelloWorld/hello.wsgi.

If the browser says “Hello, World!”, you’re good to go! If not, please ask in the forum, and I’ll try to help you out.


by jdhardy (jdhardy@gmail.com) at June 23, 2009 06:41 AM

June 22, 2009

The Voidspace Techie Blog

The Python Object Model Revisited (data descriptors)

A few weeks ago I demonstrated the complexity of the Python object model by fetching docstrings from objects. A while after posting it I thought of a bug - or at least a way in which it could return the wrong result when looking up an attribute on an object. ... [661 words]

June 22, 2009 10:08 PM

IronPython URLs

__clrtype__ Metaclasses: Positional Attribute Parameters

Harry Pierson (the IronPython Program Manager for Microsoft) has been exploring and explaining the new __clrtype__ feature coming in IronPython 2.6 (or already available if you are using the beta).

When we last left him Harry had been creating Python classes with simple .NET attributes applied to members. In this post he delves further and applies attributes that take parameters:
The basic infrastructure for custom attributes in IronPython is in place, but it’s woefully limited. Specifically, it only works for custom attributes that don’t have parameters. Of course, most of the custom attributes that you’d really want to use require additional parameters, both the positional or named variety. Since positional parameters are easier, let’s start with them.

Positional parameters get passed to the custom attribute’s constructor. As we saw in the previous post, you need a CustomAttributeBuilder to attach a custom attribute to an attribute target (like a class). Previously, I just needed to know the attribute type since I was hard coding the positional parameters. But now, I need to know both the attribute type as well as the desired positional parameters. I could have built a custom Python class to track this information, but it made much more sense just to use CustomAttributeBuilder instances. I built a utility function make_cab to construct the CustomAttributeBuilder instances.


by Michael Foord (noreply@blogger.com) at June 22, 2009 03:46 PM

IronPython URLs

A Good Mix 12: Upcoming Presentations, XML Namespaces, ArcGIS and the Hungarian Phrasebook

Yet another selection of blog entries and articles relating to IronPython from the last few weeks.
The Coding Geekette (Sarah Dutkiewicz) is a regular at .NET and Python conferences speaking, amongst other things, about IronPython. In this blog entry she lists her forthcoming talks:
There is also quite a bit of IronPython content at the forthcoming EuroPython 2009 in Birmingam (28th June to 4th July): an IronPython tutorial, ArcGIS and IronPython talk, Introduction to IronPython talk, Ironclad talk and a general Python VM panel discussion.
A Japanese blog demonstrating how to load and save XML from IronPython - using the .NET APIs and working with namespaces. In this case he is iterating through a directory of XHTML files and adding valid namespace declarations.
A short snippet of code showing how to work with .NET APIs that take delegates from IronPython.
Another short 'reminder' blog entry from Simon Taylor, who seems to be having fun with IronPython. String formatting is Python 101 - but is not something you will automatically understand when coming from C#. Interestingly the new string formatting in Python 3.0 (which I'm not really a fan of) is lifted straight from C#.
Silverlight (the browser plugin) is great fun to program with IronPython, but has the disadvantage of it not being possible to compile assemblies instead of deploying source code. One developer at least is keen to change this and has started the "Hungarian Phrasebook" project to create an IronPython pre-compiler for Silverlight.

This is a topic I've looked into a bit, and discussed on the IronPython mailing list, and came to the conclusion it's not easily possible. (There is no cross-compiling support in Reflection.Emit and the APIs used by the Python compiler Pyc will only save to disk which doesn't work in Silverlight.) There is no code in the project yet but I hope it works.
The perrygeo blogger would love to use IronPython with ArcGIS, but discovers that with IronPython 2.0 he has to explicitly call through the interfaces for most of the APIs, making the code painfully verbose.
And then he tries IronPython 2.6 instead of IronPython 2.0 and finds it works as expected. Joy and delight ensues...
Works perfectly now. So IronPython 2.6 promises to be a viable option for extending ArcGIS. My enthusiasm has been renewed.
Nice to finish on a happy note.


by Michael Foord (noreply@blogger.com) at June 22, 2009 03:33 PM

June 20, 2009

The Voidspace Techie Blog

discover: Test discovery for unittest backported to Python 2.4+

I kind of promised you no more entries on unittest for a while, but oh well. I've backported the test discovery in Python-trunk, what will become Python 2.7 & Python 3.2. ... [586 words]

June 20, 2009 06:35 PM

The Voidspace Techie Blog

Catching up: Pythonutils 0.4.0, akismet 0.2.0 and article updates

About two and a half years ago I started writing the book. During the next two years I received a steady trickle of feature requests, bug reports and patches for the various projects and articles I maintain (or pretend to maintain). ... [400 words]

June 20, 2009 05:37 PM

June 18, 2009

Harry Pierson

__clrtype__ Metaclasses: Named Attribute Parameters

In my last post, I added support for custom attribute positional parameters . To finish things off, I need to add support for named parameters as well. Custom attributes support named parameters for public fields and settable properties. It works kind of like C# 3.0’s object initalizers. However, unlike object initalizers, the specific fields and properties to be set on a custom attribute as well as their values are passed to the CustomAttributeBuilder constructor. With six arguments – five of which are arrays – it’s kind of an ugly constructor. But luckily, we can hide it away in the make_cab function by using Python’s keyword arguments feature.

def  make_cab(attrib_type, *args, **kwds):
  clrtype = clr.GetClrType(attrib_type)
  argtypes = tuple(map(lambda x:clr.GetClrType(type(x)), args))
  ci = clrtype.GetConstructor(argtypes)

  props = ([],[])
  fields = ([],[])
  
  for kwd in kwds:
    pi = clrtype.GetProperty(kwd)
    if pi is not None:
      props[0].append(pi)
      props[1].append(kwds[kwd])
    else:
      fi = clrtype.GetField(kwd)
      if fi is not None:
        fields[0].append(fi)
        fields[1].append(kwds[kwd])
      else:
        raise Exception"No %s Member found on %s" % (kwd, clrtype.Name)
  
  return CustomAttributeBuilder(ci, args, 
    tuple(props[0]), tuple(props[1]), 
    tuple(fields[0]), tuple(fields[1]))

def cab_builder(attrib_type):
  return lambda *args, **kwds:make_cab(attrib_type, *args, **kwds)

You’ll notice that make_cab now takes a third parameter: the attribute type and the tuple of positional arguments we saw last post. This third parameter “**kwds” is a dictionary of named parameters. Python supports both positional and named parameter passing, like VB has for a while and C# will in 4.0. However, this **kwds parameter contains all the extra or leftover named parameters that were passed in but didn’t match any existing function arguments. Think of it like the params of named parameters.

As I wrote earlier, custom attributes support setting named values of both fields and properties. We don’t want the developer to have to know if given named parameter is a field or property, so make_cab iterates over all the named parameters, checking first to see if it’s a property then if it’s a field. It keeps a list of all the field / property infos as well as their associated values. Assuming all the named parameters are found, those lists are converted to tuples and passed into the CustomAttributeBuilder constructor.

In addition to the change to make_cab, I also updated cab_builder slightly in order to pass the **kwds parameter on thru to the make_cab function. No big deal. So now, I can add an attribute with named parameters to my IronPython class and it still looks a lot like a C# attribute specification.

clr.AddReference("System.Xml")
from System.Xml.Serialization import XmlRootAttribute 
from System import ObsoleteAttribute, CLSCompliantAttribute
Obsolete = cab_builder(ObsoleteAttribute)
CLSCompliant = cab_builder(CLSCompliantAttribute)
XmlRoot = cab_builder(XmlRootAttribute)

class Product(object):
  __metaclass__ = ClrTypeMetaclass
  _clrnamespace = "DevHawk.IronPython.ClrTypeSeries" 
  _clrclassattribs = [
    Obsolete("Warning Lark's Vomit"), 
    CLSCompliant(False),
    XmlRoot("product", Namespace="http://samples.devhawk.net")]

  # remainder of Product class omitted for clarity

As usual, sample code is up on my skydrive.

Now that I can support custom attributes on classes, it would be fairly straightforward to add them to methods, properties, etc as well. The hardest part at this point is coming up with a well designed API that works within the Python syntax. If you’ve got any opinions on that, feel free to share them in the comments, via email, or on the IronPython mailing list.

by Harry Pierson at June 18, 2009 05:09 PM

Jeff Hardy's Blog (NWSGI)

NWSGI 2.0 Beta 1

NWSGI 2.0 Beta 1 is now available. This is a major update to NWSGI that makes it easier to install and use and dramatically improves the management story.

So, what happened to 1.1?

Originally, NWSGI 1.1 was going to be a refresh of v1.0 that supported IronPython 2.6 and fixed a few bugs. NWSGI 2.0 was going to completely overhaul large parts of the management UI and make some deeper changes to the handler itself. However, I got a week off with some rain and v2.0 progressed much quicker than expected; v1.1 was obsolete before it was even released.

So, v1.1 was dropped and v2.0 will be the first IronPython 2.6-compatible release. It’s easy to make breaking changes when you have no customers :).

What’s New

  • Easier configuration. In v1.0 there were different ways to configure NWSGI depending on your configuration. Now there is only one way to do it. Some of the more ambiguous options have also been cleaned up, and new ones added to support IronPython 2.6.
  • Better management UI. IIS 7 includes a rich UI framework for developing management extensions, but doesn’t have much documentation on it. Some spelunking with reflector showed me better ways to do pretty much everything; not much of the v1.0 management code is left.
  • Performance improvements. NWSGI will now cache the WSGI callable instead of reloading it each time.
  • Other misc. fixes. I really need to get into the habit of adding a Codeplex issue for each bug so that I can keep track of what I’ve fixed.

Give it a spin

The Codeplex wiki needs to be updated to reflect the new documentation, but the included readme is up to date. I’ll also be posting a series of blogs posts over the next few weeks that will explain all the features of NWSGI and provide some helpful examples. Remember, this is a Beta release, so please let me know if you encounter any issues.


by jdhardy (jdhardy@gmail.com) at June 18, 2009 03:00 PM

Dave Fugate (Testing IronPython)

Python Support in Visual Studio

Every couple of months we see a bug report on IronPython Studio or someone on the IronPython Mailing List asking why Microsoft doesn’t support Python in Visual Studio.  Most recently there was a pretty lengthy thread about Python intellisense in VS – see http://lists.ironpython.com/pipermail/users-ironpython.com/2009-June/010566.html.  I’ll attempt to shed more light on some facts mentioned in the thread…

A long time ago (2005), in a galaxy far, far away (Microsoft’s building 42) at least one Jedi (aka software engineer) used the Visual Studio Force to put together a Python light saber…err…I mean ‘language service’ for Visual Studio 2005 – see http://lists.ironpython.com/pipermail/users-ironpython.com/2005-December/001375.html for background.  A ‘language service’ is simply an extension to Visual Studio that makes it aware of one or more file extensions denoting a programming language Visual Studio doesn’t understand by default.  Among other things, this means Visual Studio might provide syntax highlighting for the programming language in the editor.  Any ways, this particular Python language service was never intended to provide complete IronPython support for Visual Studio.  Instead, this was bundled with the VS 2005 SDK as a complete sample to show developers how to extend Visual Studio for their own programming languages.  I’m not even sure any testers on the IronPython team ever evaluated this sample, but do believe we had at least one developer working on it.  I can’t really provide too many more details on the Python language service in the VS 2005 SDK as I didn’t join the IronPython team until summer 2006.

IronPython Studio was an update to the VS 2005 SDK Python language service for VS 2008 put together by a consulting firm named Clarius Consulting Labs.  To the best of my knowledge the IronPython Team had no involvement in the creation of IronPython Studio.  Also, the emphasis again was on being a complete VS language service implementation and not necessarily adding the best Python support to VS.  I think it’s a little unfortunate this tool has ‘IronPython’ in the title as this confuses people and leads them to believe we have the ability to fix bugs in it and also add new features (none of the IronPython Team is even listed as contributors to IronPython Studio – see http://ironpythonstudio.codeplex.com/People/ProjectPeople.aspx).  Finally, a few people in the IronPython community have observed that this piece of software is “abandonware”.  I agree, but wouldn’t be too surprised if it got revived for VS2010.

I think I speak for everyone on the IronPython Team when I say we’d love to see IronPython support in Visual Studio by default without the need for any language service addition.  The thing is these types of decisions are made at a much higher level than us and are heavily influenced by business needs.  What I’m getting at here is if enough people provided feedback via the proper channels that:
 

  • The next version of VS is great, but it’d be better if it supported Python development
  • You don’t currently use VS but you would if it had Python support
  • Ahem…you’d be willing to pay for IronPython support in VS
  • Etc

then the next version of VS could very well have Python support built into itJ  What are the proper channels for feedback you ask?  The VS 2010 feedback page (https://connect.microsoft.com/VisualStudio/content/content.aspx?ContentID=9790) would be a great start.

June 18, 2009 05:06 AM

Dave Fugate (Testing IronPython)

Congratulations to the Jython Team

Looks like the Jython guys just released 2.5.0 final!  I'm curious as to which version of CPython they target next compatibility wise...



June 18, 2009 02:43 AM

June 17, 2009

Harry Pierson

__clrtype__ Metaclasses: Positional Attribute Parameters

The basic infrastructure for custom attributes in IronPython is in place, but it’s woefully limited. Specifically, it only works for custom attributes that don’t have parameters. Of course, most of the custom attributes that you’d really want to use require additional parameters, both the positional or named variety. Since positional parameters are easier, let’s start with them.

Positional parameters get passed to the custom attribute’s constructor. As we saw in the previous post, you need a CustomAttributeBuilder to attach a custom attribute to an attribute target (like a class). Previously, I just needed to know the attribute type since I was hard coding the positional parameters. But now, I need to know both the attribute type as well as the desired positional parameters. I could have built a custom Python class to track this information, but it made much more sense just to use CustomAttributeBuilder instances. I built a utility function make_cab to construct the CustomAttributeBuilder instances.

def  make_cab(attrib_type, *args):
  argtypes = tuple(map(lambda x:clr.GetClrType(type(x)), args))
  ci = clr.GetClrType(attrib_type).GetConstructor(argtypes)
  return CustomAttributeBuilder(ci, args)

from System import ObsoleteAttribute 

class Product(object):
  __metaclass__ = ClrTypeMetaclass
  _clrnamespace = "DevHawk.IronPython.ClrTypeSeries"   
  _clrclassattribs = [make_cab(ObsoleteAttribute , "Warning Lark's Vomit")]

  # remaining Product class definition omited for clarity

In make_cab, I build a tuple of CLR types from the list of positional arguments that was passed in. If you haven’t seed the *args syntax before, it works like C#’s params keyword – any extra arguments are passed into the function as a tuple names args. I use Python’s built in map function (FP FTW!) to build a tuple of CLR types of the provided arguments, which I then pass to GetConstructor. Previously, I passed an empty tuple to GetConstructor because I wanted the default constructor. If you don’t pass any positional arguments, you still get the default constructor. Once I’ve found the right constructor, I pass it and the original tuple of arguments to the CustomAttributeBuilder constructor.

One major benefit of this approach is that it simplifies the metaclass code. Since _clrclassattribs is now a list of CustomAttributeBuilders, now I just need to iterate over that list and call SetCustomAttribute for each.

    if hasattr(cls, '_clrclassattribs'):
      for cab in cls._clrclassattribs:
        typebld.SetCustomAttribute(cab)

The only problem with this approach is that specifying the list of custom attributes is now extremely verbose. Not only am I specifying the full attribute class name as well as the positional arguments, I’m also having to insert a call to make_cab. Previously, it kinda looked like a C# custom attribute, albeit in the wrong place. Not anymore. So I decided to write a function called cab_builder to generates less verbose calls to make_cab:

def  cab_builder(attrib_type):
  return lambda *args:make_cab(attrib_type, *args)

from System import ObsoleteAttribute 
Obsolete = cab_builder(ObsoleteAttribute)

class Product(object):
  __metaclass__ = ClrTypeMetaclass
  _clrnamespace = "DevHawk.IronPython.ClrTypeSeries"   
  _clrclassattribs = [Obsolete("Warning Lark's Vomit")]

  # remaining Product class definition omited for clarity

The cab_builder function returns an anonymous lambda function that closes over the attrib_type variable. Python lambdas are just like C# lambdas, except that they only support expressions [1]. The results of calling the lambda returned from cab_builder is exactly the same as calling make_cab directly, but less verbose. And since I named the function returned from cab_builder Obsolete, now my list of class custom attributes looks exactly like it does in C# (though still in a different place). As usual, the code is up on my skydrive.

If you’re only using the attribute once like this, it is kind of annoying to first declare the cab_builder function. If you wanted to you could iterate over the types in a given assembly, looking for ones that inherit from Attribute and generate the cab_builder call dynamically. However, I’m not sure how performant that would be. Another possibility would be to iterate over the types in a given assembly and generate a Python module on disk with the calls to cab_builder. Then, you’d just have to import this module of common attributes but still be able to include additional calls to cab_builder as needed.

[1] The lack of statement lambdas in Python is one of my few issues with the language.

by Harry Pierson at June 17, 2009 06:02 PM

ASP.NET for IronPython

A new and improved ASP.NET MVC T4 template

A couple weeks ago, I blogged about using a Build provider and CodeDom to generate strongly typed MVC helpers at runtime. I followed up a few days later with another version that used T4 templates instead, making it easier to customize. And now I’m back with yet another post on this topic, but this time with a much simpler and improved approach! The big difference is that I’m now doing the generation at design time instead of runtime. As you will see, this has a lot of advantages. Drawbacks of the previous runtime approach Before we go and re-invent the wheel, let’s discuss what the issues with the runtime T4 approach were, and how this is solved by this new approach. Complex configuration : to enable the runtime template, you had to add a DLL...(read more)

by David Ebbo's blog : ASP.NET at June 17, 2009 03:34 PM

June 16, 2009

IronPython URLs

__clrtype__ Metaclasses: Simple Custom Attributes

One of the exciting new features in IronPython 2.6 is the addition of the __clrtype__ metaclass. This allows you to specify and customize the .NET type that backs your Python classes.

This is important because by default new Python classes aren't also .NET classes. This is for various reasons: Python classes are mutable, .NET classes can't be garbage collected and so on. This causes one of the biggest gaps in the IronPython integration; using .NET attributes requires them to be applied to a real .NET class. There are other features, like some kinds of data binding, also a real .NET class.

There are techniques to overcome this, but they're clunky at best. In IronPython in Action I demostrate runtime generation, compilation and subclassing of C# classes as one technique.

At last the __clrtype__ metaclass provides a better way built into IronPython, but it is a pretty low-level feature requiring a lot of work to build on top of it. Harry Pierson, the IronPython program manager, has been showing how to use __clrtype__ to fill some of these use cases. In his first series of articles Harry demonstrated databinding with Silverlight. Now he has started to tackle custom attributes:
Over the course of the next three blog posts, I’m going to build out a mechanism for specifying custom attributes on the CLR type we’re generating via __clrtype__. All the various Builder classes in System.Reflection.Emit support a SetCustomAttribute method that works basically the same way. There are two overloads – the one I’m going to use takes a single CustomAttributeBuilder as a parameter.

For this first post, I’m going to focus on the basic custom attribute infrastructure, so we’re going to use the extremely simple ObsoleteAttribute. While you can pass some arguments to the constructor, for this first post I’m going to use the parameterless constructor. To keep things less confusing, I’m going back to the original version of the Product class, before I introduced CLR fields and properties. The one change I’m making is that I’m adding a list of attributes I want to add to the class.


by Michael Foord (noreply@blogger.com) at June 16, 2009 09:46 PM

IronPython URLs

Embedding IronPython as a scripting language

Mark Bloodworth, Microsoft Architect Evangelist, shows how to use IronPython to add scripting to a .NET application.
A great way of extending an application is to allow users to write their own scripts. Fortunately, with the Dynamic Language Runtime it is fairly simple to provide scripting in your application. Let’s look at how to do it with a simple Windows Forms application and IronPython.

...

It’s simple to add powerful scripting support to your applications, while maintaining control over the scripting runtime means that you can restrict what any user entered code can do. I chose to show this example in IronPython, but the principles for doing this with Ironruby are identical (of course you’ll need a reference to IronRuby.) In fact, you could offer users the choice of languages.


by Michael Foord (noreply@blogger.com) at June 16, 2009 05:22 PM

June 15, 2009

Harry Pierson

__clrtype__ Metaclasses: Simple Custom Attributes

I know it’s been a while since my last __clrtype__ post, but I was blocked on some bug fixes that shipped as part of IronPython 2.6 Beta 1. So now let’s start looking at one of the most requested IronPython features – custom attributes!

Over the course of the next three blog posts, I’m going to build out a mechanism for specifying custom attributes on the CLR type we’re generating via __clrtype__. All the various Builder classes in System.Reflection.Emit support a SetCustomAttribute method that works basically the same way. There are two overloads – the one I’m going to use takes a single CustomAttributeBuilder as a parameter.

For this first post, I’m going to focus on the basic custom attribute infrastructure, so we’re going to use the extremely simple ObsoleteAttribute. While you can pass some arguments to the constructor, for this first post I’m going to use the parameterless constructor. To keep things less confusing, I’m going back to the original version of the Product class, before I introduced CLR fields and properties. The one change I’m making is that I’m adding a list of attributes I want to add to the class.

from  System import ObsoleteAttribute 

class Product(object):
  __metaclass__ = ClrTypeMetaclass
  _clrnamespace = "DevHawk.IronPython.ClrTypeSeries"   
  _clrclassattribs = [ObsoleteAttribute]
  
  # remainder of class omitted for clarity

Python list comprehensions use the same square bracket syntax as C# properties, so it kinda looks right to someone with a C# eye – though having the attribute specifications inside the class, rather than above it, is totally different. I wish I could use Python’s class decorators for custom class attributes, but class decorators run after metaclasses so unfortunately that doesn’t work. Also, I can’t leave off the “Attribute” suffix like you can in C#. If I really wanted to, I could provide a new type name in the import statement (“from System import ObsoleteAttribute as Obsolete”) but I thought spelling it out was clearer for this post.

Now that I have specified the class attributes, I can update the metaclass __clrtype__ method to set the attribute on the generated CLR class:

    if hasattr(cls, '_clrclassattribs'):
      for attribtype in cls._clrclassattribs:
        ci = clr.GetClrType(attribtype).GetConstructor(())
        cab = CustomAttributeBuilder(ci, ())
        typebld.SetCustomAttribute(cab)

I’m simply iterating over the list of _clrclassattribs (if it exists), getting the default parameterless constructor for each attribute type, creating a CustomAttributeBuilder instance from that constructor and then calling SetCustomAttribute. Of course, this is very simple because we’re not supporting any custom arguments or setting of named properties. We’ll get to that in the next post. In the mean time, you can get the full code for this post from my skydrive.

There is one significant issue with this custom attribute code. Attributes are typically marked with the AttributeUsage attribute that specifies a set of constraints, such as the kind of targets a given attribute can be attached to and if it can be specified multiple times. For example, the MTAThread attribute can’t be specified multiple times and it can only be attached to methods. However, those attribute constraints are validated by the compiler, not the runtime. I haven’t written any code yet to validate those constraints, so you can specify invalid combinations like multiple MTAThread attributes on a class. For now, I’m just going to leave it to the developer not to specify invalid attribute combinations. Custom attributes are passive anyway so I’m figure no one will come looking for a MTAThread attribute on a class or other such scenarios.

However, I’m interested in your opinion: When we get to actually productizing a higher-level API for __clrtype__, what kinds of attribute validation should we do, if any?

by Harry Pierson at June 15, 2009 05:34 PM

The Voidspace Techie Blog

Parametrized Tests and unittest

Yet another blog entry on unittest; this is the last one in my list so I'm not planning any more for a while. Something that both nose and py.test provide that unittest (the [1] Python standard library testing framework) doesn't is a builtin mechanism for writing parametrized tests. ... [1227 words]

June 15, 2009 02:38 PM

The Voidspace Techie Blog

Gadgets: Samsung SSD, Sharkoon SATA Adaptor, Mimo USB Monitor and Powermate USB Volume Knob(!)

Over the last few months I've bought a few new gadgets, and they're well overdue a review; so here goes. Samsung PB22 2.5" 256GB SSD (Solid State Drive) As I'm sure you're aware Solid State Drives are hard drives using flash memory instead of mechanical disks; this eliminates the need for spin up, plus makes seek times and data rates potentially much faster and power consumption less. ... [1133 words]

June 15, 2009 12:44 PM

June 14, 2009

IronPython URLs

IronRuby 1.0 (soon), Inside IronRuby and Professional IronRuby

IronPython 1.0, a complete implementation of Python for the .NET framework, was released in September 2006. The first IronPython 2.0 release (Alpha 1) came in April 2007. IronPython 2.0 was built on the new Dynamic Language Runtime (DLR) which was a framework for implementing dynamic languages in general, which had been abstracted out of the IronPython 1.0 release.

Along with the new IronPython 2.0 project IronRuby was announced. IronRuby was an implementation of Ruby for .NET, led by John Lam who had previously been involved in the RubyCLR project. It has been a long road for IronRuby, with the latest release version 0.5.
Following their tradition of conference driven releases (panic-driven-development?) IronRuby 1.0 will be released at the coming OSCON 2009 conference:
IronRuby is 1.0! Come and see how IronRuby is used in .NET programs, how well it performs, and how conformant it is. IronRuby is an Open Source implementation of the Ruby programming language, built on top of Microsoft’s Open Source Dynamic Language Runtime. OSCON has an important place in the history of IronRuby, and it is only appropriate that we launch IronRuby 1.0 at OSCON 2009.
Jimmy Schementi is a member of the Microsoft dynamic languages team. In this 43 minutes channel 9 video he discusses the IronRuby project:
Jimmy Schementi is a Program Manager (and developer) on the IronRuby team. IronRuby is an Open Source implementation of the Ruby programming language for .NET, heavily relying on Microsoft's Dynamic Language Runtime. IronRuby is Ruby, but implemented on top of the DLR (which of course provides the capability for dynamic languages to interact with the BCL and CLR).

You've learned about the details of the DLR here on 9, which provides dynamic runtime support for .NET. IronRuby targets compatibility with the 1.8.x branch of Ruby modulo continuations. IronRuby is an implementation of Ruby version 1.8.6.

Here, Jimmy explains the thinking behind the IronRuby project. Why are we doing this, anyway? When/Why would Ruby developers use IronRuby? What's the current status of the project? What's the future hold for IronRuby? Tune in and learn about the past, present and future of IronRuby.
Early reviews of IronRuby in Action (for Manning Publications by Ivan Porto Carrero) are good, but it isn't the only IronRuby book in progress. Hot on the heels of Pro IronPython being released is Professional IronRuby, by Wrox and due out any day.
Professional IronRuby provides a complete guided tour through IronRuby, demonstrating why Ruby is important, what IronRuby can add to your .NET development arsenal, and how you can take advantage of Ruby while utilizing existing infrastructures. Building on your existing .NET knowledge, the authors will walk you through Ruby’s syntax and structure and the ways you can use IronRuby for .NET projects. Learn how to apply IronRuby to ASP.NET and Silverlight and decide where to develop your components, with straight-forward guidance on when and why to use IronRuby instead of C#, and vice versa.
Meanwhile Ivan continues to work IronRuby in Action (the companion book to IronPython in Action). He has just posted a sample ASP.NET MVC example using IronRuby to his blog that will be one of the examples in the book.


by Michael Foord (noreply@blogger.com) at June 14, 2009 07:38 PM

June 13, 2009

The Voidspace Techie Blog

Fuzzywuzzy Beard

In my last post I mentioned my fuzzywuzzy beard not once but twice. Here's a great picture of me and my fuzzywuzzy beard drawn by Scott Meyer, the creator of the Basic Instructions webcomic. ... [43 words]

June 13, 2009 07:24 PM

The Voidspace Techie Blog

Future adventures of unittest and a mini-rant

There is a general rule that innovation doesn't happen in the standard library. Instead modules or techniques that have already proven themselves in the Python community are adopted into the standard library. ... [1372 words]

June 13, 2009 07:06 PM

IronPython URLs

A Good Mix 11: A Rules Engine, Embedding, SharePoint and NWSGI

Another selection of blog entries and articles relating to IronPython from the last few weeks.
A blog entry from Dave Fugate (IronPython testing and infrastructure guy) on an exception message that shouldn't be visible. Looks like it is actually a bug in Vista, but as it was triggered by IronPython it gets a mention here:
IronPython most definitely should not be able to spawn an error message box that's visible when Vista is locked at the username/password screen. Quite annoying yet very interesting at the same time...
Another blog entry from Mark Bloodworth (a Microsoft Architect evangelist) on using IronPython. It demonstrates writing classes in C# and using them from IronPython. The entry is short because this is something that IronPython makes trivially easy:
It’s really simple to use a .NET class in IronPython. The first thing to remember is that you’ll need to add a reference (just like you would in .NET). To do that you use the AddReference method of the clr module. In the case of an assembly you’ve written, IronPython needs to be able to find it, which means it needs to be in sys.path. It turns out that you can add the path to your assembly by using the append method of sys.path.
This project is actually not new at all, I just hadn't heard of it. It's nice to discover people using IronPython in ways I wasn't aware of. This project is by Glen Cooper and he describes it here:
This library provides the ability to automate various
SharePoint activities through easy to read and modify Python
scripts.

The core library is located in the sp module. The scripts
module contains a number of scripts for performing specific
activities such as backing up sites.
A good use case for embedding IronPython in a .NET application is to use it as a rules engine for evaluating rules stored as text which can be modified or added to without requiring recompilation of the application. This is exactly what Nathan of the Crippeoblade blog has been up to:
In my last post I talked about creating a rules engine to generate a scouts evaluation of a player. Having played with IronPython for a few hours this evening I’ve managed to introduce a dynamic script to represent the rule engine. This means I can replace the rules engine or for that matter any one else can without having to re-compile the code. It’s suddenly dawned on me how this exciting technology can make a game extensible. With .NET 4 introducing the dynamic keyword plus other functionality for dynamic languages it’s going to make it even easier.

Performance wise it actually seemed pretty fast. This was one concern I had because of the greater work at runtime required. Objects aren’t statically typed so the runtime engine has to do the typing at runtime. Just starting to learn python and I must say I’m loving it so far. I’ve done nothing complex just followed a few tutorials and coded up a small script to test out ironpython running within c#. So how did I manage that.
It seems like only a few days since the release of NWSGI 1.1 Preview 2 was announced, but it seems there was a problem with configuration on 32bit machines: "NWSGI 1.1 Preview 3 is a refresh of Preview 2 that fixes issues with configuration on 32-bit platforms. The release can only be used for xcopy deployments."

NWSGI is an implementation of the WSGI specification (Web Server Gateway Interface) for IronPython. It is implemented as an ASP.NET HttpHandler and is supported on the IIS 6 / 7 webservers (or any ASP.NET capable server). NWSGI allows the integration of Python applications like Trac and Django with existing ASP.NET facilities such as caching, sessions, and user management.
Embedding IronPython in C# is so easy everyone is at it. Here is another example; including executing code and fetching the result and populating a DataTable and manipulating it from IronPython.


by Michael Foord (noreply@blogger.com) at June 13, 2009 02:04 PM

IronPython URLs

A New Book on IronPython: Pro IronPython

IronPython in Action may have been the first book (in English) on IronPython but it is no longer the only one. Pro IronPython, by Alan Harris for Apress, is now available.
IronPython represents a unique direction for developers interested in working with dynamic languages within the .NET Framework. Whether you’re looking to develop applications from scratch or add functionality and maintainability to an existing application, IronPython opens many doors while providing a high–speed, high–performance language that integrates tightly with other .NET languages.
  • Learn to create applications using the benefits of a dynamically typed language.
  • Discover how to leverage the power of IronPython to improve existing applications.
  • Explore interacting with other .NET languages by invoking the common language runtime.
What you’ll learn
  • Write IronPython console and forms applications.
  • Integrate IronPython scripts into existing applications to increase their functionality.
  • Implement complex data patterns and interact with databases.
  • Use the common language runtime to take advantage of .NET’s existing framework within IronPython scripts.
  • Understand how IronPython can be brought in to solve a variety of programming tasks through extensive exercises and recipes.
  • Avoid the common pitfalls of working with a dynamically typed language.
Who is this book for?
This book is designed for .NET developers interested in expanding their IronPython skills and learning how to make use of them to improve their daily programming practices. It will introduce core concepts of IronPython programming using a .NET–centric approach. Additionally, it will speak to Python developers looking to expand into their skills into the .NET world. Experience with a .NET language is expected. Previous Python experience is not necessary.

About the Author
Alan Harris is a web and application developer living in Arlington, VA. He has worked at more than a few organizations using .NET to create enterprise solutions since the glory days of version 1.1, and can still browse to some of the oldest ones. Aside from working at his desk, he spends most of his time studying Krav Maga and writing music.
Before the book was published Alan and I exchanged a few emails, discussing duck-typing and the different audiences for IronPython in Action and Pro IronPython. In the process I ended up getting quoted in the intro to his book:
"Many developers take issue with this and find the approach too loose, too error-prone. I was speaking to Pythonista and author Michael Foord about the matter; I mentioned the argument, “What if it looks like a duck, quacks like a duck, but is really a dragon impersonating a duck? You don’t want a dragon in your pond.” He replied, “if you code dragons, you’ve got no one to blame but yourself if they get in your pond.” I informed him that “the only difference between my IronPython dragons and my C# ones is my C# ones have ‘Hello my name is’ nametags.” So it goes."

I will be interested to see what you think of "Pro IronPython". I've had the luxury of reading both your book and mine, and I think you'll agree we speak to very different audiences. Apress wanted a book easy enough that someone with zero programming experience could pick it up and run, being pretty well versed by the end (which pretty much speaks to the entire Pro line I think, with a few exceptions). Your book covers some terrific stuff (the PowerShell parts I found particularly interesting) but a lot would be beyond the target audience of mine. I think, however, that they are rather complimentary books.


by Michael Foord (noreply@blogger.com) at June 13, 2009 12:59 PM

June 11, 2009

IronPython URLs

Why Choose IronPython over C#?

Matthew Harelick just asked (on the Python.NET mailing list of all places) why he should consider using IronPython:
My background is primarily UNIX. I have been programming in C, TCL, Perl, and Python in UNIX and Linux for a long time.

I recently started working in Visual Studio and C#.

Visual Studio and C# make everything very easy. Python was nice when you didn’t have the convenience of Visual Studio and intellisense with a nice debugger.

In the windows world I see no major reason not to use C#.

Why would I want to use IronPython?
A lot of C# developers feel the same way, why should they consider another language? Here is my answer:
Both Python and C# are 'general purpose' programming langugages suited to a wide range of problem domains. Choice of programming language is therefore usually a matter of aesthetics, what you are used to, personal workflow, issues within a team and so on rather than a matter of which is more appropriate to the job. Obviously there are exceptions where one language is obviously more appropriate or obviously inappropriate but these are the exception rather than the rule.

Place where you should obviously use IronPython:
  • For embedding as a user scripting language / plugin mechanism or are doing runtime code generation
Place where you should obviously use C#:
  • You have already implemented in a dynamic language, profiled and optimised, and need faster performance than the dynamic language is capable of
Other than that the choice is yours!

Here are a few reasons why I / some people prefer IronPython:
  • The interactive environment is an invaluable tool for exploration
  • No need to create a whole 'object-oriented-application' for simple tasks where it is not needed
  • Without a compile phase and with duck typing / dynamic typing IronPython makes it dramatically easier to do test driven development or even normal unit testing
  • Python has many language capabilities missing from C# which make it a flexible and concise language. These include:
    • Duck typing and protocols (no need for explicit interfaces)
    • Heterogeneous containers (no need for generics)
    • Pain free introspection (no need for the complexity inherent in System.Reflection)
    • Metaprogramming including good old eval, type creation at runtime, decorators and descriptors
    • Late binding and runtime type dispatch
    • 'Little features' like tuple unpacking, returning multiple values, everything is an object (including primitives, functions, classes and modules)
There are things that C# has that Python doesn't (compile time checking, method overloading, access to .NET attributes), but choose whichever you prefer.
I've written about this subject before (and at a bit more length) in Dynamic Languages and Architecture.

Other reasons I didn't think about the time:
  • If you are starting out Python is much easier to learn than C#.
  • As a concise and expressive language it is faster to prototype solutions in Python and faster to turn those prototypes into full applications!
  • Writing portable, cross-platform code. Compatibility with CPython is a great thing.
  • Availability of open-source libraries. There are orders of magnitude more open source libraries for Python than there are for C# despite C# being used more than Python in commercial settings.
  • Python is the 'standard' language in various problem domains (GIS and animation scripting, Linux system administration and certain types of scientific programming for example).


by Michael Foord (noreply@blogger.com) at June 11, 2009 07:33 PM

IronPython URLs

Mono can now compile IronPython 2.0

If you follow this blog, or the state of IronPython on Mono, you will know that the version of IronPython included in Mono (from the FePy project) is quite out of date. This is because (for various reasons) Mono has been unable to compile IronPython 2.0 from source which has prevented a new FePy release.

This causes a problem with running the IronPython in Action examples from Mono and I wrote a blog entry about how to work around this:
The intention is that MultiDoc, along with as many examples from the book as possible, run on both Mono and the .NET framework; IronPython isn't just for Windows but can also be used on Linux and Mac OS X or anywhere that Mono will run.

Some readers have reported that MultiDoc crashes on exit when run with Mono. The root cause of this is the old version of IronPython 2 that ships with Mono.

...

This is reason enough to look at using a more recent version of IronPython 2. Even though IronPython can't be compiled with Mono you can still use the up to date Windows binaries (which is part of the point of Mono - binary compatibility). To use the latest version of IronPython (2.0.1) you'll need Mono 2.4 or more recent...
However there is good news on this front. Ankit Jain recently posted the following to the Mono development email list:
Current xbuild status:

It can handle solutions (.sln) now, thanks to Jonathan Chambers, with C#, VB.net projects. Handles embedded resources, satellite assemblies, project references etc.

Eg. Paint.Net 3 ( builds completely with it now, IronPython (2.0.1) builds, IronPython svn (builds with compile time errors) etc.

Only .net 2.0 projects are supported currently though. I will start adding support for newer versions very soon, also ASP.NET, Silverlight etc projects.

This is part of the mono 2.4.2 release and is a *big* improvement over xbuild in the last release. Would be really helpful to get feedback and bug reports on this :)
In his status update Seo Sanghyeon (FePy maintainer) did report that IronPython 2.6 trunk could be built with Mono, so it looks like a recent checkin has broken Mono compatibility - temporarily I'm sure. However, the news that Mono can now compile IronPython 2 is great and hopefully means that a FePy update will follow on shortly.


by Michael Foord (noreply@blogger.com) at June 11, 2009 02:11 PM

IronPython Cookbook (New Entries)

Checking Python Syntax without Executing

MichaelFoord: [[Checking Python Syntax with Executing]] moved to [[Checking Python Syntax without Executing]]


A useful snippet of code (actually shown from IronPython - but very easy to translate into C#) for checking the validity of Python code without actually executing it.

<pre>
engine = IronPython.Hosting.Python.CreateEngine()
source = engine.CreateScriptSourceFromString(text, SourceCodeKind.File)
errors = ErrorListener()
command = source.Compile(errors)
if command is None:
# compilation failed

</pre>

Here, ErrorListener is some class that derives from ''Microsoft.Scripting.Hosting.ErrorListener'' and stores the errors.


Back to [[Contents]].

by MichaelFoord at June 11, 2009 01:49 PM

IronPython Cookbook (New Entries)

Checking Python Syntax with Executing

MichaelFoord:


A useful snippet of code (actually shown from IronPython - but very easy to translate into C#) for checking the validity of Python code without actually executing it.

<pre>
engine = IronPython.Hosting.Python.CreateEngine()
source = engine.CreateScriptSourceFromString(text, SourceCodeKind.File)
errors = ErrorListener()
command = source.Compile(errors)
if command is None:
# compilation failed

</pre>

Here, ErrorListener is some class that derives from ''Microsoft.Scripting.Hosting.ErrorListener'' and stores the errors.


Back to [[Contents]].

by MichaelFoord at June 11, 2009 01:49 PM

June 09, 2009

IronPython URLs

A Good Mix 10: WPF, .NET Introspection, the Solver Foundation, Resolver One and Cobra

Another selection on a wide range of topics from the last few weeks.
Resolver One is an IronPython spreadsheet system and is the largest IronPython codebase in production. Normally a new release would be big news but we've already covered the Python console which is the biggest new feature in version 1.5. Other big new features include CSV import / export and a goto line dialog for the code editor. You can read a full list of all the improvements in the changelog. Now that 1.5 is out we're working hard on features for version 1.6. Our latest blog entry has a sneak preview of one of the coming attractions.
For Python methods you can use the inspect module to get information about methods / functions; like what arguments they take and so on.

Methods on .NET types don't have the attributes used by inspect (although methods of Python objects defined in IronPython work fine). We can get around this by using .NET reflection to introspect them them.

Reflection is normally done with classes from the System.Reflection namespace. We don't have to use these classes directly, but get them indirectly.

This IronPython Cookbook entry is an example of getting information about the OpenStandardOutput method of the System.Console class. We can then get the return type (something not available in Python) and the names of all the parameters.
A Japanese blog entry showing example IronPython code for a movie player capable of playing H264 encoded movies using the Windows Presentation Foundation MediaElement class (in 34 lines of code).
Microsoft Solver Foundation is a solver framework. The webpage is so full of buzzwords that its hard to get a clear definition of what it does. This looks like the closest:
Solver Foundation uses a declarative programming model, consisting of simple compatible elements that are solved by application of solvers, meta-heuristics, search techniques, and combinatorial optimization mechanisms to accelerate the solution finding process. Building a model in Solver Foundation is as simple as specifying the decisions to be made, constraints to be respected, the goals to be used to evaluate candidate proposals (solutions) and the data to be processed by the model (historical or projected parameters).
This kind of approach is very useful for working with data in spreadsheets. Suresh has posted some example IronPython code (an Optima Petro Sample) which works standalone or can be used with Resolver One.
Another Japanese blog entry from the blog that brought us the video player example. This example code shows using the Windows Presentation Foundation GUI library to create a simple window with Menu and shortcut keys. The menu is populated from a small snippet of XAML.
Cobra is a Python inspired programming language for the .NET framework. We've often covered news and updates on Cobra here on the IronPython-URLs blog. This article in the June edition of MSDN magazine, by well known .NET developer Ted Neward, is the first installment of a column on Cobra:
In the first installment of this column, I discussed the importance of understanding more than one programming language, and in particular, more than one kind of programming language; just knowing C# and/or Visual Basic isn't enough to stand out against the mob anymore. The more tools in your toolbox, the better the carpenter you become. (Up to a point, anyway—'tis the poor carpenter who owns every tool ever made and yet still doesn't know how to use any of them.)

In this installment, I'll examine a language that's not too far removed from the object-oriented languages you're familiar with, but has a few new features that will not only offer some new ideas, but potentially kick-start some new ways of thinking about your current tool set.

Allow me to introduce you to Cobra, a descendant of Python that, among other things, offers a combined dynamic and statically typed programming model, built-in unit test facilities, scripting capabilities, and some design-by-contract declarations.



by Michael Foord (noreply@blogger.com) at June 09, 2009 02:28 PM

Aaron Marten's WebLog

What is the “VSIX Project” template?

Disclaimer : This is about working with the Visual Studio 2010 Beta 1 SDK. Information is likely to be inaccurate for future or previous Visual Studio SDK releases.

When you install the Visual Studio 2010 SDK Beta 1, you’ll notice a new node in the new project dialog under Visual C#\Extensibility and Visual Basic\Extensibility:

image

The editor extension templates are what you would expect. They give you a project that builds a MEF component (which the VS core editor consumes) to provide various adornments, etc…

If you would want to build a VSPackage, the trusty package wizard still lives where it always has under Other Project Types\Extensibility:

image

So then, what is that “VSIX Project” template for (in the first screenshot)?

The VSIX Project is meant to be a very simple project template that is used for building a raw VSIX “bundle” (i.e. the zip container). That’s why there is essentially no code in the project at all. This could be useful in situations where you were only just packaging up something like a project or item template, and weren’t really building any code. Pedro mentions this in his blog post series on how to build a VSIX-based project/item template for distribution on the VS Gallery.

Preventing the DLL/PDB from being added to the VSIX

One thing you may notice is that the DLL and PDB built from the project (that you don’t need if you’re just packaging up some templates) gets included in the VSIX file. To suppress this, you could either use the VSIX Explorer tool to edit the file post-build (tedious since you need to do this for each build)…or simply add the following XML snippet to your CSProj/VBProj to prevent the DLL or PDB from being included in the VSIX file at all:

<PropertyGroup>
<CopyBuildOutputToOutputDirectory>false</CopyBuildOutputToOutputDirectory>
<CopyOutputSymbolsToOutputDirectory>false</CopyOutputSymbolsToOutputDirectory>
</PropertyGroup>
 
Please note that this workaround is only meant for the Beta 1 SDK. This may change in future SDK releases.

by aaronmar at June 09, 2009 01:11 PM

IronPython URLs

DateSelector and Excel COM Automation Examples

Greg Bray has been using IronPython since entering (and winning) a round of the Resolver Systems spreadsheet competition. Since then he has had fun experimenting with IronPython has posted a couple of fairly complex example programs to his blog.
I have been playing around with IronPython recently while creating spreadsheets in Resolver One. So far I have been having a lot of fun, but I haven't really been doing anything that would be useful in a work setting. The main reason for this is because most of the spreadsheet work that I do revolves around pivot tables and Auto Filter, which are immensely helpful for visually analyzing data. I thought I might try and use Excel's COM Automation to add Pivot Charts and Auto Filter to any system with IronPython, and here is the code that I have come up with so far.

...

The code should be pretty straight forward. The Reload() method is helpful for reloading the whole module when testing from a console. The Run() method shows the steps to load a new spreadsheet. The ExcelManager static class is the core of the logic and provides an entry point for interacting with the spreadsheet.

There is not a lot of debuging code, so if something goes wrong it is just going to throw an exception, but this should be enough to help get things started. I did fix some funky problems with importing DateTime, where they kept getting converted into integers. Should work fine now, but anything other than Datetime, numerical types or strings will probably not get imported correctly.
Another quick IronPython snipet that shows how to use the Windows.Form.MonthCalendar control to create a simple date selector.

...

Works well for selecting singe dates, and could be modified to support selecting a date range if desired. I prefer having a Start Date and End Date, and selecting each separately.


by Michael Foord (noreply@blogger.com) at June 09, 2009 12:48 PM

June 08, 2009

Miguel de Icaza

PhyreEngine, Mono, cool Mono uses in Gaming, and more.

Last week there was a little Mono surprise. It can be found on this Novell-hosted web page web page (scroll a little bit).

It has been a few very busy weeks at Novell's Eastern Research and Development Facility (Novell NERD Facility) here in Cambridge and we have been incredibly busy polishing some nice toys.

A few weeks ago we learned about Sony's developer event in the West Coast. Michael, Zoltan and myself worked very hard to put together a demo to show the virtues of C# and the CIL to developers. So we cranked on some record time some code:

  • PhyreEngine#
  • Static compiler for PowerPC for Mono on PS3
  • A yield-based co-routine framework.

We picked Sony's PhyreEngine to demostrate how to use Mono to write the high-level code for a game using Sony's finely tuned engine. We figured this was better than showing a for loop printing the numbers 1 to 10 on the screen.

PhyreEngine# wraps PhyreEngine using the same techniques that we used in Gtk# and Moonlight. The resulting API is glorious and by letting PhyreEngine do all the heavy lifting while driving all the high-level from C# there is no way of telling that the driving force is not C++. All you get is pure unadultered productivity.

To make our demos a little more interesting, Michael wrote a minimalistic yield-based co-routine framework inspired by some of the ideas that our friend Lucas gave us. It is a tiny toy, but we used it to illustrate the concept of using C# iterators as the foundation for game logic development and how a cooperative scheduler would work (Unity game logic works just like this).

We were also working on completing Mono's port to the PlayStation 3's native operating system (this is different than running Mono on Linux on the PS3: that already works, and it was used for developing CellDotNet, a JIT for the PS3's SPUs). Zoltan developed the static compiler for PowerPC and I did the platform support.

Mono can now run "Hello World" on the PS3 native OS. There are still lots of ins, lots of outs and lots of whathaveyous that need to be tied up before this fully works and before we are able to run PhyreEngine# on the PS3.

by Miguel de Icaza (miguel@gnome.org) at June 08, 2009 10:23 PM

IronPython URLs

Microsoft and Open Source

Microsoft has an antagonistic history with open source to say the least. With posturing on Linux and patents still being in the very recent past the Microsoft of today still has a schizophrenic mindset on the topic. This is hardly surprising; Microsoft has bet the shop on desktop software and its major products have open source competitors (Windows -> Linux, Office -> Open Office, Visual Studio -> SharpDevelop, Eclipse and a thousand others).

My experience of dealing with Microsoft and Microsoft employees has been very different, and very positive. IronPython is fully open source and was the first project to be released under Microsoft's OSI approved Ms-PL (Microsoft Public License). The members of the dynamic languages team that I have had dealings with understand open source and are committed to it; hardly surprising given that the project was established by Jim Hugunin a longstanding member of the Python community.

Despite this the IronPython development process is shackled with some lawyer imposed restrictions. Community members can't contribute to the project, IronPython developers can't look at the source code of Python itself and IronPython can't submit code changes or fixes back to Python or its standard library. It is only recently that we have had public commit messages on checkins to the public repository and that the Python standard library has been included with IronPython. The team still aren't able to modify the standard library for better compatibility with IronPython though; neither do they publish the internal tests they use on IronPython. These restrictions slow down and hamper IronPython development but it is still a fantastic project for those of us using Python on the .NET framework.

These restrictions come from Microsoft paranoia. In the past they have purchased code from other companies and when it turned out that the code wasn't legally owned by the people selling it they naturally sued Microsoft rather than the company that sold it to them. This has cost them many millions of dollars, so perhaps a measure of paranoia is understandable.

These issues are all understood by the dynamic languages team, and they are an important part of pushing forwards Microsoft's involvement in open source. Harry Pierson (IronPython Program Manager) has just done a presentation on this very topic in the Presentation Idol competition, and has written up his presentation as a blog entry:
Microsoft and Open Source are often portrayed as enemies. But in DevDiv, we have several high profile Open Source projects. I work on IronPython, which has been Open Source for over four years. More recently, the ASP.NET and Extensibility Framework teams have decided to release some projects as Open Source.

I believe we should have more Open Source projects at Microsoft. But more importantly, I feel that we need to go beyond the textbook definition of Open Source. Our Open Source projects are typically closed to external contributions. But for the ecosystem at large, Open Source isn’t just about the availability and distribution terms of the source code. It also implies a collaborative development model - parties working together across organizational boundaries, contributing directly to projects in question.

The thing I would most like to change about Microsoft would be to let members of our ecosystem contribute code to our Open Source projects.


by Michael Foord (noreply@blogger.com) at June 08, 2009 01:40 PM

IronPython URLs

iLove Sharepoint Reads IronPython in Action and Announces IronSharepoint

Christian Glessner is head of development at Data One and a Sharepoint expert. Even before IronPython in Action came out he was experimenting with integrating IronPython with Sharepoint and he has now enthusiastically reviewed the book with this in mind:
IronPython In Action covers all you need to get started with IronPython for a .NET or Python developer. It is written coherently without needless ballast, well suited to the philosophy of the language itself. My favorite chapters are “Silverlight: IronPython in the browser”, “Agile testing where dynamic typing shines” and “Embedding the IronPython engine”. The book has inspired me to found the CodePlex project IronSharePoint (coming soon) showing how you can develop SharePoint apps with IronPython. I’m convinced that in the near future dynamic languages will get more attention again, just think of the “dynamic” keyword in C# 4.0. Absolutely worth keeping an eye on it!


by Michael Foord (noreply@blogger.com) at June 08, 2009 01:16 PM

June 07, 2009

IronPython URLs

A Good Mix 9: Cookbook recipes, articles and examples

Another selection of articles on IronPython from the last few weeks.
Saveen Reedy has a problem finding IronPython. More to the point he has an issue reliably finding the installed location when using both 32bit and 64bit versions of Windows (which have different standard install locations).
A short blog entry demonstrating how IronPython integrates with the .NET framework by creating a simple GUI with Windows Forms and the interactive interpreter. The steps are virtually the same as I use when demoing IronPython to a .NET crowd.
This one is a bit meta, but still useful. It's a recipe I put on the IronPython cookbook and shows a 'slightly-different-from-the-usual' way to integrate C# with IronPython. It shows how you can use C# to programmatically create Python modules for use from IronPython.
Scott Hanselman has been playing with IronPython and .NET 4.0. He had some odd errors caused by old versions of the IronPython assemblies floating around. This blog entry of his is on using the Fusion Log Viewer to track down the problem.
Here's an example of how a tiny bit of digging saved me hours of confusion recently when I hit an unusual edge case. I was doing a build of sample that was showing C# interop-ing with IronPython, but I was using a daily build of .NET 4 and a random build of IronPython.

I made a mistake and had some really old DLLs floating around that I shouldn't have had. My symptom was a FileNotFoundException for the file "System.Dynamic.dll." I KNEW it was in the GAC (Global Assembly Cache) and I could SEE it as a reference DLL in my directory. Can't find the file? Dude, it's right there!
Yet another person discovers how easy it is to use IronPython to interact with .NET assemblies and classes. He also likes IronPython in Action which is nice.
A Codeplex project that has been around for a while but I hadn't seen before. Someone has ported the ZedGraph charting library examples from C# to IronPython.


by Michael Foord (noreply@blogger.com) at June 07, 2009 09:38 PM

IronPython URLs

IronPython at Resolver Systems

These videos are from presentations my colleagues Jonathan Tartley and Giles Thomas did for Skills Matter in London. Inexplicably they are filed under Erlang on the Skills Matter website.
Jonathan Hartley, a developer at Resolver Systems talks about IronPython, and how it is used at Resolver Systems.

Resolver Systems's first product, Resolver One, is a desktop and web-accessible spreadsheet aimed primarily at the financial services market. It is written entirely in IronPython, and directly exposes end-users to Python, both as expressions in cell formulae, and as an embedded scripting language which provides programmatic access to spreadsheet content.

Resolver One launched in Spring of 2008, by which time the team had grown to fourteen people, and the codebase to 40k lines of product and 140k lines of tests. Here is an article by Jonathan about use of IronPython at Resolver Systems.
At the same event my boss, Giles Thomas, spoke about founding a startup:
Giles Thomas shares the story of founding Resolver Systems and answers questions about the company. Resolver Systems was founded in 2005 to produce a next generation spreadsheet. The founders, Giles Thomas, Robert Smithson and Patrick Kemmis, had all struggled with the challenges of running multi-million or multi-billion dollar businesses through poorly debugged spreadsheets. Their solution - Resolver One - seamlessly integrates a powerful and flexible programming language (IronPython) and a traditional spreadsheet environment. Resolver One is used by companies in the financial, oil exploration and pharmaceutical industries and in academia.


by Michael Foord (noreply@blogger.com) at June 07, 2009 07:07 PM

June 06, 2009

IronPython URLs

IronPython Is it a dead parrot or does it fly?

"IronPython Is it a dead parrot or does it fly?" is the question asked by Mike James in an article in VSJ. It covers Python the language, .NET interop, and an example of using the WPF (Windows Presentation Foundation) GUI library from IronPython.
Python is one of the increasingly trendy dynamic languages and it is now available under the .NET umbrella. IronPython is an open source version of the language developed by Guido van Rossum in 1990. Python has a great many users and they are all passionate about the language and mostly about Monty Python as well. Yes, there are lots of Pythonesque (as in the well-known TV series) references in the Python world, but it is a very serious language as well! It currently runs on most platforms, and IronPython extends this range to .NET and Silverlight.

Why bother?
Python may be free and it may be a high quality language but so is C#. Why bother with a strangely named language that you probably haven’t heard very much about? One good reason is that it is an interactive object-oriented language that has managed to take the good ideas from many other languages and meld them together into something workable. If you have looked at early versions of IronPython, now is a good time to take another look because version 2.0 has just been released and this is based on the new Dynamic Language Runtime (DLR) which all of the .NET dynamic languages should be using quite soon. The DLR is an extension to the CLR designed to make it easy to implement dynamic languages. The best argument for Python, however, is to use it – so let’s get started.


by Michael Foord (noreply@blogger.com) at June 06, 2009 05:57 PM

IronPython URLs

SharpDevelop: Exploring and Debugging IronPython Code

Matt Ward is the maintainer of the IronPython support in SharpDevelop, a .NET IDE for Windows. His latest entry takes us through the IronPython debugger built into SharpDevelop. This was built using the techniques explored by Harry Pierson in writing his IronPython debugger. Crucial to debugging IronPython is "Just My Code" support (so you don't have to wade through the Dynamic Language Runtime internals when you want to step through Python code) - and this is the name of the feature in SharpDevelop.
Ensure that the Just My Code feature is checked and that the Step over code without symbols is not checked. If the Step over code without symbols option is selected then stepping will not work properly and lines of code will be skipped over.

There are two ways to debug your code. You can use the Python menu or modify the project options. We will look at both of these alternatives. First open your IronPython project into SharpDevelop. Open your main file and make sure it is the active text editor window. Set a breakpoint somewhere in your code. Then from the Python menu select Run...
Darell Hawley is a Microsoft C# MVP with an interest in IronPython. With the new IronPython support in SharpDevelop 3.1 he's been giving it a spin and blogged his initial impressions:
  • SharpDevelop is an open source IDE for the .NET platform. Is it new? Hardly. Based on the history of news releases from their website, It’s been around since December of 2000. Considering that the .NET platform was publicly announced only 6 months earlier, SharpDevelop seems only that much more mature.
  • If you’re comfortable with the basics of Visual Studio, SharpDevelop should feel like home to you. In fact, the best way to describe SharpDevelop is “Visual Studio without a lot of stuff I don’t want and a few third-party items I do”.
  • SharpDevelop uses NUnit instead of MSTest. That’s right. No third party plugins to make your IDE work with NUnit. It simply works.
  • It’s time for me to confess. It’s all about IronPython. The reason I started investigating SharpDevelop is because of my frustration with Visual Studio’s lack of support for the language. Specifically, I want Intellisense when I write IronPython. To be sure, you only get Intellisense for “non-DLR code”, but surprisingly that doesn’t seem to be as much of a handicap as you might think.
  • Speaking of first class citizens, SharpDevelop comes stock with C#, Visual Basic, Boo (I can hear Jay Wren cheering now), IronPython and F# (now a number of SRT folks are cheering).
  • If you’re frightened of the consequences that may come from changing your development environment, don’t be. You can open one of your existing Visual Studio solutions with SharpDevelop and start coding. Switching back is as simple as opening up your now modified project/solution in Visual Studio.

  • by Michael Foord (noreply@blogger.com) at June 06, 2009 05:49 PM

    June 05, 2009

    IronPython URLs

    .NET Module Testing with IronPython

    One of the areas where dynamic languages particularly shine is testing. There is a whole chapter of IronPython in Action on the subject (chapter 7 which is free to download and is a great introduction to unittest and testing topics for both Python and IronPython).

    The .NET world is starting to realise this, and a new MSDN article by Dr. James McCaffrey explores both 'ad-hoc' testing with the interactive interpreter and writing your own test harness in IronPython for automated testing of .NET classes and libraries. (Personally I think he would have found it much easier to use unittest, but as you can see from the article even writing a custom test harness can be done in very little code with Python.)
    The Python scripting language has features that make it an excellent choice for performing several types of software testing. There are several implementations of Python available including CPython, the most common implementation on machines running UNIX-like operating systems, and IronPython, an implementation released in late 2006 that targets the Microsoft .NET Framework. In this month's column I'll demonstrate how to use IronPython to test .NET-based modules from both the Python command line and in lightweight Python scripts.


    by Michael Foord (noreply@blogger.com) at June 05, 2009 08:30 PM

    IronPython URLs

    Methodist: Make .NET Reflector come alive with IronPython

    No, not a reference to a once dynamic spiritual movement that is now largely part of the institutionalised church, but a new plugin for .NET Reflector.

    Reflector is a tool for exploring and disassembling .NET libraries. From binary assemblies it will show you all the classes and their members including the relationships between them. It will also disassemble them back into C# or VB.NET source code; invaluable for understanding the behavior of objects but a nightmare if you feel the need to protect your source.

    Ben Hall, UK MVP, C# expert and dynamic languages enthusiast has created a plugin for Reflector which makes it even more useful. Part of the power of dynamic languages is how easy they make exploration from the interactive environment. Ben has brought this to Reflector by embedding an IronPython interpreter (REPL). Whilst you are looking at the available methods and their arguments and return values you can actually instantiate classes and use them from the interpreter.

    As well as being a useful tool the source code is another good example of embedding IronPython into a .NET application (plus how to write a Reflector plugin of course). In this article Ben explains how to use the tool and how it works under the hood.
    It is great to be able to inspect the contents of an assembly with .NET Reflector, but to really understand the behaviour of code, it is nice to be able to call methods and see the results immediately within .NET Reflector. Now you can, thanks to the magic of IronPython and the DLR. Ben builds a REPL add-in for .NET Reflector and makes a great tool even more useful.


    by Michael Foord (noreply@blogger.com) at June 05, 2009 08:22 PM

    Aaron Marten's WebLog

    Pkgdef and the Experimental Instance in VS 2010

    ***Disclaimer: This information is about Visual Studio 2010 Beta 1 only. The following may not be accurate for future releases.***

    One of the new features we introduced with the Visual Studio 2008 Isolated Shell was the concept of a pkgdef file. Pkgdef is essentially a REG file with tokenization. For example, you could put $RootFolder$ in your pkgdef file to refer to the root directory of your isolated shell application. At runtime, these files are consumed by the VS Isolated Shell runtime and merged into the registry (with the tokens replaced by literal values). The registry merely acts as a cache of the information in your pkgdef files.

    In Visual Studio 2010, the pkgdef model has been integrated into Visual Studio itself. As such, the manner in which your packages are built and (locally) deployed when developing with the Visual Studio 2010 SDK Beta 1 is significantly different (although the “F5 experience” should be the same).

    Visual Studio Startup / Pkgdef Merge

    On the very first launch of Visual Studio, the first thing that needs to happen is merging the pkgdef files into the registry. You can think of the destination registry key where these go as merely a cache used for performance. The fact that it’s a registry key is somewhat of an implementation detail. Here’s a graphical view of what happens:

    PkgDef-Normal

    Note in the above diagram that the cache location is under KHEY_CURRENT_USER, and that the key name is 10.0_Config. If you view this key in regedit, you’ll notice a sibling key named simply “10.0”. This 10.0 key holds your per-user settings (things like your personal preferences for fonts, window position, and other options).

    In comparison to Visual Studio 2008 and running with the /ranu switch, these 10.0 and 10.0_Config keys map to the UserSettings and Configuration keys under HKCU\Software\Microsoft\VisualStudio\9.0 respectively.

    It is a completely safe operation to delete the HKCU\…\10.0_Config key since Visual Studio will re-create it on the next launch.

    “Experimental Instance” Startup / Pkgdef Merge

    A very similar process happens when you run “devenv /rootsuffix Exp”. Instead of merging the pkgdef information to “10.0_Config”, everything is merged to “10.0Exp_Config”:

    PkgDef-Experimental

    What are the “Pkgdef Files on Disk” locations?

    There is a file called “devenv.pkgdef” in your VS installation folder (under Common7\IDE) that defines where pkgdef files are picked up from. First, pkgdef files are picked up from a few sub-folders under Common7\IDE. Secondly, you’ll notice that we scan a folder called “$AppDataLocalFolder$\Extensions”. On my user account this maps to:

    C:\Users\aaronm\AppData\Local\Microsoft\VisualStudio\10.0\Extensions

    When running with “/rootsuffix Exp” this would be:

    C:\Users\aaronm\AppData\Local\Microsoft\VisualStudio\10.0Exp\Extensions

    In order for a pkgdef flie in the per-user location to be picked up by VS, it must also be declared as owned by a VSIX-based extension and enabled in HKCU\Microsoft\VisualStudio\10.0\ExtensionManager\EnabledExtensions. When you build a VSPackage or MEF component from one of the project templates in the Visual Studio 2010 Beta 1 SDK, this is all happening for you during the build.

    by aaronmar at June 05, 2009 03:42 PM

    ASP.NET for IronPython

    A T4 based approach to creating ASP.NET MVC strongly typed helpers

    Earlier this week, I wrote a post on using a BuildProvider to create ActionLink helpers .  That approach was using CodeDom to generate the code, and there was quite some user interest in it (and Phil blogged it , which helped!). Then yesterday, I wrote a post on the Pros and Cons of using CodeDom vs T4 templates for source code generation .  They are drastically different approaches, and while both have their strengths, T4 has definitely been getting more buzz lately. The logical follow-up to those two posts is a discussion on using T4 templates to generate MVC strongly typed helpers.  The general idea here is to use the existing ASP.NET extensibility points (BuildProvider and ControlBuilder), but rely on T4 templates to produce...(read more)

    by David Ebbo's blog : ASP.NET at June 05, 2009 06:52 AM

    June 04, 2009

    Miguel de Icaza

    Developing Cross Platform application with MonoDevelop

    Yesterday Lluis announced the last missing piece from our strategy to make MonoDevelop a full cross-platform IDE: MonoDevelop now runs on Windows as well:

    When we started the planning for MonoDevelop 2.2, the major goal of that release was to get feature parity on Linux, MacOS and Windows.

    We want to grow the community of developers that contribute to MonoDevelop and we wanted to attract add-in developers that wanted to bring their IDE extensions to all three platforms.

    MonoDevelop has recently been getting some nice community contributed plugins like Flash/Flex development support, Vala language support, Mono debugger for OSX (thanks to the nice folks at Unity for this!), VI editing mode and of course our own Silverlight and ASP.NET MVC add-ins.

    My theory is that supporting MonoDevelop on all the three major operating systems will have a multiplication effect in terms of contributions to MonoDevelop: it will help both users and will enable developers that extend MonoDevelop with add-ins to reach more users.

    I secretly want Unity to adopt MonoDevelop as the code editor for Unity; for the FlashDevelop guys on Windows to adopt MonoDevelop as their cross-platform foundation (their users want a cross platform Flashdevelop); for Flashbang to bring their UnityScript framework to MonoDevelop

    Developing an add-in for MonoDevelop now brings your enhancements to a much larger community.

    Look and Feel

    Although the IDE is built using Gtk#, but we are aware that developers want to get things integrated with their operating system as much as possible. This is why we have invested in properly integrating MonoDevelop with the Mac and Windows.

    The Look of MonoDevelop still has a heavy feel of the Linux Gtk+, but we are bluring the lines by making the theme and style match the operating system. Development in Gtk native themes will also continue to improve things.

    Feel wise, we make MonoDevelop follow the conventions of the host platform. For example, on the Mac, MonoDevelop uses the Mac system menu, it uses an entirely different keybinding style that follows what every Mac developer expects (Command-KEY operations that match X-Code for example) and even text selection in the editor behaves differently:

    More work will come, because we want MonoDevelop to feel native on each platform.

    On Windows for example, MonoDevelop runs on top of the .NET Framework and uses the .NET managed debugger instead of using Mono's runtime and Mono's debugger, so there is no dependency on Mono to be installed on the system.

    by Miguel de Icaza (miguel@gnome.org) at June 04, 2009 11:32 PM

    IronPython URLs

    Running KirbyBase in IronPython

    KirbyBase has a small but warm place in my heart as the first database I ever used in an application. It is a pure-Python single module database that stores its data in plain-text delimited files and has a Pythonic query syntax. Sure you don't want to run a high volume website with it but it is fun to use and experiment with.

    Krishna Bhargav has been using it from IronPython and has written up a blog entry on how to get it working with IronPython 2.6:
    As I was looking for embedded database systems, I came across this pure python database called KirbyBase. So I decided that I would make it run on IronPython. So this post describes on how to make KirbyBase run on IronPython and using ipy.exe. Note that I am not looking at integrating this database into C# application yet. [may be in the future post]
    Using Python libraries from C# is an interesting topic (covered briefly in IronPython in Action of course) which I don't think enough people have experimented with. The need is to create a statically-typed wrapper layer which the C# can use and handles calling into Python and returning values.

    In particular I'd like to see a C# wrapper using Ironclad, so that Numpy can be used from C#. There don't seem to be any open source libraries for .NET that are anything like as comprehensive.

    There is also Curt Hagenlocher's Coils project which (if completed) could automatically generate the wrapper classes from Python class definitions.


    by Michael Foord (noreply@blogger.com) at June 04, 2009 12:40 PM

    IronPython URLs

    An Australian, a Frenchman and an American read IronPython in Action

    In the last couple of weeks three new reviews of IronPython in Action have gone online, and by reviewers from three different continents.

    The first is from Tarn Barford who is an Australian .NET programmer with an interest in IronPython. He has blogged and presented about IronPython, and now he has reviewed IronPython in Action:
    IronPython in Action is a fantastic resource for anyone learning IronPython and for anyone wondering what this dynamic language IronPython is all about and whether they should learn it. It feels nicely balanced for both .NET users looking to learn about IronPython, and for Python users looking to learn about IronPython on .NET.

    I prefer software books that have plenty of discussion and can be read from start to finish otherwise I end up skipping through chapters I never go back too. I found this book well written and fun to read with interesting insight all the way through. There is enough about the python language and .NET to get you through the book, and rather than being a reference book it instead provides information on how to learn more.
    Matt Brucher is a French Python programmer with an interest in scientific computing. His review (in English) describes the contents of the book which I think he liked:
    IronPython is the first dynamic language developed for the .Net platform. At first, .Net didn’t support this kind of language. This is something that keeps on coming back throughout the book: you have to use some additional tricks to unleash the power of .Net dynamic and static languages.

    As a conclusion, those who need a dynamic language (to script an application) can go for IronPython, the first dynamic language for the .Net framework, compatible with the language Python 2.5, and in that case, go for this book that will help you for anything.
    The final review of this trio is by the token American Scott Koon, who is a well known .NET developer under his nom-de-blog Lazycoder:
    I’ve always wanted to use Python more but it’s difficult because the .NET Framework is such a walled garden in terms of interoperability with other programming languages. Mostly I use it to write little one off scripts when I want to move a bunch of files around or parse some text. I was really excited when Manning asked to to review IronPython in Action because I wanted to dive a little deeper into Python and possibly use it in some web applications. “IronPython in Action” makes it easy to get started using IronPython right away.

    Chapter 7 discusses agile testing and unit testing using IronPython. I almost dropped the book in amazement. Unit testing is almost never mentioned in any language book and is relegated to a niche or advanced topic. Find a book about any other .NET language that mentions unit testing that doesn’t have the word “testing” in the title. This alone sets the quality of this book far above other language books I have read. It’s not just enough, in my opinion, to discuss the syntax of the language. You have to teach the reader how to use the language in your everyday work.

    My overall feeling about this book is that it’s a great book. The authors use the same humor and dry wit that Python is known for to great effect. Making the digestion of a very different language easier. I’m sure that as I continue to experiment with IronPython that I’ll keep this book close at hand.

    My favourite quote from all these reviews is from Scott's: "If anything exposes the cruel, unnecessary complexity of .NET, it’s got to be a Winforms app." Actually I quite like Windows Forms, but it's still a good quote.


    by Michael Foord (noreply@blogger.com) at June 04, 2009 12:29 PM

    June 03, 2009

    IronPython URLs

    Davy's IronPython Editor 00.01.71 Released

    In a recent entry I listed some of the editors and IDEs you can use with IronPython, but I missed one off the list: Davy's IronPython Editor.

    This is an IDE for IronPython written in IronPython and is the creation of Davy Mitchell. It comes in installable and mobile versions and the latest release is version 00.01.71.
    Nearly 2 months on since the last release and the project has changed a lot and whilst not a massive update, I seriously recommend this upgrade. Thanks to the IronPython mailing list for support, suggestions and inspiration. Like any other project out there, I am desperate for feedback :-) Also if you have any new ideas for the future, let me know.

    DIE has had about 400 downloads since launch. With blossoming interest in IronPython, (partly, I suspect, due to IronPython in Action) hopefully it will hit the 1000 mark soon! So pop along and download.

    Here's the detail in what has changed in 00.01.70:
    • Mobile Version which stores options in same dir.
    • Installed version stores in User Profile. (Existing Settings files don't transfer over - sorry).
    • 'Find in Files' feature added.
    • Much much Improved Capture of output from running Python scripts.
    • Click on error output now opens file and goes to line.
    • Resources - MSDN links area now low bandwith versions, Python links and Powershell launch menu.
    • Added CheckBox and Listbox control to gen_GUI.
    • Syntax Box -Exposed new property to get Caret Screen position.
    • Autocomplete option added - default to OFF. Experimental parsing for strings, lists and dictionaries.
    • Bug fixes and performance updates.


    by Michael Foord (noreply@blogger.com) at June 03, 2009 09:30 PM

    IronPython URLs

    A Good Mix 8: Python 101, Regular Expressions, Silverlight, IronRuby and More

    The Coding Geekette is a Python and .NET developer who has spoken on IronPython at many developer conferences including PyCon. Her next adventure is teaching .NET developers Python in Cleveland:
    What: "Python 101 for the .NET Developer" with Sarah Dutkiewicz, Cleveland C#/VB.NET SIG

    When: Tuesday, June 23, 6:30-8:30pm

    Where: Beacon Place Conference Center, Beacon Place Office Building, 6055 Rockside Woods Blvd, Lower Level, Independence, OH 44131
    This blog entry (non-English) shows two interactive sessions using the System.Text.RegularExpressions.Regex class; performing the same task from both IronPython (2.6 beta) and IronRuby (0.4). The interactive interpreter is a great environment for experimenting, and the sessions ably demonstrate this.

    Of course you could also achieve the same thing with the Python re module.

    This is true of many things in IronPython, file and path handling or threading being two more examples; you have the choice of whether to do things the Python way or the .NET way. Whether you use the Python standard library or .NET framework libraries depends on which you are more familiar with, whether you need the code to be portable across implementations or whether one of the alternatives more closely matches what you need to achieve.
    IronPython has been designed to make it easy to embed in .NET applications. With code evaluated and executed at runtime it opens up all sorts of possibilities for user scripting of applications, storing rules as text that can be created and modified at runtime and so on. Hosting IronPython in Silverlight is slightly different from desktop .NET applications. Although the hosting API is the same there is some initial configuration that needs to be done.

    I've updated my article on the topic to include the configuration needed for IronPython code to import from other Python files contained in the xap file, plus adding references to the standard .NET / Silverlight assemblies.
    An O'Reilly Radar article. James Turner interviews Eric Schuman about how Microsoft tests user experiences on its websites. Notable for this quote:
    JT: Microsoft has done a lot of work providing dynamic language support through projects through IronRuby and IronPython. Do those technologies find any traction internally?

    ES: Oh, yeah, actually. I think it depends a lot on what group you're in. Like in the research teams, they tend to be used more than the product teams that I've been on. But there's definitely -- we're all geeks, you know? You get geeks and you get neat technologies and the geeks will try and use them. So I know that Iron Python, I know quite a few people who've experimented with it for everything from build tools to little data analysis tools.
    IronRuby in Action is a book being written for Manning Publications by Ivan Porto Carrero. About half the book is complete and available through the Manning Early Access Program. Jan Van Ryswyck has posted a review of the book so far...
    Moonlight 2, the Mono port of the Silverlight 2 browser plugin for Linux, is making great progress. Preview 3 is out now and can run my IronPython web-IDE example. You can now script the browser with Python on Windows, Mac OS X and Linux.


    by Michael Foord (noreply@blogger.com) at June 03, 2009 08:56 PM

    ASP.NET for IronPython

    CodeDom vs T4: two approaches to Code Generation

    There are many scenarios where the need to generate source code arises.  The MVC helpers I introduced in my last post is one such example.  Note that I am focusing on generating source code here, and not on scenarios where you may want to generate IL directly (which certainly do exist as well, but it’s a difference discussion). To perform the code generation, there are several different approaches that can be used.  The most simplistic one is to use a plain StringBuilder and write whatever code you want to it.  It’s rather primitive, but for simple scenarios, it just might be good enough. For more complex scenarios there are two widely different approaches that I will be discussing here: CodeDom and T4 templates.  Let...(read more)

    by David Ebbo's blog : ASP.NET at June 03, 2009 07:53 PM

    June 02, 2009

    Dave Fugate (Testing IronPython)

    Umm...

    IronPython most definitely should not be able to spawn an error message box that's visible when Vista is locked at the username/password screen:


    Quite annoying yet very interesting at the same time...

    June 02, 2009 11:42 PM

    IronPython URLs

    NWSGI Release and Django on IronPython

    Jeff Hardy certainly keeps himself busy. First of all he has done a new release of NWSGI:
    NWSGI 1.1 Preview 2 is exactly the same as Preview 1, except linked against IronPython 2.6 Beta 1. NWSGI is an implementation of the WSGI specification (Web Server Gateway Interface) for IronPython. It is implemented as an ASP.NET HttpHandler and is supported on the IIS 6 / 7 webservers (or any ASP.NET capable server). NWSGI allows the integration of Python applications like Trac and Django with existing ASP.NET facilities such as caching, sessions, and user management.
    NWSGI isn't quite sufficient to get Django running with IronPython. To remedy this Jeff has a project hosted on bitbucket (Mercurial version control repository) with patches to support Django on IronPython.
    On a casual glance the patches look pretty unobtrusive although I don't know how many of the Django tests pass on IronPython. It would be an important milestone to finally have Django working fully on IronPython.


    by Michael Foord (noreply@blogger.com) at June 02, 2009 11:07 PM

    IronPython URLs

    How to install IronPython 2 with Mono on Ubuntu

    IronPython has been included with Mono for quite some time. The versions included are the last releases of the FePy project (IronPython Community Edition), which are a stable version of IronPython 1 and an alpha version of IronPython 2 - both very old.

    In the FePy status update Seo Sanghyeon (FePy maintainer) explains the difficulty of compiling the latest stable version of IronPython with Mono. It is easier to compile IronPython 2.6 (the up and coming version), so hopefully we will see a new release of FePy - along with an update in Mono - when this is released later this year.

    In the meantime the latest binary versions of IronPython released by Microsoft work with recent versions of Mono (although they need a terminal with a dark background). In this post Ali Afashar explains exactly what you need to do to get a cooperating version of IronPython and Mono working on Ubuntu.
    This is just an instructional post with the hope that it might help others in the future.

    I spent a long time trying to get IronPython2 running on Mono. Now IronPython1 ships with Ubuntu, so
    apt-get install ironpython
    , if that's all that you want. Ironically, I don't really know the difference between IronPython1 and IronPython2, but "2 has got to be better than 1", right?

    The good news is that its very possible, but you will have to step out of your comfort zones.

    You will need: Mono 2.4 (sources) and IronPython 2.0.1 (binary)


    by Michael Foord (noreply@blogger.com) at June 02, 2009 11:05 PM

    ASP.NET for IronPython

    A BuildProvider to simplify your ASP.NET MVC Action Links

    Update : Please see this newer post for the latest and greatest MVC T4 template   One downside of using Html.ActionLink in your views is that it is late bound.  e.g. say you write something like this: <% = Html.ActionLink( "Home" , "Index" , "Home" ) %> The second parameter is the Action name, and the third is the Controller name.  Note how they are both specified as plain strings.  This means that if you rename either your Controller or Action, you will not catch the issue until you actually run your code and try to click on the link. Now let’s take the case where you Action takes parameters, e.g.: public ActionResult Test( int id, string name) { return View(); } Now your ActionLink calls...(read more)

    by Angle Bracket Percent : ASP.NET at June 02, 2009 01:41 AM

    June 01, 2009

    IronPython URLs

    Getting started with IronPython - Part 3: unit testing

    This is the third part of Dror Helper's series on getting started with IronPython. Part 1 was on first steps, including useful references. Part 2 focused on the Python programming language, introducing an example game project that Dror is using to learn IronPython. As promised part 3 is on testing the game with the Python unittest module.
    Being a TDD’er (Test Driven Developer) one of the first things I’ve searched for when I started learning IronPython is a unit testing framework, luckily for me I didn’t need to search too long.

    IronPython has a good unit testing framework inherited from Python called PyUnit.

    Writing unit tests using PyUnit is simple:
    1. import unittest class
    2. Create a class that inherits unittest.TestCase (test fixture)
    3. Write test methods using assertions methods


    by Michael Foord (noreply@blogger.com) at June 01, 2009 10:32 PM

    IronPython URLs

    Dynamic Languages at TechEd 2009

    TechEd 2009 (Microsoft developer conference) is come and gone, but dynamic languages played a bigger part there than ever before and John Lam (IronRuby commander in chief) has blogged about his presentation.

    He has been working on interesting twists on the REPL; the Read-Eval-Print-Loop otherwise known as the interactive interpreter. He demonstrates one that can switch between DLR based languages (IronPython and IronRuby) and is an editor as well.

    The story for dynamic languages in Visual Studio is not massively impressive, but you can get good results with Wing or Netbeans, SharpDevelop has excellent IronPython support and there is also the editor built into the very interesting Pyjama Project.

    With the Microsoft dynamic languages team getting interested in editors perhaps the future is brighter for a supported Microsoft IDE for IronPython and IronRuby?
    Dynamic languages on .NET are picking up momentum at this year's TechEd. Your typical TechEd attendee is a mainstream .NET developer, since this conference focuses on technologies that are shipping today (as opposed to futures conferences like the PDC). To speak more to this crowd, I focused on how they can make their existing .NET apps better by mixing in some end-user scripting.

    My talk was DTL332 if you're a TechEd attendee (not sure when/if the videos will open up to the general public). I showed how you can add Ruby and Python scripting to an existing app, and spent some time building some simple REPLs. Toward the end of the talk, I showed a more realistic scenario where I embed a REPL in an existing Open Source .NET application: Witty.

    During the demo, I showed off a twist on the traditional REPL - one where the editor and the REPL are one and the same. To run code in this REPL, you select the code that you want to run, and the output appears immediately below the selection. Since the REPL is just an editor, you can just delete any output that you don't want. History behaves just fine as well.


    by Michael Foord (noreply@blogger.com) at June 01, 2009 10:14 PM

    The Voidspace Techie Blog

    New in unittest: Test Discovery and the load_tests protocol for Python 2.7 and 3.2

    A feature that has long been missing from unittest, is automatic test discovery. This alone is a major reason why people move to alternative frameworks like nose and py.test. ... [663 words]

    June 01, 2009 12:00 PM

    The Voidspace Techie Blog

    New in unittest: Other Minor Changes

    There are a couple of other minor improvements to unittest that I haven't already mentioned. The TestResult class has two new methods: startTestRun and stopTestRun. ... [189 words]

    June 01, 2009 10:33 AM

    The Voidspace Techie Blog

    New in unittest: Cleaning up resources with addCleanup

    One of the new features in unittest for Python 2.7 / 3.1 is better support for resource deallocation through cleanup functions. This isn't a new idea, it's something that is already in use in the Bazaar, Twisted and Zope test frameworks. ... [308 words]

    June 01, 2009 12:06 AM

    May 31, 2009

    The Voidspace Techie Blog

    New in unittest in Python 2.7 and 3.1: Better Command Line Features

    One of the things I've been working on over the last few weeks is the Python unittest module. By virtue of having been included in the standard library for many years unittest is the most widely used Python testing framework. ... [397 words]

    May 31, 2009 11:13 PM

    May 30, 2009

    IronPython URLs

    Two Englishmen Named Tim Review IronPython in Action

    In the last couple of weeks two Englishmen called Tim have posted reviews of IronPython in Action.

    Tim Anderson is a technical writer who specialises in writing about Microsoft technologies. As well as writing for the Guardian he blogs regularly and has just reviewed IronPython in Action:
    It is aimed at Python programmers who do not know .NET, and .NET programmers who do not know Python, rather than at existing IronPython developers. The authors run through the basics of Python and its .NET integration, so that by the end of Part 1 you could write a simple Windows Forms application. Part 2 is on core development techniques and covers duck typing, model-view-controller basics, handling XML, unit and functional testing, and metaprogramming – this is where you generate and execute code at runtime.

    It’s a well-written book and fulfils its purpose nicely. I like the way the book is honest about areas where IronPython is more verbose or awkward than C# or VB.NET As someone who knows .NET well, but Python little, I could have done without all the introductory .NET explanations, but I understand why they are there. I particularly liked part two, on core programming techniques, which is a thought-provoking read for any developer with an interest in dynamic languages.
    Tim Golden is a Windows Python guru. He is the author of the Python WMI module which interfaces Python to Windows Management Instrumentation. Tim's help was invaluable in writing the WMI section of the system administration chapter of IronPython in Action. This earns him a mention or two in the footnotes, a fact Tim notes in his review...
    By way of disclosure, I’m given a couple of blushingly generous footnote credits by Michael which naturally leave me feeling well-disposed towards the book as a whole. But even without those, I’d be giving it the thumbs-up.

    But the most important win, I think, is managing to write a book about IronPython, not about Python or .NET. Naturally there is an element of explanation involved in both directions when some feature is being introduced or compared. But for the most part you can refer to the appendices which give summaries of Python/.NET if an unfamiliar term arises. For me, this achievement is key to the success of a book like this.


    by Michael Foord (noreply@blogger.com) at May 30, 2009 02:34 PM

    May 29, 2009

    IronPython URLs

    A Good Mix 7: JScript, Silverlight, Pyke and more

    Another selection of IronPython and DLR related postings culled from the blogosphere in the last few weeks.
    Managed JScript is an implementation of Javascript built on the Dynamic Language Runtime that shipped with Silverlight. It was touted as being useful for porting Javascript client-side code to work with Silverlight. It was only ever released in binary form and hasn't been maintained. In this blog entry the Frugal Coder laments the situation:
    I'm a Developer, I build Web Applications, and have for well over a decade now, and I love Javascript. I find the DLR compelling, and really want to see the Javascript implementation treated like a first class citizen. Give me code, samples and howtos. I'm going down this path anyhow, and would rather not do it alone.
    Pyke is a very interesting looking Python project: "Pyke introduces a form of Logic Programming (inspired by Prolog) to the Python community by providing a knowledge-based inference engine (expert system) written in 100% Python."

    This blog entry goes through what it takes to get Pyke running on IronPython; running the towers of hanoi example.
    Python is fantastic for scripting and system administration tasks, but in the .NET world Powershell got there first. This blog entry has an interesting take on which you should use:
    Were it not for the fact that Powershell is as intuitive as Linear B, it would be game over. As it is, IronPython and IronRuby remain interesting alternatives. They make the scripting process far simpler, and the syntax is much closer to the type of programming language that DBAs are used to. They become even more attractive when one considers the versatility of the .NET Dynamic Language Runtime (DLR), which allows you to plug IronPython or IronRuby into your .NET applications, call C# methods and so on. Maybe, with these DLR-based languages, we really are moving closer to achieving the dream of all DBAs: one scripting language to do everything. However, your Sysamin will loathe them as he will be engrossed in the extended culture-shock of having to redo all his favourite scripts in Powershell.
    An IronPython presentation by Guiseppe Turitto:
    Last night (March 19th), I had the chance to give a speech about IronPython at the .NET users group New York. First thing, I have to say Thank You, to the .NET UG-NY leader’s, for the opportunity, and thank you to my fellows at the .NET UG-NY for attending.

    Anyway for all of those that ask me for a copy of the slides, you can get them here together with the source code for the demos.
    The obligatory non-English entry, this is a simple "Hello World" example using IronPython and XAML in Silverlight. It is great fun to program the browser in Python through Silverlight. I'm not a big fan of XAML (an XML dialect for describing user interfaces) but its ok if someone else does it... (Anything that can be done from XAML can be done from code - but there are occasions when the XAML is actually less verbose.)


    by Michael Foord (noreply@blogger.com) at May 29, 2009 11:59 PM

    IronPython URLs

    IronPython and the elmcity project: Together again

    Jon Udell has been using Azure (Microsoft's cloud platform) for a calendar project he calls elmcity. Initially he tried to use IronPython, but the security settings of Azure (medium trust only) made this impossible. He proceeded with the project in C#, but Azure can now be used with a full-trust environment so IronPython is back on the table...
    In the first installment of this elmcity+azure series my plan was to build an Azure-based calendar aggregator using IronPython. That turned out not to be possible at the time, because IronPython couldn’t run at full strength in Azure’s medium-trust environment. So I switched to C#, and have spent the past few months working in that language.

    It’s been a long while since I’ve worked intensively in a compiled and statically-typed language. But I love being contrarian. At a time when low ceremony languages are surging in popularity, I’m revisiting the realm of high ceremony. It’s been an enjoyable challenge, I’ve gotten good results, and it’s given me a chance to reflect in a more balanced way on the “ceremony vs. essence” dialogue.

    Meanwhile, Azure has moved forward. It now provides a full-trust environment. That means you can run PHP, which is interesting to a lot of folks, but it also means you can run IronPython, which is interesting to me.

    In this entry I’ll show you how I’m starting to integrate IronPython in the two main components of my Azure project: the web role that provides the (currently minimal) user interface, and the worker role that does calendar aggregation.


    by Michael Foord (noreply@blogger.com) at May 29, 2009 10:08 PM

    May 28, 2009

    IronPython URLs

    Python on the .NET Framework: There's more than one way to do it

    IronPython is written in C# and is an implementation of the Python programming language that runs natively on the .NET framework with full access to .NET libraries. It isn't however the only way of using Python with .NET. One disadvantage of IronPython is that unless you are using Ironclad you can't use Python C extensions with IronPython,

    One alternative is Python.NET. This is a version of CPython (the normal implementation of Python) which also has integration with the .NET framework. As you would expect you can use Python C extensions with Python.NET, but when you use .NET objects you aren't using them natively but are using a proxied or copied version instead.

    There is also a little known third option: PyPy.NET. PyPy is an extremely interesting project - it is both an interpreter compiler toolchain, allowing you to write interpreters for dynamic languages in a high level static language called RPython which is a subset of Python, and a Python interpreter written in RPython.

    The compiler toolchain supports compiling for a variety of backends - compiling interpreters to C (the native backend), Java byte-code and also IL (Intermediate Language the .NET bytecode). This means that a single implementation (sourcecode in RPython) can be maintained for all three platforms.

    A key feature of PyPy is that the toolchain can also generate and compile specialised JIT compilers for all three backends.

    The PyPy team recently blogged about two papers that have been accepted for the ICOOOLPS (Implementation, Compilation, Optimization of Object-Oriented Languages, Programs and Systems) conference. One of these is on the PyPy JIT for .NET:
    The relevant paper is "Faster than C#: efficient implementation of dynamic languages on .NET" (PDF) by Armin, Anto and Davide Ancona, who is Anto's Ph.D. advisor.
    "Faster than C#" is a deliberately misleading quote. It refers to PyPy's claim (still unproven except for specific benchmarks) that PyPy can be "Faster than C". Faster than C means faster than the C implementation of Python but also alludes to the PyPy team's conviction that dynamic languages need not be slower than statically typed languages like C...

    .NET already has a JIT, so it may seem odd for a .NET implementation of Python to also have a JIT. What it permits is for the language to emit efficient and typed bytecode that the .NET JIT is better able to optimise as machine code - a genuine double JITting! The paper does claim to demonstrate that with their approach code written in a dynamic language can run as fast, or faster, than the equivalent code in C#!

    The paper abstract describes this:
    The Common Language Infrastructure (CLI) is a virtual machine expressly designed for implementing statically typed languages as C#, therefore programs written in dynamically typed languages are typically much slower than C# when executed on .NET.

    Recent developments show that Just In Time (JIT) compilers can exploit runtime type information to generate quite efficient code. Unfortunately, writing a JIT compiler is far from being simple.

    In this paper we report our positive experience with automatic generation of JIT compilers as supported by the PyPy infrastructure, by focusing on JIT compilation for .NET.

    Following this approach, we have in fact added a second layer of JIT compilation, by allowing dynamic generation of more efficient .NET bytecode, which in turn can be compiled to machine code by the .NET JIT compiler.

    The main and novel contribution of this paper is to show that this two-layers JIT technique is effective, since programs written in dynamic languages can run on .NET as fast as (and in some cases even faster than) the equivalent C# programs.

    The practicality of the approach is demonstrated by showing some promising experiments done with benchmarks written in a simple dynamic language.
    Interestingly both Python.NET and PyPy.NET have copied IronPython in makingthe clr module the first point of integration with the Common Language Runtime and use the same syntax as IronPython for creating typed arrays and working with generics. This means that despite their differences code which uses .NET classes and features is 'somewhat portable' between all three implmentations.


    by Michael Foord (noreply@blogger.com) at May 28, 2009 01:15 PM

    IronPython URLs

    Using IronPython with Wing and Netbeans IDEs

    Any good Python IDE will work well as an IronPython IDE, but some specific integration helps. One very good option is SharpDevelop, which has recently gained some very sophisticated IronPython support.

    My favourite Python IDE is Wing, particularly for its autocomplete (intellisense) for Python and how easy it is to extend with new tools through its scripting API. Unfortunately Wing doesn't know about .NET types and so doesn't provide autocomplete when using them through IronPython. It does have a mechanism for teaching it about new libraries (generating interface files) which I modified to work with .NET libraries.
    This article has the PI (Python Interface) script for downloads with instructions on how to generate PI files for .NET assemblies / namespaces plus how to make them available for Wing. It also has an example extension script for Wing which launches the current file with the IronPython interpreter (with instructions on how to make it available to Wing and bind it to a key combination).
    I'm not the only one who has been experimenting with using IronPython with Python editors. Steve Gilham has been using Netbeans (the Java IDE by Sun which recently gained Python support) with IronPython:
    With the arrival of the IronPython 2.6 beta 1, with ctypes support, the IronPython 1.x only support in IronPython Studio really takes the IDE from a bit dated to seriously obsolescent.

    Now, I had tried to get IronPython 2.0 to talk with NetBeans, but hadn't immediately achieved success, so, with less motivation, had put that to one side. Perhaps for similar reasons, a recipe for this wasn't out on Google already -- but now I really needed to crack the problem, I wasn't going to let that earlier abject failure put me off...


    by Michael Foord (noreply@blogger.com) at May 28, 2009 12:22 PM

    May 27, 2009

    IronPython URLs

    Two New Releases: DLR 0.9.1 and IronPython 2.6 Beta ASP.NET Integration

    To go with the four releases of IronPython and IronRuby are two more new releases:
    A new source release of the DLR. This includes the Sympl sample language and can be built with Visual Studio 2008:
    This release has several design cleanups and final calls for the bits we’re shipping in CLR 4.0. This release is also consistent with Visual Studio’s Beta1 release in that these sources (with namespace tweaks) were used for parts of CLR 4.0. Documents have all been updated, and there is a new walkthrough document for an example language implementation on the DLR. The language, Sympl, has a C# and an IronPython implementation in the source tree, along with some example code written in Sympl. There are many one-off examples for Expression Trees node types that are in the DLR source tree now.
    This is an updated release for using IronPython with ASP.NET and is compatible with the recent IronPython 2.6 Beta 1 release. Amongst other things it fixes the problem of using IronPython with ASP.NET and .NET 3.5 which were present in the last release. For this reason it was a highly anticipated release. Part of the delay has been finding a Microsoft team to take responsibility for the integration. It was 'owned' by the ASP.NET team who showed little interest in maintaining it. The hope is to get authorization for a source release and including it in the main IronPython project. In the meantime Jimmy Schementi did the work for this build.
    This release is compatible with IronPython 2.6 Beta 1. Currently it does not include Language Services Support and project templates. To create a new IronPython ASP.NET WebForms project, simply copy the “examples\hello-webforms” to a new directory and rename the directory to your liking. A redistributed copy of IronPython 2.6 Beta 1 can be found in the “bin” directory; all files except Microsoft.Web.Scripting.dll, the IronPython ASP.NET integration, are from the IronPython 2.6 Beta 1 release.

    Included in this release are two WebForms examples that are written in IronPython: “hello-webforms” and “album-handler”, which can be found in the “examples” directory. “hello-webforms” is a simple web application that shows PostBack handling, and “album-handler” is a larger web application that creates a photo album from a directory of images and generates thumbnails for them on the fly.


    by Michael Foord (noreply@blogger.com) at May 27, 2009 01:40 PM

    May 26, 2009

    tech-michael

    Silverlight WCF Inner-Exceptions

    Found a quick and dirty way to do WCF exceptions in silverlight http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=silverlightws&DownloadId=3473 .  The problem is that it doesn’t do inner-exceptions.

    I changed the raw fault exception around a bit to get inner exceptions working.

     

        public static RawFaultException BuildRawFaultException(XmlDictionaryReader reader)
    {
    List<string> messages = new List<string>();
    List<string> stacktraces = new List<string>();
    while (reader.ReadToFollowing("Message"))
    {
    string message = reader.ReadElementContentAsString();
    string stackTrace = reader.ReadElementContentAsString("StackTrace", reader.NamespaceURI);
    messages.Add(message);
    stacktraces.Add(stackTrace);
    }
    RawFaultException e = null;
    for (int i = 0; i < messages.Count; i++)
    {
    if (e == null) { e = new RawFaultException(messages[i]) { stackTrace = stacktraces[i] }; }
    else { e = new RawFaultException(messages[i], e) { stackTrace = stacktraces[i] }; }
    }

    return e;

    }
    }

    by Michael (noreply@blogger.com) at May 26, 2009 11:59 PM

    Iron Curt

    DynamicDataTable, Part 2

    The next thing we want for our dynamic DataTable is to do calculations between one or more columns. Imagine (for instance) that you want to add two columns and store the result in a third. In C#, the client code might look like this:

    dynamic table = new DynamicDataTable(t);
    table.Foo = table.Bar + table.Baz;

    At build time, the second statement gets compiled into a series of four dynamic call sites, which we can describe in pseudo-code as follows:

    dynamic tmp1 = table.GetMember("Bar");
    dynamic tmp2 = table.GetMember("Baz");
    dynamic tmp3 = tmp1.BinaryOperation(OperationType.Add, tmp2);
    table.SetMember("Foo", tmp3)

    We’ve already defined GetMember and SetMember on our table, so all we need to do to make this work is to define BinaryOperation – at least for the “addition” operator. Right?

    Alas, it’s a little more involved. The BinaryOperation isn’t being performed against the table itself; rather, it’s being performed against the results of the GetMember operation. Our current implementation has GetMember returning a System.Array, and we have no way to define a new operation against this preexisting type – whether the operation is static or dynamic.

    What about extension methods?

    If we were using statically-defined types, we might be able to effectively “monkey patch” System.Array by defining extension methods for either System.Array itself or for the specialized array types that we’re interested in. Unfortunately, this won’t work for us here because extension methods are neither supported against dynamic types nor can they be used to define operators for C# or VB.

    (The first of these limitations is deliberate. Extension methods work at compile time because the compiler has direct access to the “using” statements which bring the methods you want into the local scope. There’s no obvious way to get the same information at runtime, which is when dynamic call sites are bound.)

    First implementation

    Our initial implementation will wrap the array we were originally returning and will add a CLS-compliant implementation of the “+” operator. We won’t derive this class from DynamicObject. Because our DynamicDataColumn will be typed to "dynamic", resolution of operator + will happen at runtime.

    How do we implement this operator? We can identify two different scenarios – adding a sequence of values (such as another column) to a column, and adding a constant to a column. In both cases, we’ll end up performing n additions, where n is the number of rows in the table. To perform the element-wise operation, we’ll simply cast the two values to “dynamic” and let the C# runtime binder do the work.

    Here’s the code:

        internal class DynamicDataColumn : IList {
            private readonly Array _data;
    
            internal DynamicDataColumn(Array data) {
                _data = data;
            }
            
            // IList implementation goes here
            
            public static DynamicDataColumn operator +(DynamicDataColumn left, IList right) {
                if (left.Count != right.Count) {
                    throw new ArgumentOutOfRangeException(
                        String.Format("Column length mismatch ({0} found, {1} expected)",
                            right.Count, left.Count)
                    );
                }
                object[] result = new object[left.Count];
                for (int i = 0; i < left.Count; i++) {
                    result[i] = (dynamic)left[i] + (dynamic)right[i];
                }
                return new DynamicDataColumn(result);
            }
    
            public static DynamicDataColumn operator +(DynamicDataColumn left, object right) {
                return left + new ConstantList(right, left.Count);
            }
        }

    (I’ve chosen to use IList instead of IEnumerable in order to simplify the code. In principle, we could create an overload for each. This would give us the flexibility of IEnumerable when we don’t have a more specific interface, while still letting us take advantage of IList.Count when we get an IList.)

    The exact same code can be used to implement other binary operators – both arithmetic operators like “-“, “*” and “/” and logical operators like “>” and “<” – simply by replacing the four instances of “+” in the code above with the appropriate substitute.

    Now we’ll need to change DynamicDataTable.TryGetMember so that it returns “new DynamicDataColumn(a)” instead of just Array “a”. Then - in conjunction with what we’ve done already - we’re able to write the following:

            public static void Main(string[] args) {
                DataTable table = CreateTable();
                dynamic t = new DynamicDataTable(table);
                t.Amount += 1.0;
                t.SmallerAmount = (1 + t.Amount) / 15.0;
                t.Average = (t.Amount + t.SmallerAmount) / 2;
                t.IsOkay = t.Average > 50
                t.Greeting = "Hello " + t.Name;
                // This line no longer works!
                // t.NewAmount = Apply(t.Amount, new Func<double, double>((x) => Math.Sqrt(x)));
                foreach (var r in t.Rows) {
                    System.Console.WriteLine("{0}, your status is {1}", r.Greeting, r.IsOkay);
                }
                System.Console.ReadLine();
            }

    This is pretty exciting! The statement “t.IsOkay = t.Average > 50” creates a new bool column on our table and sets its value based on a comparison between another column and a constant value – and it does so with syntax that is both clean and natural. So it looks like we’re done implementing arithmetic.

    The fly in the ointment

    Unfortunately, there are a few problems with this approach – some obvious, some subtle.

    1. Our code doesn’t currently handle the reverse sequence “t.Foo = x + t.Bar” – whether x is a single value or a non-DynamicDataColumn sequence. Changing this means that we need to create another two overloads per operator. And if we want to support both IList and IEnumerable sequences, we need a further two overloads. Six overloads times sixteen binary operators makes 96 methods to implement.
    2. Nearly all of these methods are basically boilerplate copies of the first ones that we created for “operator +”. It would be nice if we could combine the implementations because duplicated code is a frequent source of errors.
    3. Our original implementation let us do some interesting things with columns if we knew their type, because we were able to cast an array T[] into an IEnumerable<T>. In this first implementation of arithmetic operators, we can no longer cast columns to strongly-typed collections.
    4. The semantics we’re using for addition are those of our implementation language (C#) and not those of the language that is using the DynamicDataTable. We may not be able to do anything about this, but it would be nice to change it if possible.
    5. One potential problem is particularly hard to see, and it results from the way the C# compiler implements dynamic sites. The compiled code for “operator +” contains exactly one dynamic call site which is shared between all users of the method. This means that the sample code above will generate three rules into the site – for type pairs (double, double), (int, double) and (string, string). Generating many rules into a site will degrade that site’s performance. Three rules isn’t bad, but this code introduces the possibility of many more being created.

    But we do have working code now, so this is a good time to take a break. We’ll tackle some of these issues in the next installment. The current version of the source code can be downloaded from here.

    by curth at May 26, 2009 05:30 AM

    May 24, 2009

    Iron Curt

    DynamicDataTable, Part 1

    Let’s get started by doing “the simplest thing that could possibly work”.

        public class DynamicDataTable : DynamicObject {
            private readonly DataTable _table;
    
            public DynamicDataTable(DataTable table) {
                _table = table;
            }
        }

    For now, we’ll use a DataTable for the actual storage and a DynamicObject to provide an implementation of IDynamicMetaObjectProvider. What can we accomplish with this? Well, quite a lot, actually – in a very real sense, we’re only limited by our imagination.

    GetMember

    The first ability we want is to be able to extract a column out of the data table; given a DynamicDataTable “foo”, the expression “foo.Bar” should give us something enumerable that represents the data in the column. The DLR describes this operation as “get member”, and DLR-based languages implement a GetMemberBinder in order to bind a dynamic “get member” operation.

    DynamicObject makes it very easy for us to handle the GetMemberBinder. We simply override the virtual method TryGetMember and implement the behavior that we want. The binder has two properties: Name, which indicates the name of the member that is being bound, and IgnoreCase. You can reasonably expect that case-sensitive languages like C#, Ruby and Python will set IgnoreCase to false, while VB will set it to true.

            private DataColumn GetColumn(string name, bool ignoreCase) {
                if (!ignoreCase) {
                    return _table.Columns[name];
                }
                for (int i = 0; i < _table.Columns.Count; i++) {
                    if (_table.Columns[i].ColumnName.Equals(name, StringComparison.InvariantCultureIgnoreCase)) {
                        return _table.Columns[i];
                    }
                }
                return null;
            }
    
            public override bool TryGetMember(GetMemberBinder binder, out object result) {
                var c = _table.Columns[binder.Name];
                if (c == null) {
                    return base.TryGetMember(binder, out result);
                }
                var a = Array.CreateInstance(c.DataType, _table.Rows.Count);
                for (int i = 0; i < _table.Rows.Count; i++) {
                    a.SetValue(_table.Rows[i][c], i);
                }
                result = a;
                return true;
            }

    Here I’ve chosen to return an Array whose elements are typed identically to the column’s original data type. That’s because it’s very easy to create an Array of a particular type and to set its individual elements from the System.Objects that we can get from the DataRow.

    By factoring out GetColumn into a separate method, I’ve made it easy to change just this logic. We might want, for instance, to allow a symbol name like “hello_world” to match the column named “hello world”.

    Non-dynamic members

    What if I want to directly access other properties of the DataTable like the “Rows” DataRowCollection? The design of the DLR makes this easy. If you don’t handle a binding operation yourself, it’s possible to fall back to a default behavior implemented by the language-provided binder. And for VB, C#, Python and Ruby, the fallback behavior is to treat the object like a normal .NET object and to access its features via Reflection. That’s why it’s useful to call base.TryGetMember instead of throwing an exception when the column name can’t be found.

    So if we implement a trivial “Rows” property, a reference to DynamicDataTable.Rows will return DataTable.Rows even when the GetMember is performed dynamically at runtime (unless there actually is a column named “Rows”…).

            public DataRowCollection Rows {
                get { return _table.Rows; }
            }

    SetMember

    The next interesting thing we want to be able to do is to set a column on the DataTable whether or not it already exists. The DLR describes this operation as “set member”, and defines a corresponding SetMemberBinder to perform the binding operation. Like the GetMemberBinder, this class has two properties: Name and IgnoreCase.

    We want to be able to set the column either to a single repeated constant value or to a list of values. But there are lots of different lists we might like to support: for instance, lists, collections or even plain IEnumerables. Let’s make some decisions about the semantics of the SetMember operation on our type:

    • If the object’s type implements IEnumerable and the object isn’t a System.String, then we’ll treat it like an enumeration. Otherwise, we’ll treat it like a single value.
    • If it’s an IEnumerable<T> we’ll use the generic type as our DataType. For a plain IEnumerable, the DataType will be System.Object.
    • If the object does not implement IEnumerable (or the object is a System.String) then the DataType will be the object’s actual RuntimeType.

    For an enumeration, we’ll read items into a temporary array until we reach the number of rows in the table. If the enumeration ends before then, we’ll raise an error. If at that point, there are still additional items remaining in the enumeration, then we’ll also raise an error.

    The specific behavior of our implementation for each of these types isn’t very important. What is important is that we’ve identified all the types that we expect we might get, and have identified the logic we’re going to implement for those types. Now, on to the code!

            public override bool TrySetMember(SetMemberBinder binder, object value) {
                Type dataType;
                IEnumerable values = (value is string) ? null : (value as IEnumerable);
                bool rangeCheck = (values != null);
                
                if (values != null) {
                    dataType = GetGenericTypeOfArityOne(value.GetType(), typeof(IEnumerable<>)) ?? typeof(object);
                } else {
                    values = ConstantEnumerator(value);
                    dataType = (value != null) ? value.GetType() : typeof(object);
                }
                
                object[] data = new object[_table.Rows.Count];
                var nc = values.GetEnumerator();
                int rc = _table.Rows.Count;
                for (int i = 0; i < rc; i++) {
                    if (!nc.MoveNext()) {
                        throw new ArgumentException(String.Format("Only {0} values found ({1} needed)", i, rc));
                    }
                    data[i] = nc.Current;
                }
                if (rangeCheck && nc.MoveNext()) {
                    throw new ArgumentException(String.Format("More than {0} values found", rc));
                }
                
                var c = GetColumn(binder.Name, binder.IgnoreCase);
                if (c != null && c.DataType != dataType) {
                    _table.Columns.Remove(c);
                    c = null;
                }
                if (c == null) {
                    c = _table.Columns.Add(binder.Name, dataType);
                }
                
                for (int i = 0; i < rc; i++) {
                    _table.Rows[i][c] = data[i];
                }
                return true;
            }

    (GetGenericTypeOfArityOne and ConstantEnumerator are methods whose names are pretty self-explanatory – and whose implementations can be found in the downloadable source code).

    Armed with these two methods, our type now supports all of the operations we need to implement the sample program described in Part 0 of this series. A version of the complete source code can be downloaded this location.

    In Part 2, we’ll add the ability to perform numerical operations between columns. See you then!

    by curth at May 24, 2009 04:25 AM

    May 23, 2009

    IronPython URLs

    Python, Jython and IronPython Performance

    Robert Smallshire has been working on an implementation of BBC Basic written in IronPython.

    During development he has been disappointed with the performance of IronPython, in fact he discovered that some of his code was running massively slower than the same code on either CPython (the native implementation of Python) or Jython (the implementation for the Java Virtual Machine).

    He posted a series of blog entries on this where he dug deeper into the problem and eventually, with the help of the IronPython team he found a solution. I've listed the blog entries in the order they were posted; what follows is a story of performance, impressive charts and an explanation:
    Significant claims have been made about the performance of IronPython, notably back at its inception in 2004 when Jim Hugunin, creator of both IronPython and its cousin Jython, presented a paper on IronPython performance at PyCon. Since then, there have been numerous claims to IronPython’s supremacy over CPython in the performance stakes. The IronPython Performance Report reiterates that IronPython can turn in a good performance. According to Hugunin the standard line we’ll see is,

    “IronPython is fast – up to 1.8x faster than CPython on the standard pystone benchmark.

    But do these claims stand up in the face of real-world Python code?

    The claims of good performance are based on synthetic micro-benchmarks which don’t accurately reflect balance of coding techniques found in complete programs.

    At this point I’d like to offer my own quote:

    “IronPython can be slow – 10x to 100x slower than CPython on real-world code and it has been observed to be up to 6000x slower.
    The blog entry features some of the aforementioned pretty charts illustrating the performance of the Owl Basic code on Jython, Python and IronPython. The IronPython code is running orders of magnitude slower. Jython fares remarkably well however.

    Naturally this doesn't match my experience of working with IronPython, but the story continues...
    In this entry Robert has found an isolated example that seems to demonstrate the performance problem; a simple test program which builds a simple binary tree of objects.

    The charts show that for small depths CPython outperforms Jython, but for deeper object graphs Jython scales better than CPython. IronPython seems to perform astonishingly badly from start to finish!

    In the comments Curt Hagenlocher (IronPython core developer) notes that changing the counter from updating a class variable to a global variable makes a slight difference to the performance of IronPython.
    The code Robert Smallshire was using to benchmark was updating a class variable as a counter. This is perfectly valid Python code, even idiomatic code. Unfortunately it triggered a code path in the IronPython implementation that could be described at best as "unfortunate". More on that shortly.

    When Robert updated his code following Curt's suggestion, the results were interesting:
    This made a phenomenal difference with IronPython completing in only 12% of the time taken by CPython – over 8× faster with a binary tree depth of 20.
    Dino Viehland (IronPython core developer) followed up with a blog post explaining the problem, and how they were fixing it in IronPython. The fix is now in place and will be in IronPython 2.6.
    Ahh, performance… It’s so much fun! It’s easy to measure and as you work on it you can see immediate benefits (or not!). I personally enjoy getting to spend time looking at interesting performance issues and I’ll use this as a time to plug IronPython 2.6 Beta 1 where we’ve continued our focus in this area. Even more fun yet is when you compare and contrast different implementations - it can be both surprising and amusing. Recently Robert Smallshire has been doing just that. Obviously Robert has found a case in IronPython where something is performing horribly. I’d like to take a look at what’s happening here and what we can do to improve this case.

    Ok, but let’s get onto the fun technical details! It all comes down to one line of code “Node.counter += 1”. That’s a pretty innocent looking piece of code, how can it cause so many problems? First you need to understand a little bit about how IronPython works. IronPython internally keeps versions of type objects and uses this information to generate optimal code paths for accessing those objects. So the next line of code in this example, “self._children = children” usually turns into something that’s like:

    if (self != null && self.GetType() == typeof(PyObject) && self.PythonType.Version == 42) {

    self._dict["_children"] = ;

    }

    What that one line of code causes then is for the version of the type to change and for this “rule” to be invalidated. So we’ll figure out what to do, generate a new cached rule, only to have it not work the next time around. The same thing applies to the calls to Node – we re-generate the “optimal” code again and again only to discover we have to throw it away.

    ...

    So you might be curious - what’s the fix? Well in this case we’re just mutating the type by changing a simple value stored in the type (versus say adding a property or a method to the type). Today we get a very slight throughput performance benefit because we can burn the value directly into the generated code instead of fetching it from the wrapper the type object keeps it in. With the fix we’ll burn the wrapper in and fetch the value from the wrapper each time. Then when we go and modify the type we just modify the wrapper instead of the type and its version is unchanged! This fix is now checked into the IronPython source tree and you can download the fixed sources right now.

    In conclusion I’d like to wrap up a little bit about our performance philosophy – performance is hard and deciding which numbers matter to you is important. We have tried to tune IronPython for apps which run for more than a fraction of a second. We have also tuned IronPython for code which is not constantly mutating types at runtime. And we’re always open to feedback when users encounter problems with IronPython and we’ll listen to what scenarios are important for them. But if you look at these graphs I think you can see that we’ve done a good job at making IronPython a fast implementation of Python.
    In short, if you find code where IronPython performs dramatically worse than CPython - it's a bug! Report it on the IronPython mailing list; Dino, Curt and team are very responsive.


    by Michael Foord (noreply@blogger.com) at May 23, 2009 01:52 PM

    IronPython URLs

    The Dynamic Keyword in C# 4.0

    The new dynamic keyword in C# 4.0 is made possible by including the Dynamic Language Runtime in the .NET framework. The DLR was originally part of the first implementation of IronPython and was abstracted out in order to create a framework for implementing dynamic languages on .NET.

    Further than that, the DLR has been used to introduce new features into C# and VB.NET, the static languages traditionally used to program .NET. This is seen as a major part of what is new in .NET 4.0.

    When Jim Hugunin went to work at Microsoft he wasn't employed to work specifically on IronPython; he joined the CLR (Common Language Runtime) architecture team with the brief of helping to make .NET a better runtime for dynamic languages. What follows is largely as the result of his influence and work.

    The full semantics of the dynamic keyword are laid out in the C# 4.0 language specification document.
    Note that this document is for the beta version of .NET 4.0. Although the details are not likely to change much it will inevitably be revised and edited for the final release.
    19. Introduction to C# 4.0
    The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples include
    • Objects from dynamic programming languages, such as Python or Ruby
    • COM objects accessed through IDispatch
    • Ordinary .NET types accessed through reflection
    • Objects with changing structure, such as HTML DOM objects
    While C# remains a statically typed language, we aim to vastly improve the interaction with such objects.

    Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the normal static binding of C# and instead gets resolved dynamically.
    20. Dynamic Binding
    Dynamic binding provides a unified approach to selecting operations dynamically. With dynamic binding developer does not need to worry about whether a given object comes from e.g. COM, IronPython, the HTML DOM or reflection; operations can uniformly be applied to it and the runtime will determine what those operations mean for that particular object.

    This affords enormous flexibility, and can greatly simplify the source code, but it does come with a significant drawback: Static typing is not maintained for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will an error occur if it was not so.

    C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:
    dynamic d = GetDynamicObject(…);
    d.M(7);
    C# allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.

    The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, the compiler allows implicit conversion of dynamic expressions to any type:
    dynamic d = 7; // statically bound implicit conversion
    int i = d; // dynamically bound implicit conversion
    Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations and constructors can be dispatched dynamically:
    dynamic d = GetDynamicObject(…);
    d.M(7); // calling methods
    d.M(x: “Hello”); // passing arguments by name
    d.f = d.P; // getting and setting fields and properties
    d[“one”] = d[“two”]; // getting and setting through indexers
    int i = d + 3; // calling operators
    string s = d(5,7); // invoking as a delegate
    C c = new C(d); // selecting constructors
    The role of the C# compiler is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is, given an actual object referenced by d. Think of it as deferring part of the compiler’s job to runtime.

    The result of most dynamic operations is itself of type dynamic. The exceptions are conversions and constructor invocations, both of which have a natural static type.

    At runtime a dynamic operation is resolved according to the nature of its target object d: If d implements the special interface IDynamicObject, d itself is asked to perform the operation. Thus by implementing IDynamicObject a type can completely redefine the meaning of dynamic operations. This is used intensively by dynamic programming languages such as IronPython and IronRuby to implement their own dynamic object models. It can also be used by APIs, e.g. to allow direct access to the object’s dynamic properties using property syntax.

    Otherwise d is treated a standard .NET object, and the operation will be resolved using reflection on its type and a C# “runtime binder” component which implements C#’s lookup and overload resolution semantics at runtime. The runtime binder is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was left for it by the static compiler.

    Assume the following code:
    dynamic d1 = new Foo();
    dynamic d2 = new Bar();
    string s;
    d1.M(s, d2, 3, null);
    Because the receiver of the call to M is dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to:
    “Perform an instance method call of M with the following arguments:
    • a string
    • a dynamic
    • a literal int 3
    • a literal object null”
    At runtime, assume that the actual type Foo of d1 does not implement IDynamicObject. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows:
    • Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2.
    • Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics.
    • If the method is found it is invoked; otherwise a runtime exception is thrown.
    20.1 The dynamic type
    The grammar is extended with the following type expression:
    type:
    ...
    dynamic
    The types dynamic and object are considered the same, and are semantically equivalent in every way except the following two cases:
    • Expressions of type dynamic can cause dynamic binding to occur in specific situations
    • Type inference algorithms as described in §7.4 will prefer dynamic over object if both are candidates
    This deep equivalence means for instance that:
    • There is an implicit identity conversion between object and dynamic
    • There is an implicit identity conversion between constructed types that differ only by dynamic versus object
    • Method signatures that differ only by dynamic versus object are considered the same
    • Like with object, there is an implicit conversion from every type (other than pointer types) to dynamic and an explicit conversion from dynamic to every such type.
    The type dynamic does not have a separate runtime representation from object – for instance the expression
    typeof(dynamic) == typeof(object)
    is true.

    An expression of the type dynamic is referred to as a dynamic expression.

    20.2 Dynamic binding
    The purpose of the dynamic type is to affect the way operations are selected by the compiler. The process of selecting which operation to apply based on the types of constituent expressions is referred to as binding.

    The following operations in C# are selected based on some form of binding:
    • Member access: e.M
    • Method invocation: e.M(e1,…,en)
    • Delegate invocaton: e(e1,…,en)
    • Element access: e[e1,…,en]
    • Constructor calls: new C(e1,…,en)
    • Overloaded unary operators: +, -, !, ~, ++, --, true, false
    • Overloaded binary operators: +, -, *, /, %, &, &&, |, ||, ??, ^, <<, >>, ==,!=, >, <, >=, <=
    • Compound assignment operators: +=, -=, etc.
    • Implicit and explicit conversions
    When dynamic expressions are not involved, C# always defaults to static binding, which means that the compile-time types of constituent expressions are used in the selection process. However, when one of the constituent expressions in the above listed operations is a dynamic expression, the operation is instead dynamically bound.

    20.3 Compile time semantics of dynamic binding
    An anonymous function cannot be used as a constituent value of a dynamically bound operation.

    A method group can only be a constituent value of a dynamically bound operation if it is immediately invoked.

    Other than that, a dynamically bound operation always succeeds at compile time, unless otherwise specified in the following.

    The static result type of most dynamically bound operations is dynamic. The only exceptions are:
    • Conversions, which has the static type that is being converted to
    • Constructor invocations which have the static type that is being constructed
    Most dynamically bound operations are classified as a value. The only exceptions are member accesses and element accesses, which are classified as variables. However, they can not be used as arguments to ref or out parameters.

    20.3.1 Static binding with dynamic arguments
    In certain cases if enough is known statically, the above operations will not lead to dynamic binding. This is the case for:
    • Element accesses where the static type of the receiver is an array type
    • Delegate invocations where the static type of the delegate is a delegate type
    In these cases the operation is resolved statically, instead implicitly converting dynamic arguments to their required type. Thus, the result type of such operations is statically known.

    20.3.2 Dynamic binding with a statically known candidate set
    For most dynamically bound operations the set of possible candidates for resolution is unknown at compile time. In certain cases, however the candidate set is known:
    • Static method calls with dynamic arguments
    • Instance method calls where the static type of the receiver is not dynamic
    • Indexer calls where the static type of the receiver is not dynamic
    • Constructor calls
    In these cases a limited compile time check is performed for each candidate to see if any of them could possibly apply at runtime. This check includes:
    • Checking that the candidate has the right name and arity
    • Performing a partial type inference to check that inferences do exist where not depending on arguments with the static type dynamic
    • Checking that any arguments not statically typed as dynamic match parameter types that are known at compile time
    If no candidate passes this test, a compile time error occurs.
    Extension methods are not considered candidates for instance method calls, because they are not available during runtime binding.

    20.3.3 Conversion to interface types
    In C# user defined conversions to interface types are not allowed. For performance purposes conversions of dynamic expressions to interface types are therefore statically rather than dynamically bound. This does have a slight semantic effect, because a dynamic object (i.e. an object whose runtime type implements IDynamicObject) could have given other meaning to the conversion, had it been dynamically bound.

    In foreach and using statements (§20.3.4 and §20.3.5), expansions may do dynamic casts to interfaces even though that cannot be done directly from source code.

    20.3.4 Dynamic collections in foreach statements
    If the collection expression of a foreach statement (§8.8.4) has the static type dynamic, then the collection type is System.IEnumerable, the enumerator type is the interface System.Collections.IEnumerator, and the element type is object.

    Furthermore the cast that is part of the foreach expansion is bound dynamically, not statically as is otherwise the case for interface types (§20.3.3). This enables dynamic objects to participate in a foreach loop even if they do not implement the IEnumerable interface directly.

    20.3.5 Dynamic resources in using statements
    A using statement (§8.13) is allowed to have a dynamic expression as the resource acquisition. More specifically, if the form of resource-acquisition is expression and the type of the expression is dynamic, or if the form of resource-acquisition is local-variable-declaration and the type of the local-variable-declaration is dynamic, then the using statement is allowed.

    In this case, the conversion of the expression or local variables to IDisposible occurs before the body of the using statement is executed, to ensure that the conversion does in fact succeed. Furthermore the conversion is bound dynamically, not statically as is otherwise the case for conversion of dynamic to interface types (§20.3.3). This enables dynamic objects to participate in a using statement even if they do not implement the IDisposable interface directly.

    A using statement of the form
    using (expression) statement
    where the type of expression is dynamic, is expanded as:
    { IDisposable __d = (IDisposable)expression // as a dynamic cast
    try {
    statement;
    }
    finally {
    if (__d != null) __d.Dispose();
    }
    }
    A using statement of the form
    using (dynamic resource = expression) statement
    is expanded as:
    {
    dynamic resource = expression;
    IDisposable __d = (IDisposable)resource // as a dynamic cast
    try {
    statement;
    }
    finally {
    if (__d != null) __d.Dispose();
    }
    }
    In either expansion, the resource variable is read-only and the __d variable is invisible in the embedded statement. Also, as already mentioned, the cast to IDisposable is bound dynamically.

    20.3.6 Compound operators
    Compound operators x binop= y are bound as if expanded to the form x = x binop y, but both the binop and assignment operations, if bound dynamically, are specially marked as coming from a compound assignment.

    At runtime if all the following are true:
    • x is of the form d.X where d is of type dynamic
    • the runtime type of d declares X to have type T or T? where T is a primitive type
    • the result of x binop y has the runtime type S where S is a primitive type
    • S and T are either both integral types (sbyte, byte, short, ushort, int, uint, long or ulong) or both floating point types (float or double)
    • S is implicitly convertible to T
    Then the result of x binop y is explicitly converted to T before being assigned. This is to mimic the corresponding behavior of statically bound compound assignments, which will explicitly convert the result of a primitive binop to the type of the left hand side variable (§7.16.2).
    For dynamically bound += and -= the compiler will emit a call to check dynamically whether the left hand side of the += or -= operator is an event. If so, the dynamic operation will be resolved as an event subscription or unsubscription instead of through the expansion above.

    20.4 Runtime semantics of dynamic binding
    Unless specified otherwise in the following, dynamic binding is performed at runtime and generally proceeds as follows:
    • If the receiver is a dynamic object – i.e., implements an implementation-specific interface that we shall refer to as IDynamicObject – the object itself programmatically defines the resolution of the operations performed on it.
    • Otherwise the operation gets resolved at runtime in the same way as it would have at compile time, using the runtime type of any constituent value statically typed as dynamic and the compile time type of any other constituent value.
      • If a constituent value derives from a literal, the dynamic binding is able to take that into account. For instance, some conversions are available only on literals.
      • If a constituent value of static type dynamic has the runtime value null, it will be treated as if the literal null was used.
      • Extension method invocations will not be considered – the set of available extension methods at the site of the call is not preserved for the runtime binding to use.
    • If the runtime binding of the operation succeeds, the operation is immediately performed,otherwise a runtime error occurs.
    In reality the runtime binder will make heavy use of caching techniques in order to avoid the performance overhead of binding on each call. However, the observed behavior is the same as described here.

    The rest of the document covers the other features in C# 4.0: Named and Optional Arguments, COM Interoperability, and Co- and Contravariance. Particularly COM Interoperability also makes use of dynamic:
    COM methods are often designed for a language environment that is more dynamic than C#. This means that they will often return weakly typed results, and rely on the calling language to dynamically look up further operations on those results.


    by Michael Foord (noreply@blogger.com) at May 23, 2009 01:19 PM

    The Voidspace Techie Blog

    EuroPython: Coming Soon

    EuroPython is the official community conference for Python Programmers across Europe. This year it is being held in the Birmingham Conservatoire, where previous UK Python events and some recent UKUUG events have been held. ... [227 words]

    May 23, 2009 01:05 PM

    May 22, 2009

    Dino Viehland

    On Performance

    Ahh, performance…  It’s so much fun!  It’s easy to measure and as you work on it you can see immediate benefits (or not!).  I personally enjoy getting to spend time looking at interesting performance issues and I’ll use this as a time to plug IronPython 2.6 Beta 1 where we’ve continued our focus in this area.  Even more fun yet is when you compare and contrast different implementations - it can be both surprising and amusing.  Recently Robert Smallshire has been doing just that: http://www.smallshire.org.uk/sufficientlysmall/2009/05/22/ironpython-2-0-and-jython-2-5-performance-compared-to-python-2-5/ Obviously Robert has found a case in IronPython where something is performing horribly.  I’d like to take a look at what’s happening here and what we can do to improve this case. 

    But before I look at what’s going on here I’d like to briefly say we love to hear feedback from users of IronPython.  We’ve have a mailing list you can join and give us your feedback on and bugs can be reported on our website.  We track both of these very closely and respond as quickly as we can – which is usually pretty fast.  I just mention that because it’s easier for us to improve IronPython when people let us know about a problem vs. us having to scour the web to find issues.  Hopefully this piqued interest will have more people trying out IronPython and giving us feedback.

    Ok, but let’s get onto the fun technical details!  It all comes down to one line of code “Node.counter += 1”.  That’s a pretty innocent looking piece of code, how can it cause so many problems?  First you need to understand a little bit about how IronPython works.  IronPython internally keeps versions of type objects and uses this information to generate optimal code paths for accessing those objects.  So the next line of code in this example, “self._children = children” usually turns into something that’s like:

    if (self != null && self.GetType() == typeof(PyObject) && self.PythonType.Version == 42) {

         self._dict["_children"] = <new value>;

    }

    What that one line of code causes then is for the version of the type to change and for this “rule” to be invalidated.  So we’ll figure out what to do, generate a new cached rule, only to have it not work the next time around.  The same thing applies to the calls to Node – we re-generate the “optimal” code again and again only to discover we have to throw it away.

    So that sounds pretty bad but if you’re familiar with Python’s member access rules you’ll quickly recognize that this will be much faster than needing to do the resolution again and again.  That involves looking through the class hierarchy to see if we have any data descriptors or classes defining __setattr__ and it's nice to avoid all of that work.   So to get the best performance we require for the world to settle down and not be continuously changing.  We’re well aware of this problem with our implementation and we have continued to focus on improving it.  IronPython 2.0 already includes one mitigation so that we don’t need to continuously generate new code – instead we effectively patch new values into an existing piece of code.  In our IronPython 2.6 branch we’ve continued to improve performance here and significantly reduced the expense when things get mutated.  But it turns out that there’s an easy fix for this particular problem we’ve just never thought it that important of a problem to solve.

    One of the amusing things about this is we’ve actually seen it before – Resolver Systems was having some performance issues with Resolver One  which is their advanced spreadsheet which is written in IronPython.  One of those issues turned to be a type which they both used frequently and mutated frequently.  This actually doesn’t seem to be a common idiom in Python code which is the reason we’ve never optimized for it before.  In this case though it turned out that they had found an optimization that improved performance on IronPython 1.0 but was destroying perf on IronPython 2.0!  For Resolver fixing this was a simple change for them to no longer mutate types.  Even if you really want to use a type as a property bag you can always move that to a type which you aren’t creating instances of and executing methods on.

    With all that in mind let’s look at some numbers.  Here I’ve compared IronPython 2.01, IronPython 2.6 Beta 1, CPython 2.6 plus IronPython 2.6 with a fix for this issue.

    Perf Comparison

     

    Like Robert’s charts I have tree size in number of nodes across the bottom and execution time in seconds across the top and the execution times are logarithmic.  We can see the abysmal performance of 2.0.1, we can see that 2.6B1 has already made significant improvements, and with IronPython 2.6B1 plus a fix for this specific issue we actually beat CPython as the number of iterations scales up.

    But there’s another way we can look at this – instead of fixing IronPython let’s look what happens if we fix the benchmark to avoid this performance pitfall.   To do this I’ve replaced the mutation of the class with a global variable.  When running against all of the same implementations again I get these results:

    perf 2

     

    Here you can see that all 3 versions of IronPython are performing about the same and are coming in significantly faster than CPython as the number of iterations goes up.  These are now also matching the numbers Robert is getting when he has made the same change.

    So you might be curious - what’s the fix?  Well in this case we’re just mutating the type by changing a simple value stored in the type (versus say adding a property or a method to the type).  Today we get a very slight throughput performance benefit because we can burn the value directly into the generated code instead of fetching it from the wrapper the type object keeps it in.  With the fix we’ll burn the wrapper in and fetch the value from the wrapper each time.  Then when we go and modify the type we just modify the wrapper instead of the type and its version is unchanged!  This fix is now checked into the IronPython source tree and you can download the fixed sources right now. 

    In conclusion I’d like to wrap up a little bit about our performance philosophy – performance is hard and deciding which numbers matter to you is important.  We have tried to tune IronPython for apps which run for more than a fraction of a second.  We have also tuned IronPython for code which is not constantly mutating types at runtime.  And we’re always open to feedback when users encounter problems with IronPython and we’ll listen to what scenarios are important for them.  But if you look at these graphs I think you can see that we’ve done a good job at making IronPython a fast implementation of Python.

     

    by DinoViehland at May 22, 2009 09:23 PM

    IronPython URLs

    IronPython and IronRuby: Four New Releases

    There have been four new releases of IronPython and IronRuby; two new ones for each project.

    The first pair of releases are for the CTP (Community Technology Preview) of .NET 4.0 Beta 1. Part of the Dynamic Language Runtime is included in .NET 4 and on top of this is built one of the major new features of C# 4.0 and VB.NET 10; the dynamic keyword. dynamic is a new static type and informs the compiler that operations on dynamic objects should be performed at runtime rather than bound at compile time. In particular this makes late bound COM and interacting with objects from DLR languages much more pleasant. It also enables true duck typing (in fact dynamic typing) in these traditionally statically compiled languages.

    To go alongside the .NET 4.0 CTP are new releases of IronPython and IronRuby, targetting the same version of the DLR included the CTP.
    This is our second preview of IronRuby running under the Dynamic Language Runtime that is built directly into a .NET 4.0 release! As before, this release allows you to use IronRuby objects and types as .NET 4.0 dynamic objects from within C# and Visual Basic code. These binaries are roughly equivalent to the functionality found in IronRuby 0.3. Please also note that the IronRuby CTP for .NET 4.0 Beta 1 will run only under .NET 4.0 Beta 1.
    We’re quite pleased to announce the release of IronPython 2.6 CTP for .NET 4.0 Beta 1. This is our second preview of IronPython running under the Dynamic Language Runtime that is built directly into a .NET 4.0 release! As before, this release allows you to use IronPython objects and types as .NET 4.0 dynamic objects from within C# and Visual Basic code. While this release does share a bit in common with the upcoming IronPython 2.6 Beta 1 release (e.g., a number of MSI improvements), the core functionality is essentially that of IronPython 2.6 Alpha 1. Please also note that IronPython 2.6 CTP for .NET 4.0 Beta 1 will run only under .NET 4.0 Beta 1.
    This walkthrough shows how the new Dynamic feature in C# 4.0 and Visual Basic 10.0 enables the natural use of object models that expect their host language to provide dynamic dispatch. This capability is demonstrated for an IronPython scenario of accessing libraries that are written for the Python language. Note that more advanced IronPython scenarios that involve hosting your own scripts with access to your application’s object model are beyond the scope of this walkthrough.

    Notes:
    • Using Dynamic with Office programming is demonstrated in the Office Programmability walkthrough.
    • Using Dynamic with Silverlight will be shown in a later preview release of Visual Studio 2010.

    More importantly (for those using IronPython and IronRuby) we have also had new released with new functionality. The IronPython release is the first beta of IronPython 2.6 and targets compatibility with Python 2.6. As well as new features from Python 2.6 it also includes important new features like ctypes and Python stack frame (sys._getframe) support.
    Staying true to our "Conference-driven development schedule," this release is in conjunction with RailsConf '09, where IronRuby was demonstrated running real Rails applications and deploying them on IIS. A ton of work has been done in this release to get real Ruby programs running well, like RubyGems, Rake, Sinatra, and Rails.
    We’re pleased to announce the release of IronPython 2.6 Beta 1. As you might imagine, this release is all about supporting new CPython 2.6 features such as the ‘bytes’ and ‘bytearray’ types (PEP 3112), decorators for classes (PEP 3129), advanced string formatting (PEP 3101), etc and as such includes nearly all of the new Python 2.6 features. The small number of remaining features will be implemented for Beta 2. The minimum .NET version required for this release is the same as IronPython 2.0; namely .NET 2.0 Service Pack 1.

    There’ve also been several new features added: ctypes, sys.getframe, pyc for pre-compilation, and improved help. Ctypes provides access to C-based APIs and provides a way for Python developers to optimize performance or access libraries that would otherwise be unavailable. sys.getframe is commonly used by Python programs to introspect the call stack and can now be enabled with the –X:Frames and –X:FullFrames command line options; for better compatibility with programs that check for the presence of sys.getframe it is now not available unless these options are provided. The pyc.py pre-compiler is now shipped with IronPython and is available in the Tools\Scripts directory. Finally the help of many builtin functions and types has been improved by including IronPython.xml and IronPython.Modules.xml.

    Another focus has been on improving startup time of large applications. This release accomplishes that through the adaptive compilation feature announced with 2.6 Alpha 1 and also includes many other enhancements to reduce the amount of code generation required to start applications. But only do these improvements help large applications but they also significantly speed up basic hello worlds startup time.

    There’s also a few minor changes since IronPython 2.0.1 that are worth calling out here:
    • Binaries are ngen’d for both 32-bit and 64-bit platforms on install by default
    • IronPython.msi now offers a little more selection with respect to what you’d like to install. For example, Silverlight templates are optional
    • The default installation location of IronPython.msi no longer indicates whether the 2.6 release is an Alpha, Beta, or a patched release. Future IronPython 2.6 installations will replace previous 2.6 releases which will be uninstalled automatically
    • The -X:PreferComInteropAssembly flag has been removed. All COM interop is now done through normal COM dispatch
    There are two big new features in this release. The first is our implementation of the ctypes module. The ctypes module is like P/Invoke for Python. It allows Python code to call into unmanaged DLL functions. Here, for example, I’m calling into the standard wprintf function from msvcrt.dll

    IronPython 2.6 Beta 1 (2.6.0.10) on .NET 2.0.50727.4918
    >>> import ctypes
    >>> libc = ctypes.cdll.msvcrt
    >>> ret = libc.wprintf("%s\n", "hello")
    hello

    Between ctypes and Ironclad, I think we’ll eventually be able to load most native Python extensions in IronPython. Woot!

    The other big new feature in this release is a real implementation of sys._getframe. _getframe lets you write code that inspects the Python callstack.
    IronPython 2.6 Beta 1 is the second IronPython release today! I'm happy to say that the sys._getframe issues of IronPython 2.6 Alpha 1 have been resolved, and we have re-added urllib.py and other modules dependent upon collections.py to the MSI installer. Man am I ever ready for the long weekend=)


    by Michael Foord (noreply@blogger.com) at May 22, 2009 02:17 PM

    Iron Curt

    DynamicDataTable, Part 0

    To commemorate the first beta release of the first CLR to contain the DLR, I’m going to try to implement something more interesting than useful – a dynamic version of the DataTable class. My goal is to show how the dynamic support in C#4 and VB10 can be used to create a better development experience, and to show how you can work effectively with IDynamicMetaObjectProvider.

    The BCL’s DataTable is already fairly dynamic; its columns can vary at runtime in type and name. You can even add and remove columns on-the-fly. As such, it’s a pretty good candidate for “dynamicizing”. Of course, we can’t actually modify the existing DataTable implementation, so I’ll start out by creating a wrapper for it using DynamicObject. Where I hope to end up is with a self-contained implementation that implements its own DynamicMetaObject rather than leaning on DynamicObject and DataTable.

    Here’s a sneak preview of Part 1:

        public static class Program {
            private static DataTable CreateTable() {
                DataTable table = new DataTable();
                table.Columns.Add("Name", typeof(string));
                table.Columns.Add("Value", typeof(int));
    
                table.Rows.Add("Bob", 23);
                table.Rows.Add("Karen", 17);
                table.Rows.Add("Allen", 10);
                table.Rows.Add("Grace", 31);
                return table;
            }
            public static void Main(string[] args) {
                DataTable table = CreateTable();
                dynamic t = new DynamicDataTable(table);
                t.NewName = t.Name;
                t.Name = "unknown";
                foreach (var r in t.NewName) {
                    System.Console.WriteLine(r);
                }
            }
        }

    See you again soon!

    by curth at May 22, 2009 05:01 AM

    Mike Stall

    Virtual code execution via IL interpretation

    As Soma announced, we just shipped VS2010 Beta1. This includes dump debugging support for managed code and a very cool bonus feature tucked in there that I’ll blog about today.

    Dump-debugging (aka post-mortem debugging) is very useful and a long-requested feature for managed code.  The downside is that with a dump-file, you don’t have a live process anymore, and so property-evaluation won’t work. That’s because property evaluation is implemented by hijacking a thread in the debuggee to run the function of interest, commonly a ToString() or property-getter. There’s no live thread to hijack in post-mortem debugging.

    We have a mitigation for that in VS2010. In addition to loading the dump file, we can also interpret the IL opcodes of the function and simulate execution to show the results in the debugger.

     

    Here, I’ll just blog about the end-user experience and some top-level points. I’ll save the technical drill down for future blogs.

    Consider the following sample:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    public class Point 
    {
        int m_x;
        int m_y;
        public Point(int x, int y)
        {
            m_x = x;
            m_y = y;
        }
        public override string ToString()
        {
            return String.Format("({0},{1})", this.X, this.Y);
        }
    
        public int X
        {
            get
            {
                return m_x;
            }
        }
        public int Y
        {
            get
            {
                return m_y;
            }
        }
    }
    
    public class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict[5] = "Five";
            dict[3] = "three";
    
            Point p = new Point(3, 4);
                    
        }
    
        public static int  Dot(Point p1, Point p2)
        {
            int r2 = p1.X * p2.X + p1.Y * p2.Y;
            return r2;
        }
    
    }
    
    
     

    Suppose you have a dump-file from a thread stopped at the end of Main() (See newly added menu item “Debug | Save Dump As …”; load dump-file via “File | Open | File …”).

    Normally, you could see the locals (dict, p) and their raw fields, but you wouldn’t be able to see the properties or ToString() values. So it would look something like this:

    image

    But with the interpreter, you can actually simulate execution. With the IL interpreter, here’s what it looks like in the watch window:

    image

    Which is exactly what you’d expect with live-debugging.  (In one sense, “everything still works like it worked before” is not a gratifying demo…)

    The ‘*’ after the values are indications that they came from the interpreter.  Note you still need to ensure that property-evaluation is enabled in “Tools | options | Debugging”:

    image

     

     

     

     

    How does it work?
    The Interpreter gets the raw IL opcodes via ICorDebug and then simulates execution of those opcodes. For example, when you inspect “p.X” in the watch window, the debugger can get the raw IL opcodes:

    .method public hidebysig specialname instance int32
            get_X() cil managed
    {
      // Code size       12 (0xc)
      .maxstack  1
      .locals init ([0] int32 CS$1$0000)
      IL_0000:  nop
      IL_0001:  ldarg.0
      IL_0002:  ldfld      int32 Point::m_x
      IL_0007:  stloc.0
      IL_0008:  br.s       IL_000a
      IL_000a:  ldloc.0
      IL_000b:  ret
    } // end of method Point::get_X

    And then translate that ldfld opcode into a ICorDebug field fetch the same way it would fetch “p.m_x”. The problem gets a lot harder then that (eg, how does it interpret a newobj instruction?) but that’s the basic idea.

     

    Other things it can interpret:

    The immediate window is also wired up to use the interpreter when dump-debugging. Here are some sample things that work. Again, note the ‘*’ means the results are in the interpreter and the debuggee is not modified.

    Simulating new objects:
    ? new Point(10,12).ToString()
    "(10,12)"*

    Basic reflection:
    ? typeof(Point).FullName
    "Point"*

    Dynamic method invocation:
    ? typeof(Point).GetMethod("get_X").Invoke(new Point(6,7), null)
    0x00000006*

    Calling functions, and even mixing debuggee data (the local variable ‘p’) with interpreter generated data (via the ‘new’ expression):
    ? Dot(p,new Point(10,20))
    110*

     

    It even works for Visualizers

    Notice that it can even load the Visualizer for the Dictionary (dict) and show you the contents as a pretty array view rather than just the raw view of buckets. Visualizers are their own dll,  and we can verify that the dll is not actually loaded into the debuggee. For example, the Dictionary visualizer dll is  Microsoft.VisualStudio.DebuggerVisualizers.dll, but that’s not in the module list:

    image

     

    That’s because the interpreter has virtualized loading the visualizer dll into its own “virtual interpreter” space and not the actual debuggee process space. That’s important because in a dump file, you can’t load a visualizer dll post-mortem.

     

     

    Other issues:

    There are lots of other details here that I’m skipping over, like:

    1. The interpreter is definitely not bullet proof. If it sees something it can’t interpreter (like a pinvoke or dangerous code), then it simply aborts the interpretation attempt.
    2. The intepreter is recursive, so it can handle functions that call other functions. (Notice that ToString call get_X.)
    3. How does it deal with side-effecting operations?
    4. How does it handle virtual dispatch call opcodes?
    5. How does it handle ecalls?
    6. How does it handle reflection

     

    Other advantages?

    There are other advantages of IL interpretation for function evaluation, mainly that it addresses the ”func-eval is evil” problems by essentially degenerating dangerous func-evals to safe field accesses.

    1. It is provably safe because it errs on the side of safety. The interpreter is completely non-invasive (it operates on a dump-file!).
    2. No accidentally executing dangerous code.
    3. Side-effect free func-evals. This is a natural consequence of it being non-invasive.
    4. Bullet proof func-eval abort.
    5. Bullet proof protection against recursive properties that stack-overflow.
    6. It allows func-eval to occur at places previously impossible, such as in dump-files, when the thread is in native code, retail code, or places where there is no thread to hijack.

    Closing thoughts

    We realize that the interpreter is definitely not perfect. That’s part of why we choose to have it active in dump-files but not replace func-eval in regular execution. For dump-file scenarios, it took something that would have been completely broken and made many things work. 

    by jmstall at May 22, 2009 12:10 AM

    May 21, 2009

    The Voidspace Techie Blog

    Python in Fifty Words

    Aahz, a long standing member of the Python community, is manning a Python booth at the OSCON Conference. With the help of the Python Advocacy mailing list he has come up with a description of Python in fifty words. ... [95 words]

    May 21, 2009 09:14 PM

    Aaron Marten's WebLog

    Visual Studio 2010 SDK Beta 1

    The Visual Studio 2010 SDK Beta 1 is now available for download. Be sure to check out the latest supplemental readme as you’re likely to encounter some of these issues in using the SDK.

    by aaronmar at May 21, 2009 05:04 PM

    Jimmy Schementi

    IronRuby 0.5 Released

    imageI’m pleased to announce a new release of IronRuby: IronRuby 0.5!

    .download_ironruby { color: white; padding: 10px; border: 3px solid gray; background-color: #333; display: block; font-size: 18px; text-decoration: none; font-weight: bold; text-align: center;margin: 20px 30px; } .download_ironruby:hover { background-color: #555; cursor: pointer; }Download IronRuby 0.5

    You can also check out the source code for this release

    Staying true to our "Conference-driven development schedule," this release is in conjunction with RailsConf '09, where IronRuby was demonstrated running real Rails applications and deploying them on IIS. A ton of work has been done in this release to get real Ruby programs running well, like RubyGems, Rake, Sinatra, and Rails.

    Read more about IronRuby at RailsConf here

    Special thanks to Daniele Alessandri, Jirapong Nanta, and Ray Vernagus, who contributed code during this release, and everyone else who has submitted bugs, updated the wikis, or built software on-top of IronRuby.

    Also, take a look at the IronRuby CTP for .NET 4.0 Beta 1, which has been released as part of Visual Studio 2010 Beta 1.

    What’s in the Release?

    A big language feature of this past release was adaptive compilation; the ability to start-up quicker with a fast interpreter, and then compile code that gets interpreted more than two times. This brought Rails startup time down from 89 seconds to 34 seconds, giving Rails approximately 2.5x quicker startup. Since this compiles “hot” code, your Rails application will get faster after an initial set of requests. There is a lot more to do for performance, but this was a great accomplishment.

    Here are some more interesting changes:

    • Removes ClrString. CLR strings are referred to as System::String
    • Removes IronRuby library. "require 'IronRuby'" is no longer needed; IronRuby module is now a built-in module.
    • Integer/Float operations for all CLR primitive numeric types
    • System::Char and System::String methods so that they behave like an immutable UTF-8 encoded string
    • Improves handling of BOM in 1.8 mode
    • Debugger visualizer for RubyObject so that VS will display the result of to_s in the Watch window.
    • Adds support for .NET operators (op_* special methods)
    • Implements bitwise operators on flag enums
    • Precompilation of simple Ruby method invocations
    • Improves performance for file IO#read method. Previously we were 10x slower than MRI, now we are approx. 1.5-times faster.
    • Tons of fixes to File, String, Array, and other built-in types to drive up RubySpec and Ruby application test-suite pass-rates.

    For detailed information, please see the CHANGELOG (which is much more verbose now. including all commit messages for the release … not just syncing to head of tfs)

    Bugs closed

    RubySpec status

    IronRuby passed the 80% mark on RubySpec during this release:

    image

    You can see more IronRuby statistics on http://ironruby.info.

    Also during this release IronRuby has been running other Ruby applications test-suites as part of individual developer tests and in continuous integration, such as RubyGems, Rails (including ActiveRecord, ActiveSupport, ActionPack), and Rake.

    Next Release

    The next release will push harder on application compatibility, especially Cucumber (which has been the most requested application), Rails, and all the other frameworks being tested currently.

    Also, the feature which makes IronRuby stand out, .NET integration, has next-to-no documentation, so that will large focus during this next release as well. Keep an eye on http://ironruby.net/Documentation/.NET, but as I said, is very sparse at the moment.

    In the meantime, please test out IronRuby 0.5 and let us know all the issues you find. Enjoy!

    by Jimmy Schementi (jschementi@gmail.com) at May 21, 2009 01:45 AM

    Jimmy Schementi

    IronRuby CTP for .NET 4.0 Beta 1

    We’re pleased to announce the release of the IronRuby CTP for .NET 4.0 Beta 1!

    Download IronRuby CTP for .NET 4.0 Beta 1

    This is our second preview of IronRuby running under the Dynamic Language Runtime that is built directly into a .NET 4.0 release! As before, this release allows you to use IronRuby objects and types as .NET 4.0 dynamic objects from within C# and Visual Basic code. These binaries are roughly equivalent to the functionality found in IronRuby 0.3. Please also note that the IronRuby CTP for .NET 4.0 Beta 1 will run only under .NET 4.0 Beta 1.

    This release also includes the binaries for the IronPython 2.6 CTP for .NET 4.0 Beta 1.

    To try out this preview release:

    1. Install some variant of .NET 4.0 Beta 1 or Visual Studio 2010 Beta 1 from here
    2. Download the release
    3. Follow any of the many dynamic walkthroughs online. Here would be a good start.

    Enjoy!

    by Jimmy Schementi (jschementi@gmail.com) at May 21, 2009 01:09 AM

    Harry Pierson

    IronPython 2.6 Beta 1

    In addition to the IronPython CTP for .NET Framework 4.0 Beta 1 I blogged about earlier, we also released the first beta of IronPython 2.6 today. How about that – two IronPython releases in one day! This is our second preview release as we work towards our 2.6 RTM in September. 2.6 Alpha 1 was released back in March.

    There are two big new features in this release. The first is our implementation of the ctypes module. The ctypes module is like P/Invoke for Python. It allows Python code to call into unmanaged DLL functions. Here, for example, I’m calling into the standard wprintf function from msvcrt.dll

    IronPython 2.6 Beta 1 (2.6.0.10) on .NET 2.0.50727.4918
    >>>  import  ctypes
    >>> libc = ctypes.cdll.msvcrt
    >>> ret = libc.wprintf("%s\n""hello")
    hello

    Between ctypes and Ironclad, I think we’ll eventually be able to load most native Python extensions in IronPython. Woot!

    The other big new feature in this release is a real implementation of sys._getframe. _getframe lets you write code that inspects the Python callstack. Previously, we supported _getframe only with a depth of zero which is to say you could inspect the current frame, but no others. Now, by default we don’t implement _getframe at all unless you pass in –X:Frames or –X:FullFrames on the command line. Removing the version of _getframe that only worked for depth zero fixes an issue with collections.py that broke much of the 2.6 standard library in IronPython 2.6 Alpha 1.

    The difference between Frames and FullFrames is in what is returned by frame.f_locals member. If you’re running with FullFrames, we hoist all local variables into the heap so they can be accessed by our frame walker. If you’re running with Frames, our ability to access locals up the stack is limited. Sometimes they are available - If you called locals() in a frame up the stack for example, then f_locals will be available – but usually not. There’s a performance difference between the default (i.e. no Frames), –X:Frames and –X:FullFrames, hence why we provide the user fine grained control over the Frame support.

    Our performance has gotten better relative to 2.6 Alpha 1. Our PyStone numbers have improved 80% from Alpha 1, similar to where we were in IronPython 2.0.1. We’ve also been able to cut our startup time about 25% from 2.0.1. We’re still an order of magnitude slower than CPython on startup, but we’re getting better. We’re significantly worse on PyBench than we were in 2.6 Alpha 1, but that’s primarily because there’s now a second exception test. As I described back in March, we get killed on the exceptions benchmarks – the two combine to consume nearly 62% of our total run time. Ouch!

    Finally, there are bug fixes. Of particular relevance to readers of this blog are a series of fixes that allow me to continue on with my __clrtype__ series. Watch for that soon.

    As I said back when we released Alpha 1, the release cycle on 2.6 will be much shorter than it was for 2.0. 2.0 had eight alphas, five betas and two release candidates over the course of around twenty months. We expect 2.6 to have one alpha, two betas and a release candidate over eight months. So please start trying using the beta as soon as you can so you can give us your feedback and we can fix your bugs!

    by Harry Pierson at May 21, 2009 12:30 AM

    May 20, 2009

    Dave Fugate (Testing IronPython)

    IronPython 2.6 Beta 1 released as well

    http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=25126

    IronPython 2.6 Beta 1 is the second IronPython release today!  I'm happy to say that the sys._getframe issues of IronPython 2.6 Alpha 1 have been resolved, and we have re-added urllib.py and other modules dependent upon collections.py to the MSI installer.  Man am I ever ready for the long weekend=)

    May 20, 2009 09:29 PM

    The Voidspace Techie Blog

    Fetching docstrings from objects: easy, right? (A painful exploration of the Python object model)

    Extraordinarily simple introspection is one of the features that makes dynamic languages like Python such a joy to work with. If you have code dealing with arbitrary objects and you want to discover and present information about those objects it is marvellously simple. ... [1862 words]

    May 20, 2009 08:51 PM

    Harry Pierson

    IronPython 2.6 CTP for .NET 4.0 Beta 1

    The .NET Framework 4.0 and Visual Studio 2010 Beta 1 is now generally available for download. Jason Zander has a very thorough rundown on some of the new features in this release. Of course, my favorite new features in VS2010 is the new dynamic language support in C# and Visual Basic, which let’s you easily call out to IronPython code from those languages.

    For anyone who wants to experiment with interoperating C# or VB with IronPython, we released IronPython 2.6 CTP for .NET 4.0 Beta 1 today. There’s also a walkthru showing how you can use the standard Python library module random from both C# and VB. Note, there’s currently a URL bug in that walkthru – it links to IronPython 2.6 Alpha 1 rather than the .NET 4.0 Beta 1 IronPython CTP. Make sure you pick up the right version of IronPython if you want to try out the walkthru. Looks like they fixed the redirect in the walkthru.

    FYI, this is a CTP quality release with about the same functionality as IronPython 2.6 Alpha 1.  Essentially, this is the version of IronPython that was in the source tree when the VS team branched for Beta 1.

    If you’ve got any feedback, please drop us a line on the mailing list.

    by Harry Pierson at May 20, 2009 06:54 PM

    Dave Fugate (Testing IronPython)