IronPython - Editor for end-user

2k Views Asked by At

We're currently investigating how we can embed IronPython (scripting) into our C# application.

We see the benefits it will provide to our end users, giving them the ability to hook into our application but one question that keeps arising is how do we provide the end-user with code editing abilities that are aware of the different entry contexts in our application.

I know that we can provide a simple text editor with syntax highlighting but how do we go one step further and allow a user to test their scripts against objects that we expose from our application. Keeping in mind that we will expose different objects depending upon the context of the entry-point.

How do you allow end users to test, write and edit scripts in your application?

PS - I am new here so let me know if I am not doing this right!!!

2

There are 2 best solutions below

0
On

Maybe what you want is to use the Visual Studio 2010 Shell Isolated. It can be used to provide a visual studio environment within an application, kind of how VBA used to be. As far was Python support you can look at IPyIsolatedShell

1
On

You could host IronPython in your C# application. Then you can pass in variables from your C# application and execute IronPython code which uses them. Dino Viehland did a talk at PDC about this called Using Dynamic Languages to Build Scriptable Applications. Dino made the source code for the application he created at the PDC available but it is using an older version of IronPython.

Here is some code for IronPython 2.7.1 that shows you how you can host IronPython in a few lines of code.

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

public class MyIronPythonHost
{
    ScriptEngine scriptEngine;
    ScriptScope scriptScope;

    public void Initialize(MyApplication myApplication)
    {
        scriptEngine = Python.CreateEngine();
        scriptScope = scriptEngine.CreateScope();
        scriptScope.SetVariable("app", myApplication);
    }

    public void RunPythonCode(string code)
    {
        ScriptSource scriptSource = scriptEngine.CreateScriptSourceFromString(code);
        scriptSource.Execute(scriptScope);
    }
}

The code above passes an application object called MyApplication to IronPython via a script scope and sets its variable name to be app. This app variable is then available to the IronPython code where it can call methods on it, access properties, etc.

The final method in the code above is the RunPythonCode method which takes in the IronPython code written by the user and executes it.

Going further than this and allowing the user to debug their IronPython code in a similar way to how you can debug VBA macros is a major piece of development work however.