User login

A Visual Studio 2008 Solution with the complete code listing for this series is attached to the final part.

The XAML framework allows us to easily switch between the Declarative and Imperative programming models easily. Examples such as event handlers are obvious cases where this happens, while others, such as MarkupExtensions and ValueConverters for Bindings are not so clear - when you implement the ProvideValue method of a custom MarkupExtension, you are suddenly in the the imperative world of C# (or CLR language of your choice) where as the XAML document that declared the MarkupExtension is declarative in nature.

The ability to dynamically load XAML using the XamlParser class allows the programmer to switch in and out of the declarative and imperative worlds with ease, affording them great power and flexibility. Or so it would seem...

Dynamically loaded XAML does not integrate with the imperative world as well as it's compiled brethren. For example, you completely lose the ability to route events to handlers when loading XAML dynamically. This greatly hampers the usefulness of dynamically loaded XAML. The stance in the community is that you should simply compile your XAML if you want to handle events. In many instances this is just not an acceptable solution!

There are a number of interpreted (hence dynamic) imperative languages that bind to the CLR, such as Python and Ruby. The new Dynamic Language Runtime (DLR) will encourage the development off new dynamic languages as well as the binding of existing dynamic languages to .NET. In this series of 6 articles I will demonstrate how to embed any and all DLR languages in XAML.

First some background reading. The dynamic nature of XAML (or lack there of) has been discussed many times in public forums. There have been attempts to embed Python and other dynamic languages (such as the Lambda Converter Extension below) into XAML, all with mixed success. Below are links to interesting documents worth reading:

Hosting the DLR is not difficult. The DLR is still under development, but my experience with it has been positive. It seems quite stable and performs well with IronPython and IronRuby.

Note: The code in this series was written against the DLR redistributed with IronPython 2.0 Beta 3. There have been some breaking changes in the DLR API since then, so code listed here may need modification to work withh later versions of the DLR.

The DLR is contained in two assemblies, Microsoft.Scripting.dll and Microsoft.Scripting.Core.dll. The easiest way to get moving is to download a compiled version of either IronPython or IronRuby as both redistribute the DLR assemblies.

Your application should reference both Microsoft.Scripting.dll and Microsoft.Scripting.Core.dll, but does not need to reference the Python or Ruby assemblies as these will be loaded on demand by the DLR. To avoid issues with locating DLLs at runtime, I suggest just dumping all these DLLs in the bin directory of your app to get moving.

The following is a simple example of hosting the DLR using C# and evaluating a simple Python expression. After execution, result is set to 11 as expected.

usingMicrosoft.Scripting.Hosting;

usingMicrosoft.Scripting;

// create a ScriptRuntime instance

ScriptRuntime runtime = ScriptRuntime.Create();

// Get the engine for the target language

ScriptEngine eng = runtime.GetEngine("python");

// A scope is used to setup local variables - the context in

// which the script will be executed.

//

// We add:

// a = 5

// b = 6

ScriptScope scope = eng.CreateScope();

scope.SetVariable("a", 5);

scope.SetVariable("b", 6);

// Create a ScriptSource object from our script:

//

// a + b

ScriptSource source =

eng.CreateScriptSourceFromString(

"a + b", SourceCodeKind.Expression);

// evaluate the expression - result == 11.

object result = source.Execute(scope);

In the interest of clarity and brevity, little attention will be paid to performance or error handling in this series. The following utility methods will be used throughout this series:

usingMicrosoft.Scripting.Hosting;

usingMicrosoft.Scripting;

staticclass DlrUtils

{

// We use a static ScriptRuntime as all scripts will run in

// the current app domain and because all scripts will be

// called from the GUI thread, so there are no treading issues.

privatestatic ScriptRuntime s_runtime = ScriptRuntime.Create();

//

// Execute a script of the specified language. A dictionary containing

// variables to be injected into the scope before script execution

// can be supplied.

//

staticpublicvoid Execute(

string language,

string script,

Dictionary<string, object> scopeVars )

{

ScriptEngine eng = s_runtime.GetEngine(language);

ScriptScope scope = eng.CreateScope();

// set up the scope

if(scopeVars !=null)

{

foreach(var kv in scopeVars)

{

scope.SetVariable(kv.Key, kv.Value);

}

}

// execute the script

if(script !=null&& script !="")

{

ScriptSource envSource =

eng.CreateScriptSourceFromString(

script, SourceCodeKind.Statements);

envSource.Execute(scope);

}

}

//

// Evaluate an expression of the specified language. A script can be supplied

// that is executed before the expression is evaluated. The script is intended to

// be used to set up the environment (ie, local variables, loaded libraries, etc)

// in which the expression is evaluated. A dictionary containing variables to

// be injected into the scope before script execution can also be supplied.

//

staticpublicobject Evaluate(

string language,

string environmentScript,

string expression,

Dictionary<string, object> scopeVars )

{

ScriptEngine eng = s_runtime.GetEngine(language);

ScriptScope scope = eng.CreateScope();

// set up the scope

if(scopeVars !=null)

{

foreach(var kv in scopeVars)

{

scope.SetVariable(kv.Key, kv.Value);

}

}

// execute the environment script

if(environmentScript !=null&& environmentScript !="")

{

ScriptSource envSource =

eng.CreateScriptSourceFromString(

environmentScript, SourceCodeKind.Statements);

envSource.Execute(scope);

}

// evaluate the expression

ScriptSource source =

eng.CreateScriptSourceFromString(

expression, SourceCodeKind.Expression);

return source.Execute(scope);

}

}

Using these utility methods, our original expressions of "a + b" could be written more concisely, like the following: