Contents

The IronPython Cookbook
This wiki contains useful example code for working with IronPython and the .NET framework.

The internet is already awash with quality examples of Python code, but .NET examples for IronPython are only just starting to arrive - so this will be the main focus of the recipes here.

For more information and resources, see the Useful Links page.

Adding Entries
If you want to add an entry, the easiest way is to add a link (in the relevant section) on this page, and then follow the link to create the new page. You will need to be logged in to edit pages, but setting up an account is easy.

If there isn't already an appropriate section, then add your link to Misc or create a new section.

If you need reminding about wiki markup format, there is a guide on the Help page. Or find an existing page on the wiki that looks like the one you want to make, click the Edit link and use that as a template.

Please note that for long examples and articles it is acceptable to link to external articles or blog entries. For shorter examples, please post them here on the Wiki.

All pages: http://www.ironpython.info/index.php/Special:AllPages

Core Concepts

 * IronPython
 * The DLR: Dynamic Language Runtime
 * The .NET Framework
 * Mono
 * Silverlight

For the people involved, see People in IronPython.

IronPython in Action


IronPython in Action is a book on IronPython, written by Michael Foord and Christian Muirhead for Manning Publications.

The first five chapters are an introduction to .NET, a Python tutorial, and then a walkthrough creating an example structured Python application.

The rest of the book covers working with various parts of the .NET framework (ASP, databases, web services, WPF, shell scripting, working with Windows and so on), getting deeper into Python (testing, protocols, metaclasses and so on) and also embedding and extending IronPython.

Chapters 1 and 7 are free to download:


 * IronPython in Action

Pro IronPython

 * Pro IronPython Book from APress (written by Alan Harris)

Getting Started

 * Getting Started with IronPython
 * Python for .NET Programmers
 * Interactive Interpreter
 * Using the Python Standard Library
 * Using .NET Framework Classes
 * Simple Python Examples - A set of very simple examples of Python syntax, illustrating constructs like conditionals, loops, functions and classes.
 * Typed Arrays in IronPython
 * Deployment - How to deploy IronPython scripts

If you are looking for an IDE or editor to use with IronPython then you will find this article helpful:


 * IronPython Tools & IDEs

It covers using IronPython with IronPython Studio, Visual Studio, SharpDevelop, the Wing IDE, Eclipse with PyDev and assorted other editors. It also looks at standard development tools for Python and IronPython.

.NET

 * File as TextReader - Wrapping Python files for use where .NET expects stream readers
 * Launching the Browser - Launch the default browser with a specific URL

Windows Forms

 * Hello World
 * Label & Button
 * Panels & Styles
 * The TextBox
 * CheckBox & RadioButton
 * Dock & Anchor
 * The Clipboard (and extending IronPython with C#)
 * BackgroundWorker Thread
 * TabControl, Splitter & PictureBox
 * Setting the Clipboard - Using Windows Forms to set the clipboard (and creating a Single Threaded Apartmentstate (STA) Thread).
 * A DataGridView with a Database as the DataSource - with textboxes to enter connection string and a query, you can view the results of any SQL query in a DataGridView (an example of data-binding). Also uses Fonts and the SystemMessageBox.
 * DataGridView Custom Formatting - loading data from IronPython data structure, custom highlighting of rows and columns, overriding default Windows selection format, autopasting of custom selection to Clipboard.
 * A DataBound ListBox - A ListBox bound to an ArrayList.
 * A Notify Icon - Two examples: one using a FileSystemWatcher to notify users of changes with a "pop-up balloon", and another more standard example.
 * Invoking onto the GUI (Control) Thread - interacting with the GUI from another thread or an asynchronous callback
 * Drag and Drop - dragging files onto a ListBox
 * SaveFileDialog - saving an image
 * Handling Unhandled Exceptions
 * Screen Capture
 * Progress Bar - A Windows Forms progress bar, updated from a calculation running in another thread.
 * Minimise WinForm To Sys Tray - Make your Windows Form Minimise to the System Tray in the taskbar.
 * A Fade in Window - Creating a form that fades in
 * MonthCalendar Control and datetime - Using a calendar widget with the datetime module.
 * Getting Images from the Clipboard - How to grab and display images from the clipboard
 * Using the WebBrowser Widget - Basic usage of the WebBrowser widget
 * Preview All Installed Fonts - A simple app to preview all the fonts installed on your system
 * Basic Handwriting Recognition - Using the InkOverlay class to enable basic handwriting functionality
 * Preview All Installed Voices - A simple app to preview all the voices installed on your system
 * HTML Encoder - A simple WinForm script which can encode or decode HTML and copy it to the clipboard

Silverlight
For a good introduction to using IronPython with Silverlight (including code, live examples and downloads), visit The Voidspace Silverlight Pages.


 * Profiling - A quick and low-impact way to get some rudimentary performance data in a silverlight application.
 * Try Python - an IronPython Silverlight application for learning Python

Databases

 * Databases with Odbc - Executing a database query with a connection string and OdbcConnection.
 * Named Data Sources - Auto-discovering named data sources (from the registry), and using them with Odbc.
 * A Walkthrough Project Jasper - Using Project Jasper with IronPython. Also see The Entity Framework with IronPython.
 * A DataGridView with a Database as the DataSource - with textboxes to enter connection string and a query, you can view the results of any SQL query in a DataGridView (an example of data-binding). Goes through setting up MySQL for the example.
 * Database access using ADO.Net - Examples for loading and querying data using Odbc and SQLite providers.
 * Database access using Python DBAPI - Connecting to the database and executing basic DDL and SQL statements via the Python DB-API instead of directly accessing ADO.Net (This 2006 example uses the FePy dbapi tools.)
 * adodbapi - A newer module for DBAPI access - The above discussion of DB-API access is great. Please read it! However, the tools to which it refers are not quite PEP249 compliant. This one is fully compliant, has several extensions, is fully updated for IronPython 2.6, and will work with JET (a.k.a. Access) databases, Microsoft SQL server, MySQL, and others.
 * Accessing SQL Server - Use IronPython to access a SQL Server.
 * Oracle & OleDb - Accessing an Oracle Server using OleDb
 * Amazon SimpleDB
 * Programmatic Control of SSIS - Simple example of programmatic control of a SQL Server 2005 Integration Services (SSIS) Package
 * Connection String Editor - Example of displaying a dialog box to prompt for database connection string

SqlServer 2005 Management Objects

 * Using SMO to manage a MS SQL Database - Using SMO (SQL Managment Objects) to manage and automate tasks with a MS SQL Server. Connecting, create a new database, backups etc.
 * close and disconnect SMO objects using ironpython
 * A Simple SMO Application in Ironpython
 * Get All Database Names in SQLserver
 * Navigate Database Hierarchy of SQLServer2005 database
 * Getting Database Properties
 * Create Table in SQLServer 2005 Database using SMO & IronPython

Network Protocols

 * Simple Server - An example web-server, using the System.Net.HttpListener class.
 * Handling POST with HttpListener
 * Sending Udp Packets
 * Receiving Udp Packets
 * Download a web page
 * Submit a POST form and download the result web page
 * Fetching a Page with Basic Authentication - also sets a UserAgent on the request and investigates the headers of the response.
 * Upload a file with FTP
 * Display local IP address

Interop

 * Interop introduction
 * Interacting with Excel
 * Converting a Word document to Text
 * Replace Text within a Word document
 * Enumerating Windows Media Player Library Contents
 * Creating a Shortcut File with WSH Interop
 * Reading the Target of a Shortcut with Shell32 Interop
 * AgentServerObjects - little flying dudes, seriously!
 * Using Spreadsheet Functions with Excel 2007 - might also work with Excel 2003, another example of Excel COM interop
 * Extremely Late Binding
 * OLE Automation support - Shri Borde discusses IronPython interop features in detail

System

 * Working with File Paths
 * Launching Sub-Processes
 * The subprocess module
 * Watching the FileSystem
 * Compression with DeflateStream - including writing and reading bytes to files.
 * The Environment Class - Access to the local environment, including setting platform wide environment variables.
 * Enumerating Installed Fonts
 * List all Running Processes - with a StringBuilder example thrown in for free.
 * List Files with Ownership
 * Data Protection with System.Security
 * SHA1Managed from System.Security.Cryptography
 * Listing all exceptions in the framework
 * Listing time zones - with current time in each time zone
 * Validating a Filename - Use the framework to ensure filenames only contain valid characters for the platform.
 * Process Monitor - Re-launch a process if it dies

Win32 & Windows Specific

 * The Registry - Getting and setting registry keys.
 * Connecting to Active Directory - using a Powershell assembly from IronPython
 * Querying Active Directory with DirectorySearcher
 * Message Queuing - MSMQ
 * Determining Windows Version
 * Active Directory and RefreshCache - enable ironpython to get attributes like TokenGroups from AD
 * DirectoryServices to Dictionary - convert a DirectoryServices object to dict
 * Registry Permissions - particularly the complexity around 64 bit Vista

System Administration and automation

 * Create a local user - Creating a local user and assigning file security rights
 * Working with IIS - Creating Websites, Virtual Directories, FTP Virtual Directories and Application Pools.
 * Create a new MS SQL Database - Using SMO to connect to a MS SQL Server and create a new database
 * Automating MSBuild
 * Folder Backup Utility - Backup project folders (i.e. VS 2003/5) and parse command-line options
 * Working with Sharepoint - Reading several data sources from a SharePoint 2007 server, merging them, and posting the merged data back to the server
 * Tfs via IronPython - working with Team Foundation Server
 * Logical Drive Enumeration - Using System.Management and a ManagementObjectSearcher query
 * WMI with IronPython - Using, the WMI interface, from IronPython
 * Adding Additional Snapins to IronPython - enable ironpython to see other powershell snapins like those in Exchange 2007
 * Active Directory and RefreshCache - enable ironpython to get attributes like TokenGroups from AD
 * Reading Eventlogs - use ironpython to get eventlogs with the System.Diagnostics Library
 * VimWrap - convenience wrapper around the VMWare API
 * Adding Exchange Snapin to IronPython - managing exchange from IronPython

.NET 3.0

 * WPF Example - StackPanel and button with WPF (Windows Presentation Foundation)
 * Speech Synthesis - making IronPython talk
 * Talking Twitter - Listen to the Twitter public timeline
 * Windows Automation - Interacting with applications through System.Windows.Automation
 * Speech Recognition - recognize a simple spoken grammar
 * WPF GUI using XamlReader - Create the layout for a WPF application in XML
 * XAML GUI Events Example - Creates a GUI using a XAML definition and dynamically hooks up event handlers.
 * XAML Crazy Windows - Creates a crazy shaped, transparent window, and attaches event handlers.
 * WPF Metaclass - An example of a very useful metaclass to use for WPF.

Graphics & Multimedia

 * Direct3D - Creating a Device
 * Direct3D - Creating a Device with SlimDX - SlimDX is an efficient, simple, and lean wrapper that fully encompasses all of DirectX.
 * Direct3D with Vertices
 * Animated Direct3D with Matrices
 * Animated Object with Lights
 * Texture Mapping in Direct3D
 * XNA Example with a Bouncing Sprite
 * XNA Example - Luminance
 * Reading and Writing JPG Metadata with .NET 3
 * Multi-colored Bar Chart with ZedGraph - saved as an image file
 * How to Play an MP3 - Managed DirectX
 * How to Play a Wav Sound File - The System.Media framework.
 * Read ID3 tags from a MP3 - Use Windows Shell/COM to read ID3 tags.
 * Pie Chart with ZedGraph - saved as an image file
 * Managed Direct3D via IronPython Tutorial - Part 1 - Importing/Referencing the Managed DirectX 1.1 Assemblies
 * Managed Direct3d via IronPython Tutorial - Part 2 - Interactive control of a Managed Direct3D Device
 * OpenGL - Initializing Context With GLFW
 * OpenGL - Rendering a spinning triangle with GLFW
 * Zoom of a 2D surface using the SDL library
 * Create Multiframe TIFF Image File - Create a TIFF file that encapsulates multiple images

Embedding

 * Creating Python Modules from CSharp - using PythonContext, CodeContext, SourceUnit, PythonDictionary and friends.
 * Checking Python Syntax without Executing
 * Using Python Classes from .NET/CSharp IP 2.6
 * Using Compiled Python Classes from .NET/CSharp IP 2.6

Note: most of the pages below are for embedding IronPython 1, or out of date tutorials for pre-release versions of IronPython 2. An up-to-date set of tutorials on embedding IronPython 2 (including interacting with dynamic objects) can be found at Embedding IronPython.


 * Custom Executable - Creating a custom executable by embedding the IronPython engine in C#.
 * Hosting the IronPython Engine - Embedding the IronPython engine. This article explores the IronPython 1.X API by hosting the Engine within IronPython.
 * Hosting IronPython 2 - A simple example of hosting IronPython 2 with C#.
 * Hosting IronPython 2 from IronPython - The IronPython 2 hosting API explored from IronPython. This includes setting variables and executing code that uses those objects.
 * Using Python Classes from .NET
 * Using Python Functions from CSharp - Using IronPython 2 from C# to create and use Python functions
 * The IronPython 2 Parser - an example of using the IronPython 2 parser to extract the variable names from an expression.
 * Wrapping a Stream in Python file -- How to convert a .NET stream to a Python file-like object.

XML

 * XSL Transform XML Files
 * Creating XML Trees - Creating XML trees using functional construction introduced with LINQ to XML
 * Parsing RSS - How to download and use RSS Feeds.
 * Settings File - Use XML to store simple application settings.

Misc

 * Introspecting .NET Types and Methods from IronPython
 * Dynamically Compiling and Using C# from IronPython
 * Reading CSV Filesby Seo Sanghyeon
 * Overridable Properties
 * Enumerations in IronPython
 * The CPython Server - Interface IronPython to CPython through a simple localhost web server
 * Simulating thread.interrupt_main
 * High Performance Timers - Profiling with the QueryPerformanceCounter high performance timer class.
 * Threading - Simple examples of creating and aborting threads in IronPython.
 * Screenshots and Unmanaged Code - Taking a screenshot using unmanaged code (user32.dll and GDI32.dll).
 * Dynamic Class Creation - Using the Reflection.Emit API.
 * NUnit and IronPython with more explanation here
 * SCons on IronPython - Running the SCons build system using IronPython
 * Tweet - Use Twitter from IronPython.
 * Random String Generation - Generate a random string
 * Self-executable scripts - Making IronPython scripts self-executable

Tools and Utilities

 * Web IDE - Try out Python in your browser.
 * SilverShell - Slick IronPython Shell that runs in a browser and also on the desktop
 * IronEditor - Win Forms based editor for DLR based languages.
 * IronPython add-in - An IronPython add-in for Redgate's .Net Reflector Redgate
 * Davy's IronPython Editor - DIE (Davy's Ironpython Editor) is a clutter free IronPython code editor along the lines of SPE or DrPython.

Compatibility
These sections document the compatibility of various Python application and libraries with IronPython.
 * Application Compatibility
 * Web Application Compatibility
 * Standard Library Compatibility
 * Third-Party Library Compatibility