[This topic is pre-release documentation and is subject to change in future releases of Microsoft Silverlight.]
Programming Silverlight with Dynamic Languages
Introduction
This QuickStart sample shows how to create a Microsoft Silverlight-based application that uses managed code and a dynamic language, and how to debug the application in Visual Studio 2008.
The Silverlight Tools Beta 1 for Visual Studio 2008 includes snapshots of the Dynamic Language Runtime (DLR) and three dynamic languages: IronPython, IronRuby, and Managed JScript. Visual Studio 2008 project templates are not yet available for dynamic languages, but you can build, run, and debug your application by using the Chiron.exe tool.
The DLR and the dynamic languages are currently under development on the Codeplex Web site. You can find more information there, including new releases, source code, and additional Silverlight samples. New releases are available frequently.
This topic covers the following subjects:
-
Creating a Silverlight-based dynamic language application and running it by using Chiron.exe.
-
Creating a .xap file for deployment.
-
Accessing class libraries in managed assemblies.
-
Debugging a Silverlight-based dynamic language application with Chiron.exe and Visual Studio.
Prerequisites (available from the Silverlight download site):
Creating a Silverlight-Based Application with a Dynamic Language
A simple Silverlight-based application that uses a dynamic language contains the following:
-
The root HTML or .aspx file that is the entry point for a browser.
-
The app.xaml file, which defines the user interface for your Silverlight-based application.
-
The app.py, app.rb, or app.jsx file, which contains the dynamic language code that handles events at run time. For dynamic languages, this file is not compiled into an assembly. Dynamic language code is compiled and executed at run time on the client computer.
note
The dynamic language engine and DLR assemblies are included in the .xap file that is generated by Chiron.exe and downloaded to the client computer. You do not have to include them in your project.
To create and run a Silverlight-based application with a dynamic language
-
Create a folder for your application.
-
In the application folder, create two folders named app and assets. Use the assets folder for bitmaps and additional XAML files.
note
If you use silverlight.js to gain greater control over application startup, the assets folder is a good locaton for it. The applications in this sample do not use silverlight.js.
Your application need not be limited to this simple folder structure. This is only a basic structure that Chiron.exe can use without specifying any special parameters. Your application program can access arbitrarily complex folder structures, and can contain any number of dynamic language code files.
-
In the app folder, create app.xaml. This file contains the root visual element for your application. A simple app.xaml file that is based on UserControl might look like this:
<UserControl
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="System.Windows.Controls.UserControl"
x:Name="Page"
>
<TextBlock x:Name="TextBlock1" TextWrapping="Wrap"
Foreground="Black" Text="Click Me." />
</UserControl>
Basing the root visual element on UserControl is recommended. Use the View Source button at the beginning of this topic to see another example of app.xaml.
-
In the app folder, create a dynamic language source file that contains your application code. The following code shows a very simple application that responds to a mouse button event.
jsx
Import("System.Windows.*");
Import("System.Windows.Controls.*");
xaml = Application.Current.LoadRootVisual(new UserControl(), 'app.xaml')
xaml.TextBlock1.MouseLeftButtonUp += function (sender, args) {
sender.FontSize *= 2
}
py
from System.Windows import Application
from System.Windows.Controls import UserControl
def OnClick (sender, args):
sender.FontSize *= 2
scene = Application.Current.LoadRootVisual(UserControl(), 'app.xaml')
scene.TextBlock1.MouseLeftButtonUp += OnClick
rb
include System::Windows
include System::Windows::Controls
scene = Application.current.load_root_visual UserControl.new, 'app.xaml'
scene.find_name('TextBlock1').mouse_left_button_up do |sender, args|
sender.font_size = sender.font_size * 2
end
The code calls the LoadRootVisual(DependencyObject, Uri) method to set the root visual object. An object of the correct type must be supplied. The DLR ensures that the correct method overload is used and provides the necessary code context.
Use the View Source button at the beginning of this topic to get the code for a more complex example that defines an App class.
note
In the IronRuby build distributed with the Silverlight Tools Beta 1 for Visual Studio 2008, only one event handler can be hooked up for any given event (for example, MouseLeftButtonUp). See the Codeplex Web site for more information about language development and availability of updates.
-
In your application folder, create an HTML page to start your application. Use the View Source button to copy the Default.html file used by all three languages. If you follow the naming conventions in this procedure, you can use this Default.html file without any changes.
The most important line in Default.html is the line that specifies the app.xap file. This is the file that contains your source code and the DLR assemblies.
<object data="data:application/x-silverlight,"
type="application/x-silverlight-2-b1"
width="100%" height="100%">
<param name="source" value="app.xap"/>
Default.html has other features, including a <div> for displaying error messages while you are debugging your application.
-
If you have not used Chiron.exe before, add it to the path.
Chiron.exe is located in the Tools folder of the SDK installation. If you used the default installation location, this folder is \Program Files\Microsoft SDKs\Silverlight\v2.0\Tools.
-
To run your application, use a Command Prompt window to run Chiron.exe with the /browser (/b) option. Run Chiron.exe from the application folder.
Chiron.exe serves your application folder in the browser.
note
By default, Chiron.exe uses the name "app" for the folder that contains your entry point code. You can change this default by using the /directory (/d) option.
Chiron.exe remains running in the Command Prompt window, displaying status messages.
-
In the browser, click Default.html to run the application.
Chiron.exe generates a .xap file on demand. Your Silverlight-based application opens. Click the text to increase the font size. Leave the browser open.
-
To show that the .xap file is generated on demand, edit the source file. Alter the line that increases the font size, so that it reduces the opacity instead:
jsx
py
rb
sender.opacity = sender.opacity / 2
-
In the browser, refresh the page.
Default.html requests app.xap, and Chiron.exe generates a new app.xap file. The application restarts. Click the control and notice that the opacity of the text now decreases. You can use this technique to edit and test your application repeatedly without having to restart Chiron.exe. In a later procedure you will see how to perform the same kind of iterative development while debugging with Visual Studio.
-
Close the browser.
-
In the Command Prompt window, press CTRL+C to stop Chiron.exe.
Creating a .xap File for Deployment
To deploy your application, you must create a .xap file that contains your dynamic language source code, manifest, XAML, other assets such as bitmaps, language compiler, and DLR assemblies. Chiron.exe performs this function.
To create a .xap file
-
Use a Command Prompt window to run Chiron.exe with the /directory (/d) and /zipdlr (/z) options. Run Chiron.exe from the application folder, just as you did when you were developing and testing your application.
The /directory option specifies the directory containing the application entry point, and the /zipdlr option specifies the name of the .xap file. For the application developed in the preceding procedure the command looks like this:
Chiron.exe /directory:app /zipdlr:app.xap
-
Copy Default.html and app.xap to the desired location.
note
Chiron.exe has command-line help that lists all its options, or you can find them listed in the Readme.txt file located with Chiron.exe. The Readme.txt file also includes information about configuring Chiron.exe to work with other dynamic languages.
Accessing Class Libraries
To write a Silverlight-based application, you have to access the Silverlight class libraries, plus any additional Silverlight-based class libraries you want to use. By default, the DLR provides references to the following assemblies:
For these assemblies, you can skip the steps for adding assembly references. You also have access to the DLR assemblies, Microsoft.Scripting.dll and Microsoft.Scripting.Silverlight.dll. You do not have to import the Microsoft.Scripting.Silverlight namespace.
To access Silverlight-based class libraries from IronPython
-
Use the import statement to load the clr module.
-
Use the clr.AddReference function to load assemblies and make their contents available for import.
clr.AddReference("MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089")
-
Use the import statement to add namespaces to the current context or to load modules. You must import namespaces before you can use them.
import System.Windows
import System
import MyPythonModule
-
Use the from … import statement to add the contents of a namespace or module to the current context.
from System.Windows import *
from System.Windows.Controls import UserControl*
To access Silverlight-based class libraries from Managed JScript
-
Use the AddReference function to load assemblies and to make their contents available for import.
AddReference("MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089")
-
Use the Import function to import namespaces into the current context. You must import namespaces before you can use them.
Import("System.Windows")
Import("System")
-
Use the Import function to import the contents of a namespace into the current context.
Import("System.Windows.*")
Import("System.*")
note
In addition to cluttering the global context, adding all the types in System replaces the Managed JScript Array with System.Array. You can import specific types.
-
Use the ImportAlias function to import a namespace or to type into the current context with an alias.
SW = ImportAlias("System.Windows")
-
Use the LoadModule and LoadModuleFromFile functions to load modules. The methods return the loaded module. The second parameter of LoadModuleFromFile specifies the type of the module, "js" or "py".
util = LoadModule("MyUtilities")
util = LoadModuleFromFile("MyUtilities", "py")
To access Silverlight-based class libraries from IronRuby
-
Use the require statement to load assemblies and to make their contents available for inclusion.
-
Use the include statement to add namespaces to the current context.
Debugging a Silverlight-Based Application Using Chiron.exe and Visual Studio
With the Silverlight Tools Beta 1 for Visual Studio 2008, you can use Visual Studio 2008 to debug a Silverlight-based application that uses dynamic languages. Your Silverlight-based application must be downloaded to a browser in order to run, and the debugger must be started after the code is downloaded. You can make changes to your code outside the debugging session, and reload the code without having to reattach to the browser process.
To debug a dynamic language application
-
Load the dynamic language files that you want to debug into Visual Studio, and set breakpoints.
-
From the application folder, run Chiron.exe with the /browser (/b) option to serve the directory in the browser.
-
In the browser, click Default.html to start the application.
Chiron.exe generates the .xap file on demand. The application startup code runs.
-
In Visual Studio, on the Debug menu, click Attach to Process.
Because your application is running in the browser, you must attach to the browser process in order to debug it.
-
In the Attach to Process dialog box, in the Available Processes list, in the Process column, click the appropriate instance of the browser to select it.
If you have other instances of the browser open, giving Default.html a title will make it easy to identify in the Title column.
-
Click Attach.
-
Switch to the browser and press F5 to refresh Default.html.
Your application is reloaded under the debugger, and you are now ready to debug. Any breakpoints you have set in your initialization code are hit when your application is reloaded.
important
You must refresh the page to reload your application after the debugger is attached. If you start interacting with your application without first refreshing the browser, none of your breakpoints will be hit.
-
Using a second instance of Visual Studio or another editor, make changes to your code and save them.
You cannot make changes to the code in the instance of Visual Studio that is attached to the browser process.
-
In the browser, refresh your HTML page.
Chiron.exe generates a new .xap file, and your application startup code runs. If you have breakpoints in your startup code, they are hit.
-
Visual Studio informs you that the source file has been modified, and asks whether you want to reload it. Click Yes to reload the file and continue your Visual Studio debugging session.
note
If your Visual Studio debugging session is at a breakpoint or stepping through code when you save the changes in your alternate editor, you cannot switch to the browser. Instead, switch to your Visual Studio debugging session. You will be prompted to reload the source file. You must then refresh the browser.
You can continue to switch between debugging and modifying your code without having to stop the browser or Chiron.exe.
-
When you are finished debugging, detach from the process. Close the browser, and use CTRL+C to stop Chiron.exe.
Status of Debugging Features
The snapshot of the DLR and dynamic languages included with the Silverlight Tools Beta 1 for Visual Studio 2008 supports most debugging features. For example, you can use F10 and F11 to step over or into code. Use the Locals window to examine variable values, and the Immediate window to set variable values or execute code.
note
In IronPython, when you step off the end of a function with F10 and control returns to the browser, Visual Studio 2008 displays a dialog box informing you that there is no source code available. Click OK to close the dialog box, and then press F5 to continue.
Support in some languages is better than in others. Debugging support will continue to expand as language development continues. See the Codeplex Web site for the most up-to-date information.