About the book
This is a sample chapter of the book
IronPython in Action. It has been published with the exclusive
permission of Manning.
Written by: Michael J. Foord and Christian Muirhead
Pages: 496
Publisher: Manning
ISBN: 1-933988-33-9
Get 30% discount
DotNetSlacker readers can get 30% off the full print book or ebook at
www.manning.com using the promo code dns30 at checkout.
Introduction
Improved browser capabilities, enabled by faster computers, have not only made complex and rich web applications possible but have
also changed the way we use computers. Techniques like AJAX, and powerful JavaScript libraries that abstract away painful cross-browser
issues, have resulted in client-side (in the browser) programming becoming one of the most important fields in modern software
development. Despite this, web applications remain restricted by the user-interface capabilities of JavaScript and the performance of
JavaScript when running large programs. Ways around these difficulties include web-programming frameworks such as Flash, AIR, Flex,
and Silverlight, which have their own programming and user-interface models. In case you haven't heard of it, Silverlight is a cross-platform
browser plug-in created by Microsoft. It's superficially similar to Flash but with the magic extra ingredient that we can program it with Python.
Because Silverlight is based on the .NET framework, it's a major new platform that IronPython runs on.
Silverlight has a
user-interface model based on Windows Presentation Foundation, and we can use it to do some exciting things, such as media streaming,
creating games, and building rich internet applications.
In this chapter, we look at some of what Silverlight can do and how to do it
from IronPython. We'll be exploring, creating, and deploying dynamic Silverlight applications and programming with the Silverlight APIs -
some of which are familiar and some of which are new.
Introduction to Silverlight
Silverlight is a cross-platform, cross-browser plug-in for embedding into web pages. Silverlight has at its heart a cut-down and
security-sandboxed version of the .NET framework called the CoreCLR. That means it contains many of the APIs we're already familiar with,
including the WPF user interface. More important, the CoreCLR is capable of hosting the Dynamic Language Runtime, so Silverlight can be
programmed with DLR languages like IronPython and IronRuby.
In this chapter we explore some of the features that Silverlight
provides. Figure 1 shows a Tetrislite game
written for Silverlight 2, from the Silverlight community samples.
Figure 1: Tetrislite from the Silverlight community samples

By cross-platform, Microsoft
means Windows and Mac OS X. By cross-browser, the Microsoft folks mean the Safari, Firefox, and Internet Explorer web browsers. This
isn't the end of the story, though; Silverlight support is in the works for the Opera browser and for the Windows Mobile and Nokia S60
platforms. The Silverlight team members aren't working directly to support Linux, but they are working with the Mono team on an officially
blessed Mono port of Silverlight called Moonlight.
This currently
works on Firefox on Linux, but the eventual goal is to get Moonlight working on multiple browsers (like Konqueror) and on every platform that
Mono runs on. The stable version of Moonlight is compatible with Silverlight 2, and there's an early preview of Moonlight 3, which unsurprisingly targets compatibility with
Silverlight 3. Meanwhile, Microsoft has also released their own developer preview, of Silverlight 4, with lots of exciting new features.
Microsoft
has assisted the Moonlight effort by providing access to the Silverlight test suite and the proprietary video codecs that Silverlight uses.
Moonlight uses the Mono stack, but a lot of the work involved implementing the security model that provides the Silverlight browser
sandboxing. Another major part was the user-interface model; this is particularly interesting, because previously the Mono team has said
that they have no interest in implementing WPF. Perhaps this will change now that they have had to implement a subset of WPF for
Moonlight.
So what benefits for web application programming does Silverlight have over traditional JavaScript and AJAX? The first
advantage is that it can be programmed in Python, and frankly that's enough for us. The Python community has long wanted to be able to
script the browser with Python rather than JavaScript, and it's at least slightly ironic that it's Microsoft that has made this possible. Perhaps a
more compelling reason is that Silverlight is fast. By some benchmarks (of course, all benchmarks are misleading, in the same way that all
generalizations are wrong) IronPython code running in Silverlight runs two orders of magnitude faster than JavaScript! As well as having its
own user-interface model, Silverlight gives you full access to the browser DOM (Document Object Model), so that everything you can do
from JavaScript you can also do from inside Silverlight. The features of Silverlight include
- A user-interface model based on WPF
- APIs including threading, sockets, XML, and JSON
- A powerful video player
- Deep zoom and adaptive media streaming
- Client-side local storage in the browser
- Out-of-browser support for desktop-style applications, new in Silverlight 4
- Access to the browser DOM and techniques to communicate between JavaScript and
- the Silverlight plug-in.
DeepZoom and adaptive streamingDeep Zoom is a fantastic image-zooming technology based on Seadragon: see
http://silverlight.net/learn/quickstarts/deepzoom/.
Adaptive streaming allows the browser to adjust the quality of streamed audio and
video according to the available bandwidth and CPU power.
The last point is particularly interesting. Although most example Silverlight applications take over the whole web page, this isn't the
only way to use it. Like Flash, the Silverlight plug-in can occupy as little of a web page as you want (yes, you can use Silverlight to create
those annoying adverts that everybody hates), and you can embed several plug-ins (which can communicate with each other) in the same
page. In fact, the Silverlight plug-in needn't be visible at all. By interacting with JavaScript and the browser DOM, you can use all your favorite
AJAX tricks from Silverlight, including using existing JavaScript libraries for the user interface, with the business logic implemented in Python.
Creating Silverlight applications with dynamic languages is simple. Let's dive into the development process.
Dynamic Silverlight
Silverlight applications are packaged as xap files (compressed zip files), containing the assemblies and resources used by your
application. An IronPython application is a normalapplication as far as Silverlight is concerned; a DLR assembly provides the entry point and
is responsible for running the Python code.
The standard IronPython distribution includes a special version of the DLR assemblies
and IronPython compiled for Silverlight, along with the development tool Chiron.exe.
Chiron and the dynamic experienceChiron packages IronPython Silverlight applications as the browser requests them.
This means that you can have a truly dynamic experience developing Silverlight applications with IronPython. Edit the Python file with a text
editor or IDE and refresh the browser, and you immediately see the changes in front of you.
Chiron can create xap files for dynamic applications and will also work as a server, allowing you to use your applications from the
filesystem while you're developing them. Chiron runs under Mono, so you can use it on the Mac. Silverlight lives on the web, so to use it we
need to embed it into a web page.
Embedding the Silverlight control
Embedding a Silverlight control into a web page is straightforward. You use an HTML <object> tag, with parameters that initialize the
control and HTML that displays the Install Microsoft Silverlight link and image (shown in figure 2) if Silverlight isn't installed.
Figure 2: The image displayed to the user if Silverlight isn't installed

Listing 1 is the
typical HTML for embedding the Silverlight control into a web page.
Listing 1: The HTML to embed the Silverlight control
The onError parameter is a JavaScript function that'll be called if an error occurs inside Silverlight (including
in your code). The value in initParams is a bit special. debug=true enables better exception messages. As
well as getting the error message, you'll get a stack trace and a snapshot of the code that caused the exception. It works in conjunction with
an errorLocation div in your HTML (plus a bit of CSS for styling), which is where the tracebacks from your application are displayed. You can
see the necessary HTML/CSS in the sources of the examples for this chapter.
CLR trackbacks in error reportingYou can extend the error tracebacks to include the CLR errors by adding
exceptionDetail to initParams:
<param name="initParams" value="debug=true,reportErrors=errorDiv,
exceptionDetail=true" />
This is usually more information than you want in tracebacks, but it can be invaluable in tracking
down the underlying reason for some errors.
The XAP file
The xap file is a zip file with a different extension; you can construct xap files manually or Chiron can autogenerate them for you. The
command-line magic to make Chiron create a xap file from a directory is
bin\Chiron /d:dir_name /z:app_name.xap
If you're running this on the Mac, then the command line will look something like this:
mono bin/Chiron.exe
/d:dir_name /z:app_name.xap
More important, you can use Chiron to test your application from the filesystem, without
having to create a xap file. If your application is called app.xap, then your application files should be kept in a directory named app. Chiron will
act as a local server and dynamically create xap files as they're requested. The command to launch Chiron as a web server is
Chiron /w
By default, this serves on localhost port 2060. The most important part of the xap file is the entry
point, which in dynamic applications will be a file called app.py, app.rb, or app.js, depending on which dynamic language you're programming
in.
Your Python application
Our first app.py will be the simplest-possible IronPython Silverlight application. Because we're using the WPF UI system, we work with
classes from the System.Windows namespaces. Listing 2 creates a Canvas, with an embedded TextBlock displaying a
message.
Listing 2: A simple IronPython application for Silverlight
The important line, which is different from our previous work with WPF, is the last one, where we set the container canvas as
the RootVisual on the current application. This makes our canvas the root (top-level) object in the object tree of the
displayed user interface. You're not stuck with a single Python file for your application, though. Imports work normally for Python modules and
packages contained in your xap file (or your application directory when developing with Chiron). You can use open or file to access other
resources from inside the xap file, but they're sandboxed, and you can't use them to get at anything on the client computer.
Project structure in Silverlight applicationsIn Silverlight projects you can break your applications into multiple Python
files in the same way you can with normal Python applications. Import statements from Python files kept in the xap file work normally,
including from Python packages. You can even keep Python files in a subdirectory and add it to sys.path to be able to import from them.
Because we're using WPF, many applications load XAML for the basic layout. They do so with very similar code to listing 2, as
shown in listing 3.
Listing 3: IronPyhton Silverlight application that loads XAML
Instead of setting the RootVisual on the application, this code loads the XAML with a call to
LoadRootVisual. Listing 4 shows the app.xaml file, for a Canvas containing a TextBlock, loaded from the xap file in listing
3.
Listing 4: Silverlight XAML for UI layout
The call to LoadRootVisual returns us an object tree. Like the object trees we worked with from XAML in
chapter 9, we can access elements that we marked with x:Name as attributes on the object tree. This allows us to set the text on the
TextBlock through xaml.textblock.Text. Many of the techniques we learned when working with the WPF libraries for desktop
applications are relevant to Silverlight, but they're far from identical. One of the major differences is that we have fewer controls to work with.
Let's look at some of the APIs available for creating Silverlight applications, including the extended set of controls.
Silverlight controls
Silverlight ships with a set of standard controls based on WPF and contained in the System.Windows.Controls namespace. Figure 3
shows examples of the standard controls.
Figure 3: Some of the standard Silverlight controls

Using controls
As you might expect from their WPF inheritance, the Silverlight controls are attractive and easy to use. Figure 4 shows a TextBox with a
Button and a TextBlock.
Figure 4: A TextBox with Button and TextBlock

Using and configuring the controls from code is splendidly
simple. Listing 5 shows a Button and a TextBox inside a horizontally oriented StackPanel. When the Button is clicked, or you press Enter, a
message is set on the TextBlock.
Listing 5: A TextBox with a Button in a horizontal StackPanel
Along with the standard controls, a set of extended controls comes with Visual Studio Tools for Silverlight. (Silverlight Tools
for Visual Studio 2008 works with Visual Studio 2008 or Visual Web Developer 2008 Express. The tools are linked to from
http://silverlight.net/getstarted/.)
This set includes additional controls such as Calendar, DataGrid, DatePicker, TabControl, and so
on.
NOTEIn addition to the standard and extended controls, Microsoft has a Codeplex project (available with source code
and tests, under the same open source license as IronPython) called Silverlight
Toolkit.
The toolkit is a collection of controls and utilities for Silverlight, including TreeView, DockPanel, and charting
components.
Using the extended controls
Visual Studio Tools for Silverlight comes with a lot more than just a new set of controls. It also includes additional assemblies for working
with JSON, XML, and so on (don't use the outdated version of IronPython it includes, though!). What we're about to cover is as relevant for
using these other assemblies as it is for the extended controls.
The two assemblies that implement the extended controls
are
System.Windows.Controls.dll
System.Windows.Controls.Data.dll
As with using other assemblies from IronPython, in order to use them we need to add a reference to them with
clr.AddReference.
Table 1 lists the Silverlight controls.
Table 1: Silverlight controls
Border | DatePicker | MultiScaleImage | Slider |
Button | Grid | OpenFileDialog | StackPanel |
Calendar | GridSplitter | Panel | TabControl |
Canvas | HyperlinkButton | PasswordBox | TextBlock |
CheckBox | Image | ProgressBar | TextBox |
ComboBox | InkPresenter | RadioButton | ToggleButton |
ContentControl | ListBox | RepeatButton | ToolTip |
DataGrid | MediaElement | ScrollViewer | UserControl |
It will be self-evident what most of these controls are for from their names (one of the advantages of consistent naming
schemes). One that may not be familiar is MultiScaleImage.
This control is for displaying multiresolution images using Deep Zoom. It allows the user to
zoom and pan across the image. These assemblies extend the System.Windows.Controls namespace, so the extended controls are
imported from the same place as the standard controls. Of course, you can use the extended controls from XAML as well as from
code.
Extended controls from XAML
Using the extended controls from XAML requires us to tell the XAML loader where to find the classes that correspond to the XAML
elements. We do this by adding extra xmlns declarations to the first tag in the XAML. Listing 6 is a part of an XAML file that
uses several of the extended controls (Calendar, DatePicker, and GridSplitter).
Listing 6: XAML for UI using the extended controls
To load this XAML from IronPython, like the example in listing 3 (This XAML has a UserControl as the root element, so you'll
need to modify listing 3 to create a UserControl instead of a Canvas.), we don't need to explicitly add references to the assemblies
containing the controls; the XML namespace declarations do this for us. The xmlns:c declaration also declares a prefix (c)
that we must use to reference controls from the System.Windows.Controls assembly. For example, the DatePicker control is referenced
with c:DatePicker in the XAML. Once this XAML is loaded, the results look like figure 5.
If you don't like the standard
silver theme, you can use a new theme for all the controls in an application. In discussing the extended controls, we've glossed over an
important point.
Packaging a Silverlight application
If you look in the source code for the example applications that use the extended controls, you'll see a file that we haven't yet discussed,
AppManifest.xaml. This XML file tells Silverlight not only what assemblies your application uses but also which one provides the entry point.
The reason it isn't included in the earlier examples is that Chiron can autogenerate it for applications that use no assemblies beyond the
standard IronPython/DLR ones.
When you deploy a typical dynamic application, the xap file contains the following:
- app.py - your main Python file
- The IronPython assemblies (dlls)
- An XAML (XML) manifest file
- Any additional Python modules, XAML files, assemblies, or resources your app uses
Listing 7 shows the manifest file needed for a basic dynamic application. You can either copy and paste this into your applications
or let Chiron create it for you.
Listing 7: The XML manifest file for an IronPython application
Requiring XML manifest files may seem like unnecessary overhead for dynamic applications, but they serve a very serious
purpose: making Silverlight applications fit for the enterprise.
It's interesting to note the EntryPoint attribute in the top-level
Deployment element. This is how Silverlight knows how to execute a dynamic application, and a dynamic application is a normal C#
application as far as Silverlight is concerned. Microsoft.Scripting.Silverlight.dll does the magic for us.
To use additional assemblies in
your applications, including the extended controls, you need to include them in the manifest. This has a serious downside, even if your
application is only a single Python file a few kilobytes in size; the resulting xap file will need to contain the IronPython assemblies and be
several hundred kilobytes in size.
Fortunately, there's a way around this. If instead of specifying the assembly name as the Source
attribute for the assemblies you specify an absolute URL, the assemblies will be fetched separately rather than being expected inside the xap
file. If several of your applications share the same assemblies, then the browser can cache them, and your application can shrink back to a
more manageable size. At some point a mechanism like the Global Assembly Cache will be implemented for Silverlight, but there isn't one
yet.
We've covered all the basics now, and you have everything you need to start writing Silverlight applications; everything else is
mere detail. The best way of learning these details is to use them, so in the next section we look at a more substantial Silverlight application:
a Twitter client.
This will be the topic of the next part of this series.
Summary
Rich internet applications are already an important part of the internet revolution, and they're only becoming more important. Silverlight is
one of the new frameworks that allow programmers to really take advantage of client-side processing power in web applications.
One of the tools we used when writing this chapter was the Silverlight IronPython Web IDE. This allows us to experiment with the Silverlight APIs by executing code in the browser,
and it has several examples preloaded, including some topics we didn't have space for here.
There's a lot we haven't had time to
use. We haven't looked at loading XAML or initializing controls from XAML or animations with the StoryBoard. Because the Silverlight
user-interface model is based on WPF, using these features is very similar to using them from WPF, and this includes using Expression
Blend (to use Expression Blend with Silverlight you'll need version 2.5 or later) as a design tool. With clever structuring, your desktop and
online versions of your applications could share a lot of their code and XAML.
This is one of the best things about working with
Silverlight; much of our existing knowledge about .NET and IronPython is directly applicable.
Get 30% discount
DotNetSlacker readers can get 30% off the full print book or ebook at
www.manning.com using the promo code dns30 at checkout.
About Manning Publications
 |
Manning Publication publishes computer books for professionals--programmers, system administrators, designers, architects, managers and others. Our focus is on computing titles at professional levels. We care about the quality of our books. We work with our authors to coax out of them the best writi...
This author has published 33 articles on DotNetSlackers. View other articles or the complete profile here.
|
You might also be interested in the following related blog posts
Using WCF with SQL Azure and Telerik OpenAccess
read more
The Underground at PDC
read more
Building A Product For Real
read more
Silverlight MVP
read more
GiveCamps Get a new Sponsor
read more
Announcing the WebsiteSpark Program
read more
Scenarios for WS-Passive and OpenID
read more
More On The CodePlex Foundation
read more
Building a Silverlight 3 based RIA Image Magagement System (1)
read more
Building a Silverlight 3 based RIA Image Management System - 1
read more
|
|
Please login to rate or to leave a comment.