Пример #1
0
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
            dynamic       calcRate      = scriptRuntime.UseFile("CalcTax.py");

            label6.Content = calcRate.CalcTax(Convert.ToDecimal(label5.Content)).ToString();
        }
Пример #2
0
        // MerlinWeb:
        public static void Scenario_CompiledCode()
        {
            var runtime = ScriptRuntime.CreateFromConfiguration();

            // code behind linked from .aspx file:
            string url = "merlin_web_page_code_behind.py";

            var          engine       = runtime.GetEngineByFileExtension(Path.GetExtension(url));
            CompiledCode compiledCode = engine.CreateScriptSourceFromFile(url).Compile();

            // 5 requests for same page:
            for (int i = 0; i < 5; i++)
            {
                // on each request, create new scope with a custom dictionary for latebound look up of elements on page.
                // This uses a derived type of DynamicObject for convenience.
                var page = new DynamicPage();

                ScriptScope scope = engine.CreateScope(page);
                compiledCode.Execute(scope);

                Action onLoad;
                if (scope.TryGetVariable <Action>("OnLoad", out onLoad))
                {
                    onLoad();
                }

                Func <string> render = (scope as dynamic).Render;
                Console.WriteLine(render());
            }
        }
Пример #3
0
        public static void Init()
        {
            var runtime = ScriptRuntime.CreateFromConfiguration();

            Engine = runtime.GetEngine("Ruby");
            _Scope = Engine.CreateScope();
        }
Пример #4
0
        internal void method2()
        {
            ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
            dynamic       ccalcRate     = scriptRuntime.UseFile("AmountDisc.py");

            ccalcRate.CalcTax("124m");  //直接调用脚本的函数
        }
Пример #5
0
        private static void Scenario_REPL(IEnumerable <string> lines)
        {
            var runtime = ScriptRuntime.CreateFromConfiguration();

            // Assume user has chosen to execute a file, and you want to set the REPL's context to that file's scope.
            dynamic      scope  = runtime.ExecuteFile("user_commands.rb");
            ScriptEngine engine = scope.Engine;

            Console.Write("{0}> ", engine.Setup.DisplayName);
            foreach (string line in lines)
            {
                if (line.StartsWith("."))
                {
                    // change the current language:
                    engine = runtime.GetEngine(line.Substring(1).Trim());
                }
                else
                {
                    // Use interactive script source to enable interactive code specific language features:
                    ScriptSource input = engine.CreateScriptSourceFromString(line, SourceCodeKind.InteractiveCode);

                    try {
                        // execute the command:
                        scope._ = input.Execute(scope);
                    } catch (Exception exception) {
                        // display the exception in a format of the current language:
                        Console.WriteLine(engine.GetService <ExceptionOperations>().FormatException(exception));
                    }
                }

                Console.Write("{0}> ", engine.Setup.DisplayName);
            }
        }
Пример #6
0
        public DynamicExportObject(Connection conn, ObjectPath object_path, object obj) : base(conn, object_path, obj)
        {
            //this.obj = obj;
            ScriptRuntime runtime = ScriptRuntime.CreateFromConfiguration();

            ops = runtime.CreateOperations();
        }
Пример #7
0
        /// <summary>
        /// Shows setting Host OM on globals so that dynamic languages
        /// can import, require, etc., to access the host's OM.
        /// </summary>
        public static void Scenario_ExecuteFile_Push()
        {
            var hostOM  = new MyHostObjectModel();
            var runtime = ScriptRuntime.CreateFromConfiguration();

            runtime.Globals.SetVariable("App", hostOM);
            runtime.ExecuteFile("register_user_commands.py");

            hostOM.UserCommands["foo"]();
        }
Пример #8
0
        /*
         * <?xml version="1.0" encoding="utf-8" ?>
         * <configuration>
         *      <configSections>
         *              <section name="microsoft.scripting"
         *                      type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
         *      </configSections>
         *      <microsoft.scripting>
         *              <languages>
         *                      <language names="IronPython;Python;py" extensions=".py"
         *                              displayName="IronPython v2.6"
         *                              type="IronPython.Runtime.PythonContext, IronPython, Version=2.6.10920.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
         *
         *                      <language names="IronRuby;Ruby;rb" extensions=".rb"
         *                              displayName="IronRuby v1.0"
         *                              type="IronRuby.Runtime.RubyContext, IronRuby, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
         *
         *              </languages>
         *      </microsoft.scripting>
         * </configuration>
         */
        #endregion

        #region Constructors
        /// <summary>
        /// Create new instance with given attribute
        /// </summary>
        /// <param name="languageId"></param>
        public ScriptEnvironment(string languageId)
        {
            LanguageId = languageId;

            Runtime    = ScriptRuntime.CreateFromConfiguration();
            Scope      = Runtime.CreateScope();
            Operations = Runtime.CreateOperations();
            Engine     = Runtime.GetEngine(LanguageId);

            codeCache = new Dictionary <int, CompiledCode>();
        }
        private void OnCalculateTax(object sender, RoutedEventArgs e)
        {
            ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
            dynamic       calcRate      = scriptRuntime.UseFile("Scripts/CalcTax.py");
            decimal       discountedAmount;

            if (!decimal.TryParse(textDiscAmount.Text, out discountedAmount))
            {
                discountedAmount = Convert.ToDecimal(totalAmt.Text);
            }
            textTaxAmount.Text = calcRate.CalcTax(discountedAmount).ToString();
        }
Пример #10
0
 /// <summary>
 /// 构造函数,初始化Python引擎
 /// </summary>
 static PythonDynamicScriptRuntime()
 {
     try
     {
         ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
         _scriptEngine = scriptRuntime.GetEngine("python");
     }
     catch (Exception ex)
     {
         throw new Exception("内部加载Python运行时失败,请检查你的配置文件,是否配置了正确的microsoft.scripting节点", ex);
     }
 }
Пример #11
0
        /*
         * 运行此程序需要配置环境 详情网上查询
         */
        internal void method1()
        {
            string        scriptToUse   = "AmountDisc.py"; //这里以python为例
            ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
            ScriptEngine  pythEng       = scriptRuntime.GetEngine("Python");
            ScriptSource  source        = pythEng.CreateScriptSourceFromFile(scriptToUse);
            ScriptScope   scope         = pythEng.CreateScope();

            scope.SetVariable("prodCount", 123);
            scope.SetVariable("amt", 124m);
            source.Execute(scope);
            var ret = scope.GetVariable("retAmt").ToString();
        }
Пример #12
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var scriptToUse   = CostRadioButton.IsChecked.Value ? "AmountDisc.py" : "CountDisc.py";
            var scriptRuntime = ScriptRuntime.CreateFromConfiguration();
            var rbEng         = scriptRuntime.GetEngine("python");
            var source        = rbEng.CreateScriptSourceFromFile(scriptToUse);
            var scope         = rbEng.CreateScope();

            scope.SetVariable("prodCount", Convert.ToInt32(totalItems.Text));
            scope.SetVariable("amt", Convert.ToDecimal(totalAmt.Text));
            source.Execute(scope);
            label5.Content = scope.GetVariable("retAmt").ToString();
        }
Пример #13
0
        public void RunFromFile()
        {
            ScriptRuntime env = ScriptRuntime.CreateFromConfiguration();

            var scope = env.Globals;

            scope.SetVariable("b", 7);

            scope = env.ExecuteFile("IronPython.py");

            var a = scope.GetVariable <int>("a");

            Console.WriteLine(a);
        }
Пример #14
0
        private void loadRunTime()
        {
            m_output  = new MemoryStream();
            m_runTime = ScriptRuntime.CreateFromConfiguration();

            m_runTime.IO.SetOutput(m_output, new StreamWriter(m_output));
            m_runTime.IO.SetErrorOutput(m_output, new StreamWriter(m_output));

            Assembly pluginsAssembly = Assembly.LoadFile(IO.IOHelper.MapPath(IO.SystemDirectories.Bin + "/umbraco.dll"));

            m_runTime.LoadAssembly(pluginsAssembly);

            m_runTime.LoadAssembly(typeof(String).Assembly);
            m_runTime.LoadAssembly(typeof(Uri).Assembly);
            m_runTime.LoadAssembly(typeof(umbraco.presentation.nodeFactory.Node).Assembly);
        }
Пример #15
0
        private static readonly int m_CommandDirCheckingInterval = 1000 * 60 * 5;// 5 minutes

        static DynamicCommandLoader()
        {
            m_ScriptRuntime = ScriptRuntime.CreateFromConfiguration();

            List <string> fileExtensions = new List <string>();

            foreach (var fxts in m_ScriptRuntime.Setup.LanguageSetups.Select(s => s.FileExtensions))
            {
                fileExtensions.AddRange(fxts);
            }

            m_CommandExtensions = new HashSet <string>(fileExtensions, StringComparer.OrdinalIgnoreCase);

            m_ServerCommandStateLib   = new Dictionary <string, ServerCommandState>(StringComparer.OrdinalIgnoreCase);
            m_CommandDirCheckingTimer = new Timer(OnCommandDirCheckingTimerCallback, null, m_CommandDirCheckingInterval, m_CommandDirCheckingInterval);
        }
Пример #16
0
        /// <summary>
        /// Shows discovering command implementations from globals in scope.
        /// Above user code explicitly added commands, but this code finds
        /// commands matching a delegate type.
        /// </summary>
        public static void Scenario_ExecuteFile_Pull()
        {
            var runtime = ScriptRuntime.CreateFromConfiguration();
            var scope   = runtime.ExecuteFile("user_commands.rb");

            var commands = new Dictionary <string, Action>();

            foreach (string name in scope.GetVariableNames())
            {
                try {
                    commands[name] = (Action)scope.GetVariable(name);
                } catch (RuntimeBinderException) {
                }
            }

            foreach (var command in commands.Values)
            {
                command();
            }
        }
        private void OnCalculateDiscount(object sender, RoutedEventArgs e)
        {
            string scriptToUse;

            if (CostRadioButton.IsChecked.Value)
            {
                scriptToUse = "Scripts/AmountDisc.py";
            }
            else
            {
                scriptToUse = "Scripts/CountDisc.py";
            }
            ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
            ScriptEngine  rbEng         = scriptRuntime.GetEngine("python");
            ScriptSource  source        = rbEng.CreateScriptSourceFromFile(scriptToUse);
            ScriptScope   scope         = rbEng.CreateScope();

            scope.SetVariable("prodCount", Convert.ToInt32(totalItems.Text));
            scope.SetVariable("amt", Convert.ToDecimal(totalAmt.Text));
            source.Execute(scope);
            textDiscAmount.Text = scope.GetVariable("retAmt").ToString();
        }
Пример #18
0
        public MainWindow()
        {
            var scriptRuntime = ScriptRuntime.CreateFromConfiguration();

            _engine = scriptRuntime.GetEngine("python");
            var searchPath = new List <string>
            {
                "G:\\version1",
                "C:\\Users\\Anaconda2\\Lib",
                "C:\\Users\\Anaconda2\\Lib\\site-packages",
                "C:\\Users\\Anaconda2\\Lib\\site-packages\\skimage\\_shared",
                "C:\\Users\\Anaconda2\\Lib\\site-packages\\numpy",
                "C:\\Users\\Anaconda2\\Lib\\site-packages\\matplotlib",
                "C:\\Users\\Anaconda2\\Lib\\site-packages\\scikit_image-0.13.0-py2.7.egg-info",
                "C:\\Users\\Anaconda2\\Lib\\site-packages\\numpy-1.12.1-py2.7.egg-info",
                "C:\\Users\\Anaconda2\\Lib\\site-packages\\numpy\\core"
            };

            _engine.SetSearchPaths(searchPath);
            _imageInfos = new List <ImageInfo>();
            InitializeComponent();
        }
Пример #19
0
 public ScriptContext()
 {
     ScriptRuntime = ScriptRuntime.CreateFromConfiguration();
 }