IronPython In C#
Silverlight allows embedding IronPython code in the
code-behind files of Silverlight XAML pages. This means you can use both C# and
IronPython code in the same C# code-behind file of ta Silverlight UI.
Consider a scenario, where you can create a Silverlight
application using both C# and IronPython code that enables user to enter any
text that automatically converts to upper case as the user keeps on typing. To
implement this example, create a Silverlight application. After creating the
appliaction, add the following assemblies ot the application.
Next type the following code to desing the UI that anables user to enter text:
Tyep the function delegate
of the Microsoft.Scripting Utils namespace,
as shown in the following code snippet:
Type the following code to declare an anonymous IronPython
function that converts strings to upper case:
String code = "lambda x: x.upper()";
Note: Lambda is
an IronPython construct to declare functions that are not bound to a name.
Next, type the following code to host the IronPython engine
and notify the engine of the IronPython script to execute, as shown in the
following code snippet:
Microsoft.Scripting.Hosting.ScriptEngine pe = PythonEngine.CurrentEngine;
Microsoft.Scripting.IscriptScope scope = pre.CreateScope();
Microsoft.Scripting.Hosting.SourceUnit source = pe.CreateScriptSourceFromString (code, "id");
Func = pe.Execute> (scope,source);
Finally, Implement the event handler method of the
Silverlight TextBlock control to display the output returned by the IronPython
expression as shown in the following code snippet:
Private void inputTextblock_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
inputTextblock.Text = func(inputTextblock.Text);
When you run the project, the Silverlight UI displays a text
box as shown in the following figure.
Figure 1:The initial Output of the DLR Hosting
As you keep typing in the textBox, the letter converted to
upper case, as shown in the following figure.
Hope you enjoyed this article.