从IronPython脚本(lightswitch)访问主机类

时间:2016-01-14 01:13:40

标签: c# ironpython visual-studio-lightswitch

我是新手,所以我希望这个问题能够很好地形成,让别人明白我的要求,如果不是,我很乐意添加更多细节。我试图从python脚本引用一个在lightswitch应用程序的服务器端定义的变量。以下文章介绍了如何从python脚本访问宿主类。

Access host class from IronPython script

我服务器端的代码是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
using System.IO.Ports;
using System.Threading;
using IronPython.Hosting;

namespace LightSwitchApplication
{
 public partial class ApplicationDataService     
{
    partial void ServerCommands_Inserting(ServerCommand entity)
    { 
        switch (entity.ClientCommand)
        {
            case "RunPythonScript":


             var engine = Python.CreateEngine();
             var searchPaths = engine.GetSearchPaths();
             searchPaths.Add(@"C:\Temp");
             engine.SetSearchPaths(searchPaths);

             var mainfile = @"C:\Temp\script.py";
             var scope = engine.CreateScope();
             engine.CreateScriptSourceFromFile(mainfile).Execute(scope);
             var param1 = entity.Param1;                       
             engine.Execute(scope);

如何从Python脚本中引用下面的服务器端变量?

entity.Param1

在python脚本中,我试图导入一个允许我访问变量的服务器端类

import clr
clr.AddReference("Microsoft.Lightswitch.Application")

但.Server引用不可用...只有.Base可用。

from Microsoft.Lightswitch.Framework.Base import

我不知道Framework.Server类是否是正确的,只是在这一点上猜测。谢谢!

enter image description here

1 个答案:

答案 0 :(得分:0)

您只需将entity设置为范围的变量即可。您也可以将其传递给script.py中的函数。例如:

你的python脚本:

class SomeClass:
    def do(self, entity):
        print entity.Param1

您的c#代码如下所示:

var engine = Python.CreateEngine();
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\Temp");
engine.SetSearchPaths(searchPaths);

var mainfile = @"C:\Temp\script.py";
var scope = engine.CreateScope();

// Execute your code
engine.CreateScriptSourceFromFile(mainfile).Execute(scope);
// Create a class instance
var type = scope.GetVariable("SomeClass");
var instance = engine.Operations.CreateInstance(type);
// Call `do` method
engine.Operations.InvokeMember(instance, "do", entity); // PASS YOUR ENTITY HERE

在此之后,您可以在IronPython脚本中访问您的完整实体。您不需要clr.AddReference("Microsoft.Lightswitch.Application")

此外,第二次执行(engine.Execute(scope);)似乎不是必需的。 也许这有助于你。

相关问题