Embedding IronPython In C#


Introduction

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 the Silverlight UI.

Scenario

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 application, add the following assemblies ot the application. 
  • IronPython.dll
  • IronPython.Modules.dll
  • Microsoft.Scripting.dll
  • Microsoft.Scripting.Silverlight.dll
Next type the following code to desing the UI that anables user to enter text:

<Grid Width="300 Height="400" Background="Aquamarine">
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="50"/>
        <RowDefinition Height="*"/>
    <Grid.RowDefinitions>
    <TextBox FontSize ="30" x:Name="inputTextblock" Grid.Row="1" Width="200" Height="50" KeyUp="inputTextblock_KeyUp"/>
</Grid>

Type the function delegate of the Microsoft.Scripting Utils namespace, as shown in the following code snippet:

Function<string, string> func;

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<Function<string, string>> (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.

ironpyton.JPG

Figure 1:The initial Output of the DLR Hosting Application

As you keep typing in the textBox, the letter converted to upper case, as shown in the following figure...

Ironpython2.JPG

Hope you enjoyed this article.

Thanks !!!


Similar Articles