Esempio n. 1
0
        /// <summary>
        /// Load the core module that offers access to the simulation environment.
        /// </summary>
        public void LoadCoreModule()
        {
            scope = engine.CreateScope();

            // Allow scriptable access to...
            scope.SetVariable("status", Program.form.toolStripStatus);  // Statusbar.
            scope.SetVariable("log", Program.form.txtLog); // Simulation log.
            try
            {
                e_script = engine.CreateScriptSourceFromFile("syeon.py");
                e_script.Execute(scope);
            }
            catch(Exception e)
            {
                DialogResult ans = MessageBox.Show(
                e.Message, SSE, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
                if(ans == DialogResult.Abort)
                {
                    Program.form.Close();
                }
                else if(ans == DialogResult.Retry)
                {
                    LoadCoreModule(); // Recursion rules!
                }
            }
        }
Esempio n. 2
0
        public RubyInstaller(string fileName, List<Assembly> assemblies)
        {
            this.fileName = fileName;
            assemblies.AddRange(new[] { typeof(IServiceLocator).Assembly, typeof(IConvention).Assembly });

            if(engine == null)
            {
               lock(@lock)
               {
                   if(engine == null)
                   {
                       engine = IronRuby.Ruby.CreateEngine();
                       scope = engine.CreateScope();

                       assemblies.ForEach(a => engine.Runtime.LoadAssembly(a));
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.Installer.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.SiegeDSL.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RubyRegistration.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.RegistrationHandlerFactory.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.DefaultRegistrationHandler.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.DefaultInstanceRegistrationHandler.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.ConditionalRegistrationHandler.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.ConditionalInstanceRegistrationHandler.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.NamedRegistrationHandler.rb");
                       LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.NamedInstanceRegistrationHandler.rb");
                   }
               }
            }

            this.source = engine.CreateScriptSourceFromFile(this.fileName);
        }
Esempio n. 3
0
        public ICondition Create()
        {
            _engine = Ruby.CreateEngine();

            string rubyRuleTemplate;
            using (var stream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream(_dslFileName))
            {
                using (var reader = new StreamReader(stream))
                {
                    rubyRuleTemplate = reader.ReadToEnd();
                }
            }
            rubyRuleTemplate = rubyRuleTemplate.Replace("$ruleAssembly$", _contextType.Namespace.Replace(".", "::"));
            rubyRuleTemplate = rubyRuleTemplate.Replace("$contextType$", _contextType.Name);
            rubyRuleTemplate = rubyRuleTemplate.Replace("$condition$", _condition);
            _source = _engine.CreateScriptSourceFromString(rubyRuleTemplate);

            var scope = _engine.CreateScope();
            _assemblies.ForEach(a => _engine.Runtime.LoadAssembly(a));

            _engine.Execute(_source.GetCode(), scope);
            var @class = _engine.Runtime.Globals.GetVariable("RubyRuleFactory");

            var installer = _engine.Operations.CreateInstance(@class);
            var rule = installer.Create();

            return (ICondition)rule;
        }
Esempio n. 4
0
 public Communicate(string python, Jardin jardin)
 {
     //création du lien avec le script python
     engine = Python.CreateEngine();
     script = engine.CreateScriptSourceFromFile(python);
     scope = engine.CreateScope();
     this.jardin = jardin;
 }
 public override void ErrorReported(ScriptSource source, string message, Microsoft.Scripting.SourceSpan span, int errorCode, Microsoft.Scripting.Severity severity)
 {
     Errors.Add(new ProgramError() {
         Line = span.Start.Line,
         Column = span.Start.Column,
         ErrorMessage = message,
         ErrorNumber = errorCode.ToString(),
         CodeBlock = blockType
     });
 }
Esempio n. 6
0
        private void InitScope(ScriptSource script)
        {
            Request = new PythonRequest();

            Scope.SetVariable("request", Request);
            Scope.SetVariable("self", peripheral);
            Scope.SetVariable("size", peripheral.Size);

            source = script;
        }
Esempio n. 7
0
        public ScriptFilter(string scriptText)
        {
            Validation.CheckObject("scriptText", scriptText);

            //initialize python
            runtime = Python.CreateRuntime();
            engine = Python.GetEngine(runtime);
            //load the script
            source = engine.CreateScriptSourceFromString(scriptText);
            script = source.Compile();
        }
Esempio n. 8
0
 public Form1()
 {
     InitializeComponent();
     imp_dir = Directory.GetCurrentDirectory();
     myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
     formGraphics = pictureBox1.CreateGraphics();
     pictureBox1.BackColor = Color.White;
     myBrush = new System.Drawing.SolidBrush(Color.Red);
     m_engine = Python.CreateEngine();
     m_scope = m_engine.CreateScope();
     source = m_engine.CreateScriptSourceFromFile("center_iron.py");
 }
Esempio n. 9
0
 /// <summary>
 /// Creates a Lexer instance with the given source of text.
 /// </summary>
 /// <param name="engine"> The associated script engine. </param>
 /// <param name="source"> The source of javascript code. </param>
 public Lexer(ScriptEngine engine, ScriptSource source)
 {
     if (engine == null)
         throw new ArgumentNullException("engine");
     if (source == null)
         throw new ArgumentNullException("source");
     this.engine = engine;
     this.source = source;
     this.reader = source.GetReader();
     this.lineNumber = 1;
     this.columnNumber = 1;
 }
Esempio n. 10
0
 /// <summary>
 /// Load the simulation script.
 /// </summary>
 /// <param name="script"></param>
 public void LoadSimulationScript(string script)
 {
     e_script = engine.CreateScriptSourceFromString(script);
     try
     {
         e_script.Execute(scope);
     }
     catch (Exception e)
     {
         MessageBox.Show
         (e.Message, SSE, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 11
0
        public dynamic Create()
        {
            if (this.filePath == "" || !File.Exists(this.filePath))
            {
                throw new FileNotFoundException();
            }

            source = engine.CreateScriptSourceFromFile(this.filePath);
            scope = engine.CreateScope();

            source.Execute(scope);
            return scope;
        }
Esempio n. 12
0
        public override void Add(SourceUnit sourceUnit, string message, SourceSpan span, int errorCode, Severity severity) {
            if (_listener != null) {

                ScriptSource scriptSource;
                if (sourceUnit != _source.SourceUnit) {
                    scriptSource = new ScriptSource(_source.Engine.Runtime.GetEngine(sourceUnit.LanguageContext), sourceUnit);
                } else {
                    scriptSource = _source;
                }

                _listener.ErrorReported(scriptSource, message, span, errorCode, severity);
            } else {
                throw new SyntaxErrorException(message, sourceUnit, span, errorCode, severity);
            }
        }
Esempio n. 13
0
        public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity) {
            // Note that we cannot use "source.SourceUnit" since "source" may be a proxy object, and we will not be able to marshall 
            // "source.SourceUnit" to the current AppDomain

            string code = null;
            string line = null;
            try {
                code = source.GetCode();
                line = source.GetCodeLine(span.Start.Line);
            } catch (System.IO.IOException) {
                // could not get source code.
            }

            _errorSink.Add(message, source.Path, code, line, span, errorCode, severity);
        }
Esempio n. 14
0
 /// <summary>
 /// Creates a new MethodGenerator instance.
 /// </summary>
 /// <param name="engine"> The script engine. </param>
 /// <param name="scope"> The initial scope. </param>
 /// <param name="source"> The source of javascript code. </param>
 /// <param name="options"> Options that influence the compiler. </param>
 protected MethodGenerator(ScriptEngine engine, Scope scope, ScriptSource source, CompilerOptions options)
 {
     if (engine == null)
         throw new ArgumentNullException("engine");
     if (scope == null)
         throw new ArgumentNullException("scope");
     if (source == null)
         throw new ArgumentNullException("source");
     if (options == null)
         throw new ArgumentNullException("options");
     this.Engine = engine;
     this.InitialScope = scope;
     this.Source = source;
     this.Options = options;
     this.StrictMode = this.Options.ForceStrictMode;
 }
Esempio n. 15
0
        public PythonInstance(string code, string className = "PyClass")
        {
            //creating engine and stuff
            engine = Python.CreateEngine();
            scope = engine.CreateScope();

            //loading and compiling codes
            source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
            compiled = source.Compile();

            //now executing this code (the code should contain a class)
            compiled.Execute(scope);

            //now creating an object that could be used to access the stuff inside a python script
            pythonClass = engine.Operations.Invoke(scope.GetVariable(className));
        }
Esempio n. 16
0
        /// <summary>
        ///     Executes a Python script with custom variable names. Script may be a string
        ///     read from a file, for example. Pass a list of names (matching the variable
        ///     names in the script) to bindingNames and pass a corresponding list of values
        ///     to bindingValues.
        /// </summary>
        /// <param name="code">Python script as a string.</param>
        /// <param name="bindingNames">Names of values referenced in Python script.</param>
        /// <param name="bindingValues">Values referenced in Python script.</param>
        public static object EvaluateIronPythonScript(
            string code,
            IList bindingNames,
            [ArbitraryDimensionArrayImport] IList bindingValues)
        {
            if (code != prev_code)
            {
                ScriptSource script = Python.CreateEngine().CreateScriptSourceFromString(code);
                script.Compile();
                prev_script = script;
                prev_code = code;
            }

            ScriptEngine engine = prev_script.Engine;
            ScriptScope scope = engine.CreateScope();

            int amt = Math.Min(bindingNames.Count, bindingValues.Count);

            for (int i = 0; i < amt; i++)
            {
                scope.SetVariable((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]));
            }

            try
            {
                OnEvaluationBegin(engine, scope, code, bindingValues);
                prev_script.Execute(scope);
            }
            catch (Exception e)
            {
                OnEvaluationEnd(false, engine, scope, code, bindingValues);
                var eo = engine.GetService<ExceptionOperations>();
                string error = eo.FormatException(e);
                throw new Exception(error);
            }

            OnEvaluationEnd(true, engine, scope, code, bindingValues);

            var result = scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null;

            return OutputMarshaler.Marshal(result);
        }
Esempio n. 17
0
		public IEnumerable<IronPythonTypeWrapper> GetTypesFromScript(ScriptSource script,
			IEnumerable<Type> injectTypes = null)
		{
			CompiledCode code = script.Compile();
			var scope = _engine.CreateScope();

			var types = new[] {typeof (IronPythonImportDefinition)}.ToList();
			if (injectTypes != null)
			{
				types.AddRange(injectTypes);
			}

			foreach (Type type in types)
			{
				scope.InjectType(type);
			}
			using (var libStream = GetType().Assembly.GetManifestResourceStream("Altman.Pex.lib.py"))
			using ( var libText = new StreamReader(libStream))
			{
				var libSource = _engine.CreateScriptSourceFromString(libText.ReadToEnd());
				libSource.Execute(scope);
			}


			// "force" all classes to be new style classes
			dynamic metaclass;
			if (!scope.TryGetVariable("__metaclass__", out metaclass))
			{
				scope.SetVariable("__metaclass__", _engine.GetBuiltinModule().GetVariable("type"));
			}

			scope.SetVariable("clr", _engine.GetClrModule());
			code.Execute(scope);

			var pluginClasses = scope.GetItems()
				.Where(kvp => kvp.Value is PythonType && !kvp.Key.StartsWith("__"))
				.Select(kvp => new IronPythonTypeWrapper(_engine, kvp.Key, kvp.Value, scope.GetVariableHandle(kvp.Key)))
				.Where(kvp => !types.Contains(kvp.Type));

			return pluginClasses;
		}
Esempio n. 18
0
        public PythonInstance(string className = "PyClass")
        {
            string code = @"
            import sys
            sys.path.append(r'C:\Program Files\IronPython 2.7\Lib')
            import os
            import hashlib
            import urllib2
            class PyClass:
            def __init__(self):
            pass

            def somemethod(self):
            print 'in some method'

            def isodd(self, n):
            return 1 == n % 2

            def get_hash(self,name):
            readsize = 64 * 1024
            with open(name, 'rb') as f:
            size = os.path.getsize(name)
            data = f.read(readsize)
            f.seek(-readsize, os.SEEK_END)
            data += f.read(readsize)
            return hashlib.md5(data).hexdigest()
            ";
            //creating engine and stuff
            engine = Python.CreateEngine();
            scope = engine.CreateScope();

            //loading and compiling code
            source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
            compiled = source.Compile();

            //now executing this code (the code should contain a class)
            compiled.Execute(scope);

            //now creating an object that could be used to access the stuff inside a python script
            pythonClass = engine.Operations.Invoke(scope.GetVariable(className));
        }
Esempio n. 19
0
        public ICondition Create()
        {
            this.engine = Ruby.CreateEngine();
            var rubyRuleTemplate = String.Empty;
            using(var stream = new StreamReader(this.dslFileName))
            {
                rubyRuleTemplate = stream.ReadToEnd();
            }
            rubyRuleTemplate = rubyRuleTemplate.Replace("$ruleAssembly$", this.contextType.Namespace.Replace(".", "::"));
            rubyRuleTemplate = rubyRuleTemplate.Replace("$contextType$", this.contextType.Name);
            rubyRuleTemplate = rubyRuleTemplate.Replace("$condition$", this.condition);
            this.source = engine.CreateScriptSourceFromString(rubyRuleTemplate);
            
            var scope = engine.CreateScope();
            assemblies.ForEach(a => engine.Runtime.LoadAssembly(a));

            engine.Execute(source.GetCode(), scope);
            var @class = engine.Runtime.Globals.GetVariable("RuleRuleFactory");

            var installer = engine.Operations.CreateInstance(@class);
            var rule = installer.Create();

            return (ICondition) rule;
        }
Esempio n. 20
0
        /// <summary>
        /// Load the script from disk, recompile it into bytecode, and execute it.
        /// </summary>
        /// <returns>boolean indicating whether the script was reloaded or not</returns>
        public bool Load()
        {
            String scriptText;
            try
            {
                scriptText = File.ReadAllText(Path);
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Couldn't open script {0}: {1}", Path, e.ToString());
                Disabled = true;
                CompilationError = e.ToString();
                return false;
            }

            Source =
                Processor.Engine.CreateScriptSourceFromString(scriptText);

            Name = System.IO.Path.GetFileName(Path).ToLower();

            try
            {
                Compile();
                Compiled.Execute(Scope);
                Disabled = false;
            }
            catch (Exception e)
            {
                var pythonFrames = PythonOps.GetDynamicStackFrames(e);
                var exceptionString = Processor.Engine.GetService<ExceptionOperations>().FormatException(e);
                Logger.ErrorFormat("script {0} encountered error, Python stack follows", Path);
                Logger.ErrorFormat("{0}", exceptionString);
                Disabled = true;
                CompilationError = exceptionString;
                return false;
            }
            return true;
        }
Esempio n. 21
0
 public void setScriptFromString(string _sScript)
 {
     _source = _engine.CreateScriptSourceFromString(_sScript);
        CompiledCode codecheck = _source.Compile(_reporter);
        if (codecheck == null)
        {
        _source = null;
        // compilation failed - alert user
        throw new Exception("compilation failed");
        }
 }
Esempio n. 22
0
 public JavaScriptValue Execute(ScriptSource source, Stream compiledCode)
 {
     throw new NotSupportedException();
 }
Esempio n. 23
0
 public void Initialize(object state, ScriptSource scriptSource, SourceLocation initialLocation)
 {
     _tokenizer.Initialize(state, scriptSource.SourceUnit.GetReader(), scriptSource.SourceUnit, initialLocation);
 }
Esempio n. 24
0
        public CompiledCode Compile(string code)
        {
            ScriptSource src = _engine.CreateScriptSourceFromString(code, SourceCodeKind.File);

            return(src.Compile());
        }
Esempio n. 25
0
 /// <summary>
 /// Do this only once per correction, not for each subject separatly (would be much slower)
 /// </summary>
 public void Initialize(PythonCode code)
 {
     this.code = code;
     source    = engine.CreateScriptSourceFromString(code.Script);
 }
Esempio n. 26
0
        private void addBtn_Click(object sender, EventArgs e)
        {
            if (kolicinaTB.Text == "")
            {
                potrebnoPoljeLabel.Text = "*Obvezno polje";
                return;
            }
            if (kolicinaTB.Text.Contains("."))
            {
                bool isPromjenjivaKolicina = bool.Parse(proizvodiGV.Rows[mSelectedPosition].Cells["promjenjivaKolicina"].Value.ToString());
                if (!isPromjenjivaKolicina)
                {
                    potrebnoPoljeLabel.Text = "*Samo cijeli broj";
                    return;
                }
            }

            if (Double.Parse(kolicinaTB.Text) < 0)
            {
                potrebnoPoljeLabel.Text = "*Kriva vrijednost";
                return;
            }

            potrebnoPoljeLabel.Text = "";
            Double kupljenaKolicina;

            kupljenaKolicina = Double.Parse(kolicinaTB.Text);

            String naziv          = proizvodiGV.Rows[mSelectedPosition].Cells["naziv"].Value.ToString();
            String proizvodjac    = proizvodiGV.Rows[mSelectedPosition].Cells["proizvodac"].Value.ToString();
            double cijena         = Double.Parse(proizvodiGV.Rows[mSelectedPosition].Cells["cijena"].Value.ToString());
            String zadanaKolicina = proizvodiGV.Rows[mSelectedPosition].Cells["kolicina"].Value.ToString();

            int razinaPoreza = int.Parse(proizvodiGV.Rows[mSelectedPosition].Cells["porez"].Value.ToString());

            double cijenaSPorezom;
            double zaPlatiti = 0;

            String pythonPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

            pythonPath = pythonPath.Replace("\\Blagajna\\bin\\Debug", "");
            ScriptSource ss = m_pyEngine.CreateScriptSourceFromFile(pythonPath + "\\Calculations\\Calculations.py");

            ss.Execute(m_pyScope);

            Func <double, double, double> IzracunCijeneSPorezom = m_pyScope.GetVariable <Func <double, double, double> >("IzracunCijeneSPorezom");

            cijenaSPorezom = IzracunCijeneSPorezom(cijena, razinaPoreza);
            cijenaSPorezom = Math.Round(cijenaSPorezom, 2);

            Func <double, double, double> IzracunKonacneCijeneStavke = m_pyScope.GetVariable <Func <double, double, double> >("IzracunKonacneCijeneStavke");

            zaPlatiti = IzracunKonacneCijeneStavke(cijenaSPorezom, kupljenaKolicina);
            zaPlatiti = Math.Round(zaPlatiti, 2);

            mUkupnaCijena += zaPlatiti;

            Stavka stavka = new Stavka();

            stavka = new Stavka(naziv, proizvodjac, zadanaKolicina, cijenaSPorezom, kupljenaKolicina, zaPlatiti);
            racun.Add(stavka);

            racunGV.DataSource = racun;

            kolicinaTB.Text  = "1";
            searchTB.Text    = "";
            selectedTB.Text  = "";
            ukupnoLabel.Text = mUkupnaCijena.ToString();

            RefreshData();
        }
Esempio n. 27
0
 public ErrorListenerProxySink(ScriptSource source, ErrorListener listener) {
     _listener = listener;
     _source = source;
 }
Esempio n. 28
0
 // TODO
 public string GetErroredCode(ScriptSource source, SourceSpan span)
 {
     return(null);
 }
Esempio n. 29
0
        public BuildResult Build(ScriptSource source, IDictionary <string, string> substitutions, bool debug)
        {
            var magic = new PixieDust(Compile(source));

            return(magic.Apply(substitutions, debug));
        }
Esempio n. 30
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     Errors.Add(string.Format("{0} (line {1})", message, span.Start.Line));
 }
Esempio n. 31
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     errors.Add(new Error {
         source = source, message = message, span = span, errorCode = errorCode, severity = severity
     });
 }
Esempio n. 32
0
        protected virtual ScriptCodeParseResult GetCommandProperties(string code)
        {
            ScriptSource command = _engine.CreateScriptSourceFromString(code, SourceCodeKind.InteractiveCode);

            return(command.GetCodeProperties(_engine.GetCompilerOptions(_scope)));
        }
Esempio n. 33
0
        protected virtual int RunFile(ScriptSource source) {
            int result = 1;

            if (Options.HandleExceptions) {
                try {
                    result = source.ExecuteProgram();
                } catch (Exception e) {
                    UnhandledException(e);
                }
            } else {
                result = source.ExecuteProgram();
            }

            return result;
        }
Esempio n. 34
0
        /// <summary>
        /// Starts the $PythonBehaviour
        /// </summary>
        /// <param name="classname">Name of the Script</param>
        public bool Awakening(String classname)
        {
            scope = engine.CreateScope();
            scope.SetVariable("this", this);
            scope.SetVariable("gameObject", gameObject);
            scope.SetVariable("transform", transform);
            scope.SetVariable("enabled", enabled);
            scope.SetVariable("useAPI", new Action(UseAPI));
            scope.SetVariable("disableAPI", new Action(DisableAPI));

            if (Settings.useAPI)
            {
                Besiege.SetUp();
                scope.SetVariable("besiege", Besiege._besiege);
            }
            spaar.ModLoader.Game.OnSimulationToggle += GameOnOnSimulationToggle;
            spaar.ModLoader.Game.OnLevelWon         += GameOnOnLevelWon;

            foreach (string @ref in refs.Where(@ref => !String.IsNullOrEmpty(@ref)))
            {
                try
                {
                    #region OBSOLETE

                    /*
                     * Assembly assembly = Assembly.Load(@ref);
                     * var namespaces = assembly.GetTypes()
                     *  .Select(t => t.Namespace)
                     *  .Distinct();
                     * String[] lines = Util.splitStringAtNewline(sauce);
                     * for (int i = 0; i < lines.Length; i++)
                     * {
                     *  if (!lines[i].Contains("import") && !String.IsNullOrEmpty(lines[i]))
                     *  {
                     *      foreach (string ns in namespaces)
                     *      {
                     *          if (!String.IsNullOrEmpty(ns))
                     *          {
                     *              if (lines[i].Contains((ns + ".")))
                     *              {
                     *                  lines[i] = Regex.Replace(lines[i], ns + ".", string.Empty);
                     *              }
                     *          }
                     *      }
                     *  }
                     *  lines[i] += Util.getNewLine();
                     * }
                     * lines = lines.Where(x => !string.IsNullOrEmpty(x) && !x.Equals("\r\n") && !x.Equals("\r") && !x.Equals("\n") && !String.IsNullOrEmpty(x.Trim())).ToArray();
                     * sauce = String.Concat(lines);
                     */
                    #endregion

                    engine.Runtime.LoadAssembly(Assembly.Load(@ref));
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    return(false);
                }
            }
            ScriptSource  source = engine.CreateScriptSourceFromString(sauce);
            ErrorListener error  = new ErrorSinkProxyListener(ErrorSink.Default);
            code = source.Compile(error);
            if (code == null)
            {
                Debug.LogError(error);
                return(false);
            }
            code.Execute(scope);
            pythonClass = engine.Operations.Invoke(scope.GetVariable(classname));
            CallMethod("Awake");
            return(true);
        }
Esempio n. 35
0
 /// <summary>
 /// Creates a new GlobalMethodGenerator instance.
 /// </summary>
 /// <param name="engine"> The script engine. </param>
 /// <param name="source"> The source of javascript code. </param>
 /// <param name="options"> Options that influence the compiler. </param>
 public GlobalMethodGenerator(ScriptEngine engine, ScriptSource source, CompilerOptions options)
     : base(engine, engine.CreateGlobalScope(), source, options)
 {
 }
Esempio n. 36
0
        private void PythonConsole(bool cmdLine)
        {
            Dictionary <string, object> options = new Dictionary <string, object>();

            options["Debug"] = true;

            var ipy    = Python.CreateRuntime(options);
            var engine = Python.GetEngine(ipy);

            try
            {
                string path = "";

                System.Version version = Application.Version;

                string ver = version.ToString();

                string release = "2020";

                switch (ver)
                {
                case "20":
                    release = "2016";
                    break;

                case "21.0.0.0":
                    release = "2017";
                    break;

                case "22.0.0.0":
                    release = "2018";
                    break;

                case "23.0.0.0":
                    release = "2019";
                    break;

                case "23.1.0.0":
                    release = "2020";
                    break;
                }

                if (!cmdLine)
                {
                    WF.OpenFileDialog ofd = new WF.OpenFileDialog();
                    ofd.Filter = "Python Script (*.py) | *.py";

                    if (ofd.ShowDialog() == WF.DialogResult.OK)
                    {
                        path = ofd.FileName;
                    }
                }
                else
                {
                    Document doc = Application.DocumentManager.MdiActiveDocument;
                    Editor   ed  = doc.Editor;

                    short fd = (short)Application.GetSystemVariable("FILEDIA");

                    // Ask the user to select a .py file

                    PromptOpenFileOptions pfo = new PromptOpenFileOptions("Select Python script to load");
                    pfo.Filter            = "Python script (*.py)|*.py";
                    pfo.PreferCommandLine = (cmdLine || fd == 0);
                    PromptFileNameResult pr = ed.GetFileNameForOpen(pfo);
                    path = pr.StringResult;
                }

                if (path != "")
                {
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\acmgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\acdbmgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\accoremgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\ACA\AecBaseMgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\ACA\AecPropDataMgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\C3D\AeccDbMgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\C3D\AeccPressurePipesMgd.dll", release)));
                    ipy.LoadAssembly(Assembly.LoadFrom(string.Format(@"C:\Program Files\Autodesk\AutoCAD {0}\acdbmgdbrep.dll", release)));


                    ScriptSource source       = engine.CreateScriptSourceFromFile(path);
                    CompiledCode compiledCode = source.Compile();
                    ScriptScope  scope        = engine.CreateScope();
                    compiledCode.Execute(scope);
                }
            }
            catch (System.Exception ex)
            {
                string message = engine.GetService <ExceptionOperations>().FormatException(ex);
                WF.MessageBox.Show(message);
            }

            return;
        }
Esempio n. 37
0
 public static void Reload()
 {
     try
     {
         source = pyEngine.CreateScriptSourceFromFile(RendererPyPath); // Load the script
         compiledCode = source.Compile();
         compiledCode.Execute(scope); // Create class object
         rendererClass = scope.GetVariable("Renderer"); // Retrieve the class object
         if (rendererClass != null)
             rendererImpl = objOps.Invoke(rendererClass) as IRenderer; // Create an instance of the Renderer
     }
     catch (Exception)
     {
         source = null;
         compiledCode = null;
         rendererClass = null;
         rendererImpl = null;
     }
 }
Esempio n. 38
0
        static void Main(string[] args)
        {
            string logPath = Path.Combine("logs", "log.txt");

            if (File.Exists(logPath))
            {
                File.Delete(logPath);
            }
            FileStream fileStream = new FileStream(logPath, FileMode.OpenOrCreate);

            //Console.WriteLine("------------------------以下是C#执行日志信息------------------------");
            try
            {
                string pythonCodePath = Path.Combine("templates", "pythonCode.txt");
                string sourceCodePath = Path.Combine("pys", "performer.py");
                if (!File.Exists(pythonCodePath))
                {
                    throw new Exception("Python模板不存在!");
                }
                if (!File.Exists(sourceCodePath))
                {
                    throw new Exception("Python源代码文件不存在!");
                }
                string[] pythonCodeContent = File.ReadAllText(pythonCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
                string[] sourceCodeContent = File.ReadAllText(sourceCodePath).Split(new string[] { "\r\n" }, StringSplitOptions.None);
                if (sourceCodeContent == null || sourceCodeContent.Length == 0)
                {
                    throw new Exception("Python代码不能为空!");
                }
                List <string> strList = new List <string>(pythonCodeContent);
                foreach (var item in sourceCodeContent)
                {
                    strList.Add("        " + item);
                }
                string codes = "";
                foreach (var s in strList)
                {
                    codes += s + Environment.NewLine;
                }
                ScriptEngine engine = Python.CreateEngine();
                ScriptSource source = engine.CreateScriptSourceFromString(codes);
                ScriptScope  scope  = engine.CreateScope();
                source.Execute(scope);

                dynamic performer = scope.GetVariable("performer");
                dynamic per       = performer("1005");
                per.run();
                var out_param = per.out_param;
                Console.WriteLine(per.out_param);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                Console.ReadKey();
            }
            finally
            {
                fileStream.Close();
                fileStream.Dispose();
            }
        }
        internal static void RunScript(string path)
        {
            if (Path.GetExtension(path) == ".fsx")
            {
                string fsi_path =
                    new[] {
                    ".",
                    Environment.GetEnvironmentVariable("ProgramFiles"),
                    Environment.GetEnvironmentVariable("ProgramFiles(x86)")
                }
                .Where(s => s != null)
                .SelectMany(s => new[] {
                    Path.Combine(s, "Microsoft SDKs", "F#"),
                    Path.Combine(s, "Microsoft Visual Studio")
                })
                .SelectMany(dir => Directory.Exists(dir)
                        ? Directory.GetFiles(dir, "fsi.exe", SearchOption.AllDirectories)
                        : new string[0])
                .FirstOrDefault(s => File.Exists(s));

                if (fsi_path == null)
                {
                    if (DialogResult.OK == MessageBox.Show("F# Interactive (fsi.exe) was not found. Would you like to install the Build Tools for Visual Studio?", "BrawlBox", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        Process.Start("https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017");
                    }
                }
                else
                {
                    string tempPath = Path.Combine(Path.GetTempPath(), $"BrawlBox-{Guid.NewGuid()}.fsx");
                    using (var srIn = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read)))
                        using (var swOut = new StreamWriter(new FileStream(tempPath, FileMode.Create, FileAccess.Write))) {
                            swOut.WriteLine($"#r \"{Assembly.GetAssembly(typeof(NodeFactory)).Location.Replace('\\', '/')}\"");
                            swOut.WriteLine($"#r \"{Assembly.GetAssembly(typeof(MainForm)).Location.Replace('\\', '/')}\"");
                            string line;
                            while ((line = srIn.ReadLine()) != null)
                            {
                                swOut.WriteLine(line);
                            }
                        }

                    var p = Process.Start(new ProcessStartInfo {
                        FileName              = fsi_path,
                        Arguments             = $"--noninteractive \"{tempPath}\"",
                        UseShellExecute       = false,
                        CreateNoWindow        = true,
                        RedirectStandardError = true
                    });
                    p.EnableRaisingEvents = true;
                    p.Exited += (o, e) =>
                    {
                        File.Delete(tempPath);
                        if (p.ExitCode != 0)
                        {
                            string err = p.StandardError.ReadToEnd().Trim();
                            if (!string.IsNullOrWhiteSpace(err))
                            {
                                MessageBox.Show(err);
                            }
                            else
                            {
                                MessageBox.Show($"fsi.exe quit with exit code {p.ExitCode}");
                            }
                        }
                    };
                }
            }
            else
            {
                try
                {
                    ScriptSource script = Engine.CreateScriptSourceFromFile(path);
                    CompiledCode code   = script.Compile();
                    ScriptScope  scope  = Engine.CreateScope();
                    script.Execute();
                }
                catch (SyntaxErrorException e)
                {
                    string msg = $"Syntax error in \"{Path.GetFileName(path)}\"\n{e.Message}";
                    ShowMessage(msg, Path.GetFileName(path));
                }
                catch (SystemExitException e)
                {
                    string msg = $"SystemExit in \"{Path.GetFileName(path)}\"\n{e.Message}";
                    ShowMessage(msg, Path.GetFileName(path));
                }

                catch (Exception e)
                {
                    string msg = $"Error running script \"{Path.GetFileName(path)}\"\n{e.Message}";
                    ShowMessage(msg, Path.GetFileName(path));
                }
            }
        }
Esempio n. 40
0
 /// <summary>
 /// Creates a new EvalMethodGenerator instance.
 /// </summary>
 /// <param name="engine"> The script engine. </param>
 /// <param name="parentScope"> The scope of the calling code. </param>
 /// <param name="source"> The script code to execute. </param>
 /// <param name="options"> Options that influence the compiler. </param>
 /// <param name="thisObject"> The value of the "this" keyword in the calling code. </param>
 public EvalMethodGenerator(ScriptEngine engine, Scope parentScope, ScriptSource source, CompilerOptions options, object thisObject)
     : base(engine, parentScope, source, options)
 {
     this.ThisObject = thisObject;
 }
Esempio n. 41
0
        protected override void SetupCommands()
        {
            _commands = new List <Command>();

            // Build the Rebuild Index command
            Command rebuild_index = new Command("Rebuild Index", "Rescan files in your computer");

            rebuild_index.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            rebuild_index.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(rebuild_index.Name);
            }));
            rebuild_index.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(rebuild_index.Description);
            }));
            rebuild_index.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(rebuild_index.Name);
            }));
            rebuild_index.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.rebuild.ToBitmap());
            }));
            rebuild_index.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(rebuild_index.Name, args, comp));
            }));
            rebuild_index.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                _parent.RebuildIndex();
            }));
            Commands.Add(rebuild_index);

            // Build the Rebuild Index command
            Command configure_blaze = new Command("Settings", "Open settings dialog");

            configure_blaze.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            configure_blaze.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(configure_blaze.Name);
            }));
            configure_blaze.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(configure_blaze.Description);
            }));
            configure_blaze.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(configure_blaze.Name);
            }));
            configure_blaze.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.preferences.ToBitmap());
            }));
            configure_blaze.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(configure_blaze.Name, args, comp));
            }));
            configure_blaze.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                _parent.OpenSettings();
            }));
            Commands.Add(configure_blaze);

            // Build the Clear Learned Commands command
            //Command clear_commands = new Command("Clear Learned Commands", new string[] { "clear", "reset", "learned", "commands", "blaze" }, "Resets all learned commands");
            Command clear_command = new Command("Clear Commands", "Reset all learned commands");

            clear_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            clear_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(clear_command.Name);
            }));
            clear_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(clear_command.Description);
            }));
            clear_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(clear_command.Name);
            }));
            clear_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.preferences.ToBitmap());
            }));
            clear_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(clear_command.Name, args, comp));
            }));
            clear_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                _parent.ClearLearnedCommands();
            }));
            Commands.Add(clear_command);

            // Build the Open scripts folder command
            Command scripts_folder_command = new Command("Scripts Folder", "Open Blaze scripts folder");

            scripts_folder_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            scripts_folder_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(scripts_folder_command.Name);
            }));
            scripts_folder_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(scripts_folder_command.Description);
            }));
            scripts_folder_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(scripts_folder_command.Name);
            }));
            scripts_folder_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.folder.ToBitmap());
            }));
            scripts_folder_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(scripts_folder_command.Name, args, comp));
            }));
            scripts_folder_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                if (!Directory.Exists(CommonInfo.ScriptsFolder))
                {
                    Directory.CreateDirectory(Path.GetFullPath(CommonInfo.ScriptsFolder));
                }
                System.Diagnostics.Process.Start(Path.GetFullPath(CommonInfo.ScriptsFolder));
            }));
            Commands.Add(scripts_folder_command);

            // Build the Record Macro command
            Command record_macro_command = new Command("Record Macro", "Records a macro");

            record_macro_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            record_macro_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(record_macro_command.Name);
            }));
            record_macro_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(record_macro_command.Description);
            }));
            record_macro_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(record_macro_command.Name);
            }));
            record_macro_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.record.ToBitmap());
            }));
            record_macro_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(record_macro_command.Name, args, comp));
            }));
            record_macro_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                UserContext.Instance.StartMacroRecording();
            }));
            Commands.Add(record_macro_command);

            // Build the Exit command
            Command exit_command = new Command("Exit", "Exit Blaze");

            exit_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            exit_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(exit_command.Name);
            }));
            exit_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(exit_command.Description);
            }));
            exit_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(exit_command.Name);
            }));
            exit_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.exit.ToBitmap());
            }));
            exit_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(exit_command.Name, args, comp));
            }));
            exit_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                _parent.Exit();
            }));
            Commands.Add(exit_command);

            // Build the Assistant command
            Command assistant_command = new Command("Show Assistant", "Show Blaze Assistant");

            assistant_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            assistant_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(assistant_command.Name);
            }));
            assistant_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(assistant_command.Description);
            }));
            assistant_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(assistant_command.Name);
            }));
            assistant_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.assistant.ToBitmap());
            }));
            assistant_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>();
                Dictionary <string, bool> comp = new Dictionary <string, bool>();

                return(new CommandUsage(assistant_command.Name, args, comp));
            }));
            assistant_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                _parent.ShowAssistantWindow();
            }));
            Commands.Add(assistant_command);

            // Build the Redo command
            Command redo_command = new Command("redo", "Repeat last suggestion");

            redo_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                int iterations;
                return(Int32.TryParse(parameters, out iterations) && iterations > 0 && iterations < 1001);
            }));
            redo_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(redo_command.Name);
            }));
            redo_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                int iterations;
                if (Int32.TryParse(parameters, out iterations) && iterations > 0 && iterations < 1001)
                {
                    return("Repeat last suggestion for " + iterations.ToString() + (iterations > 1 ? " iterations" : " iteration"));
                }
                return(redo_command.Description);
            }));
            redo_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                int iterations;
                if (Int32.TryParse(parameters, out iterations) && iterations > 0 && iterations < 1001)
                {
                    return(redo_command.Name + " " + iterations.ToString());
                }
                else
                {
                    return(redo_command.Name);
                }
            }));
            redo_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.redo.ToBitmap());
            }));
            redo_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>(new string[] { "number of iterations [0, 1000]" });
                Dictionary <string, bool> comp = new Dictionary <string, bool>();
                foreach (string arg in args)
                {
                    comp.Add(arg, false);
                }

                int iterations;
                if (Int32.TryParse(parameters, out iterations) && iterations > 0)
                {
                    comp["number of iterations [0, 1000]"] = true;
                }

                return(new CommandUsage(redo_command.Name, args, comp));
            }));
            redo_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                if (_parent.LastAcceptedSuggestion != null)
                {
                    int iterations;
                    _parent.LastAcceptedSuggestion.Validate(true);
                    if (Int32.TryParse(parameters, out iterations))
                    {
                        if (iterations > 0)
                        {
                            _parent.LastAcceptedSuggestion.Update(iterations, true);
                        }
                    }
                    else
                    {
                        _parent.LastAcceptedSuggestion.Update(true);
                    }
                    Thread sug = new Thread(new ThreadStart(delegate()
                    {
                        _parent.LastAcceptedSuggestion.Execute();
                    }));
                    sug.Start();
                    _thread_pool.Add(sug);
                }
            }));
            Commands.Add(redo_command);

            // Build the Continue command
            Command continue_command = new Command("continue", "Continue last suggestion");

            continue_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                int iterations;
                return(Int32.TryParse(parameters, out iterations) && iterations > 0 && iterations < 1001);
            }));
            continue_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(continue_command.Name);
            }));
            continue_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                int iterations;
                if (Int32.TryParse(parameters, out iterations) && iterations > 0 && iterations < 1001)
                {
                    return("Continue last suggestion for " + iterations.ToString() + (iterations > 1 ? " iterations" : " iteration"));
                }
                return(continue_command.Description);
            }));
            continue_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                int iterations;
                if (Int32.TryParse(parameters, out iterations) && iterations > 0 && iterations < 1001)
                {
                    return(continue_command.Name + " " + iterations.ToString());
                }
                else
                {
                    return(continue_command.Name);
                }
            }));
            continue_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.cont.ToBitmap());
            }));
            continue_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>(new string[] { "number of iterations [1, 1000]" });
                Dictionary <string, bool> comp = new Dictionary <string, bool>();
                foreach (string arg in args)
                {
                    comp.Add(arg, false);
                }

                int iterations;
                if (Int32.TryParse(parameters, out iterations) && iterations > 0)
                {
                    comp["number of iterations [1, 1000]"] = true;
                }

                return(new CommandUsage(continue_command.Name, args, comp));
            }));
            continue_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                if (_parent.LastAcceptedSuggestion != null)
                {
                    int iterations;
                    _parent.LastAcceptedSuggestion.Validate(false);
                    if (Int32.TryParse(parameters, out iterations))
                    {
                        if (iterations > 0)
                        {
                            _parent.LastAcceptedSuggestion.Update(iterations, false);
                        }
                    }
                    else
                    {
                        _parent.LastAcceptedSuggestion.Update(false);
                    }
                    Thread sug = new Thread(new ThreadStart(delegate()
                    {
                        _parent.LastAcceptedSuggestion.Execute();
                    }));
                    sug.Start();
                    _thread_pool.Add(sug);
                }
            }));
            Commands.Add(continue_command);

            // Build script commands
            string[] files = SettingsManager.Instance.GetScripts();
            foreach (string file in files)
            {
                string  ifile          = file;
                Command script_command = new Command(file, "Run " + file + ".py" + " script");
                script_command.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
                {
                    return(true);
                }));
                script_command.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
                {
                    return(script_command.Name);
                }));
                script_command.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
                {
                    return(script_command.Description);
                }));
                script_command.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
                {
                    return(script_command.Name);
                }));
                script_command.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
                {
                    return(Properties.Resources.script.ToBitmap());
                }));
                script_command.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
                {
                    List <string> args             = new List <string>(new string[] { "arguments" });
                    Dictionary <string, bool> comp = new Dictionary <string, bool>();
                    foreach (string arg in args)
                    {
                        comp.Add(arg, false);
                    }

                    if (parameters != string.Empty)
                    {
                        comp["arguments"] = true;
                    }

                    return(new CommandUsage(script_command.Name, args, comp));
                }));
                script_command.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
                {
                    string[] tokens = parameters.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    List args       = new List();
                    foreach (string token in tokens)
                    {
                        args.Add(token);
                    }
                    ScriptSource source = _script_engine.CreateScriptSourceFromFile(CommonInfo.ScriptsFolder + script_command.Name + ".py");
                    ScriptScope scope   = _script_engine.CreateScope();
                    scope.SetVariable("_user_context", UserContext.Instance);
                    _script_engine.GetSysModule().SetVariable("argv", args);
                    Thread python = new Thread(new ThreadStart(delegate()
                    {
                        try
                        {
                            source.Execute(scope);
                        }
                        catch (ThreadAbortException)
                        {
                            MessageBox.Show(script_command.Name + " execution was aborted by the user.", "Script execution aborted", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        catch (Exception e2)
                        {
                            MessageBox.Show(script_command.Name + " encountered an error while executing: " + Environment.NewLine + Environment.NewLine
                                            + e2.ToString() + Environment.NewLine + Environment.NewLine + "Script execution aborted.", "Script execution error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        }
                    }));
                    python.Start();
                    _thread_pool.Add(python);
                }));
                Commands.Add(script_command);
            }
        }
Esempio n. 42
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     OnError.Invoke(source, message, span, errorCode, severity);
 }
 /// <summary>
 /// Creates a new GlobalMethodGenerator instance.
 /// </summary>
 /// <param name="engine"> The script engine. </param>
 /// <param name="source"> The source of javascript code. </param>
 /// <param name="options"> Options that influence the compiler. </param>
 public GlobalMethodGenerator(ScriptEngine engine, ScriptSource source, CompilerOptions options)
     : base(engine, engine.CreateGlobalScope(), source, options)
 {
 }
Esempio n. 44
0
        /// <summary>
        ///  コマンド受信スレッド
        /// </summary>
        unsafe private void CommandThread(Object argObj)
        {
            //引数の展開
            object[] argsTmp = (object[])argObj;

            byte[] buffer = new byte[1024];

            //ソケットの生成
            _sock = new SockCtrl();
            _sock.Init(_serverIP, (int)argsTmp[0]);

            while (_sock.listener == null)
            {
                Thread.Sleep(10);
            }
            try {
                _sock.listener.Pending();
            }
            catch (Exception err) {
                _sock.listener.Start();
            }

            while (true)
            {
                if (_sock.listener.Pending() == true)
                {
                    _sock.Accept();

                    ConnectionMsg = "接続中";
                    Trace.TraceFormat("Socket Connected");

                    int           len    = 0;
                    NetworkStream stream = _sock.stream;
                    MemoryStream  ms     = new MemoryStream();

                    int  cmdMode = 0;
                    bool loop    = true;
                    while (loop)
                    {
                        //コマンド文字列受信
                        do
                        {
                            try {
                                len = stream.Read(buffer, 0, 1);

                                if (len == 0)
                                {
                                    //クライアント側から切断された
                                    loop        = false;
                                    ms.Position = 0;
                                    ms.Dispose();
                                    break;
                                }
                                ms.Write(buffer, 0, len);
                            }
                            catch (Exception err) {
                                //Read中に切断された
                                //MessageBox.Show("CMD::" + err.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                                WriteConsole(err.Message);
                                loop = false;
                                ms.Flush();
                                ms.Position = 0;
                                ms.Dispose();
                                break;
                            }
                            //コマンドの最終文字は';' または'@'とする
                            if (buffer[0] == ';')
                            {
                                cmdMode = 1;
                                break;
                            }
                            if (buffer[0] == '@')
                            {
                                cmdMode = 2;
                                break;
                            }
                            if (buffer[0] == '?')
                            {
                                cmdMode = 3;
                                break;
                            }
                        }while (stream.DataAvailable);

                        //コマンドを受信した
                        if (loop == true && (int)ms.Position != 0)
                        {
                            Encoding enc = Encoding.UTF8;

                            string cmd = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length - 1);

                            ms.Flush();
                            ms.Position = 0;
                            ms.Dispose();

                            //コマンドスクリプトを実行する
                            if (cmdMode == 1)
                            {
                                MessageData msg;
                                try {
                                    ScriptSource src = _pythonConsole.Pad.Console.ScriptScope.Engine.CreateScriptSourceFromString(cmd);
                                    Object       obj = src.Execute(_pythonConsole.Pad.Console.ScriptScope);

                                    msg = CreateMsg(MessageCode.SYS_CMD_RETOK, obj);
                                }
                                catch (Exception err) {
                                    //スクリプトの実行で例外発生
                                    string errMsg = _pythonConsole.Pad.Console.ScriptScope.Engine.GetService <ExceptionOperations>().FormatException(err);
                                    Trace.TraceFormat("[ERR]Script:{0}", errMsg);

                                    //MessageBox.Show(errMsg, "err", MessageBoxButton.OK, MessageBoxImage.Error);
                                    _pythonConsole.Pad.Console.WriteLine(errMsg, Microsoft.Scripting.Hosting.Shell.Style.Out);

                                    msg = CreateMsg(MessageCode.SYS_CMD_RETNG, (int)ErrCode.ERR_EXEC);
                                }
                                try {
                                    //結果を送信する
                                    stream.Write(msg.Binary(), 0, Marshal.SizeOf(msg));
                                }
                                catch (Exception err) {
                                    //MessageBox.Show("CMD_Write::" + err.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                                    WriteConsole(err.Message);
                                    loop = false;
                                }
                            }
                            else if (cmdMode == 3)
                            {
                                //スクリプトファイルで実行
                                MessageData msg;
                                try {
                                    ScriptSource src = _pythonConsole.Pad.Console.ScriptScope.Engine.CreateScriptSourceFromFile(cmd);
                                    Object       obj = src.Execute(_pythonConsole.Pad.Console.ScriptScope);

                                    msg = CreateMsg(MessageCode.SYS_CMD_RETOK, obj);
                                }
                                catch (Exception err) {
                                    //スクリプトの実行で例外発生
                                    string errMsg = _pythonConsole.Pad.Console.ScriptScope.Engine.GetService <ExceptionOperations>().FormatException(err);
                                    Trace.TraceFormat("[ERR]Script:{0}", errMsg);

//									MessageBox.Show(errMsg, "err", MessageBoxButton.OK, MessageBoxImage.Error);

                                    msg = CreateMsg(MessageCode.SYS_CMD_RETNG, (int)ErrCode.ERR_EXEC);
                                }
                                try {
                                    //結果を送信する
                                    stream.Write(msg.Binary(), 0, Marshal.SizeOf(msg));
                                }
                                catch (Exception err) {
                                    Trace.TraceFormat("[ERR]Socket Write:{0}", err.Message);
                                    //MessageBox.Show("CMD_Write::" + err.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                                    WriteConsole(err.Message);
                                    loop = false;
                                }
                                _ExecuteScript(this, new ScriptEventArgs("\n"));
                            }
                            else
                            {
                                // 別スレッドでのコマンド実行
                                bool threadRun = true;
                                if (_scriptThread != null)
                                {
                                    if (_scriptThread.ThreadState != ThreadState.Stopped)
                                    {
                                        //前回のスクリプトスレッドが動作中
                                        Trace.TraceFormat("Script already Run");
                                        MessageData msg = CreateMsg(MessageCode.SYS_CMD_RETNG, (int)ErrCode.ERR_EXEC);
                                        try {
                                            //結果を送信する
                                            stream.Write(msg.Binary(), 0, Marshal.SizeOf(msg));
                                        }
                                        catch (Exception err) {
                                            Trace.TraceFormat("[ERR]Socket Write:{0}", err.Message);
                                            //MessageBox.Show("CMD_Write::" + err.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                                            WriteConsole(err.Message);
                                            loop      = false;
                                            threadRun = false;
                                        }
                                        threadRun = false;
                                    }
                                }
                                if (threadRun == true)
                                {
                                    //スクリプト実行のイベント
                                    PEventManager.PEvent evObj = GetEvent();

                                    ThreadArgs args = new ThreadArgs();
                                    args.vm     = this;
                                    args.cmd    = cmd;
                                    args._event = evObj;

                                    _scriptThread = new Thread(new ParameterizedThreadStart(ScriptThread));
                                    _scriptThread.Start(args);

                                    Trace.TraceFormat("Script thread started");

                                    //execute_program() のリターン用データ
                                    MessageData msg = CreateMsg(MessageCode.SYS_CMD_RETOK, evObj._number);
                                    try {
                                        stream.Write(msg.Binary(), 0, Marshal.SizeOf(msg));
                                    }
                                    catch (Exception err) {
                                        Trace.TraceFormat("[ERR]Socket:{0}", err.Message);
                                        //MessageBox.Show("SCR_Write::" + err.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                                        WriteConsole(err.Message);
                                        loop = false;
                                    }
                                }
                            }
                            ms = new MemoryStream();
                        }
                    }
                    _sock.Close();
                    ConnectionMsg  = "未接続";
                    _threadRestart = 1;
                    Trace.TraceFormat("Socket DisConnected");
                }
                else
                {
                    Thread.Sleep(500);
                    if (_threadStop != 0)
                    {
                        break;
                    }
                }
            }
            _sock.Close();
            ConnectionMsg  = "未接続";
            _threadRestart = 1;
            Trace.TraceFormat("Socket DisConnected");
        }
Esempio n. 45
0
 /// <summary>
 /// Creates a new EvalMethodGenerator instance.
 /// </summary>
 /// <param name="engine"> The script engine. </param>
 /// <param name="parentScope"> The scope of the calling code. </param>
 /// <param name="source"> The script code to execute. </param>
 /// <param name="options"> Options that influence the compiler. </param>
 /// <param name="thisObject"> The value of the "this" keyword in the calling code. </param>
 public EvalMethodGenerator(ScriptEngine engine, Scope parentScope, ScriptSource source, CompilerOptions options, object thisObject)
     : base(engine, parentScope, source, options)
 {
     this.ThisObject = thisObject;
 }
Esempio n. 46
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     Program.Error(message);
 }
Esempio n. 47
0
        void _file_watcher_Created(object sender, FileSystemEventArgs e)
        {
            string  file       = Path.GetFileNameWithoutExtension(e.FullPath);
            Command new_script = new Command(file, "Run " + file + ".py" + " script");

            new_script.SetIsOwnerDelegate(new Command.OwnershipDelegate(delegate(string parameters)
            {
                return(false);
            }));
            new_script.SetNameDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(new_script.Name);
            }));
            new_script.SetDescriptionDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(new_script.Description);
            }));
            new_script.SetAutoCompleteDelegate(new Command.EvaluationDelegate(delegate(string parameters)
            {
                return(new_script.Name);
            }));
            new_script.SetIconDelegate(new Command.IconDelegate(delegate(string parameters)
            {
                return(Properties.Resources.script.ToBitmap());
            }));
            new_script.SetUsageDelegate(new Command.UsageDelegate(delegate(string parameters)
            {
                List <string> args             = new List <string>(new string[] { "arguments" });
                Dictionary <string, bool> comp = new Dictionary <string, bool>();
                foreach (string arg in args)
                {
                    comp.Add(arg, false);
                }

                if (parameters != string.Empty)
                {
                    comp["arguments"] = true;
                }

                return(new CommandUsage(new_script.Name, args, comp));
            }));
            new_script.SetExecuteDelegate(new Command.ExecutionDelegate(delegate(string parameters, Keys modifiers)
            {
                string[] tokens = parameters.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                List args       = new List();
                foreach (string token in tokens)
                {
                    args.Add(token);
                }
                ScriptSource source = _script_engine.CreateScriptSourceFromFile(CommonInfo.ScriptsFolder + new_script.Name + ".py");
                ScriptScope scope   = _script_engine.CreateScope();
                scope.SetVariable("_user_context", UserContext.Instance);
                _script_engine.GetSysModule().SetVariable("argv", args);
                Thread python = new Thread(new ThreadStart(delegate()
                {
                    try
                    {
                        source.Execute(scope);
                    }
                    catch (ThreadAbortException)
                    {
                        MessageBox.Show(new_script.Name + " execution was aborted by the user.", "Script execution aborted", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    catch (Exception e2)
                    {
                        MessageBox.Show(new_script.Name + " encountered an error while executing: " + Environment.NewLine + Environment.NewLine
                                        + e2.ToString() + Environment.NewLine + Environment.NewLine + "Script execution aborted.", "Script execution error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }));
                python.Start();
                _thread_pool.Add(python);
            }));
            Commands.Add(new_script);
        }
Esempio n. 48
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     throw new SyntaxErrorException(message, HostingHelpers.GetSourceUnit(source), span, errorCode, severity);
 }
Esempio n. 49
0
 public void ProcessCode(string code)
 {
     _source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
 }
Esempio n. 50
0
        private void StartExecution(ScriptSource src, ScriptScope scope, Action <ExecutionResult> continuation)
        {
            var job = new ScriptJob(src, scope, continuation);

            StartExecution(job);
        }
Esempio n. 51
0
 protected object ExecuteCommand(ScriptSource source) {
     ErrorListener errorListener = new ErrorSinkProxyListener(ErrorSink);
     CompiledCode compiledCode = source.Compile(_engine.GetCompilerOptions(_scope), errorListener);
     return _commandDispatcher.Execute(compiledCode, _scope);
 }
Esempio n. 52
0
 public static SourceUnit GetSourceUnit(ScriptSource scriptSource)
 {
     ContractUtils.RequiresNotNull(scriptSource, "scriptSource");
     return(scriptSource.SourceUnit);
 }
Esempio n. 53
0
        public dynamic CreateScriptFromString(string expr)
        {
            ScriptSource source = m_Engine.CreateScriptSourceFromString(expr);

            return(source.Execute(m_Scope));
        }
Esempio n. 54
0
        /// <summary>
        ///     Executes a Python script with custom variable names. Script may be a string
        ///     read from a file, for example. Pass a list of names (matching the variable
        ///     names in the script) to bindingNames and pass a corresponding list of values
        ///     to bindingValues.
        /// </summary>
        /// <param name="code">Python script as a string.</param>
        /// <param name="bindingNames">Names of values referenced in Python script.</param>
        /// <param name="bindingValues">Values referenced in Python script.</param>
        public static object EvaluateIronPythonScript(
            string code,
            IList bindingNames,
            [ArbitraryDimensionArrayImport] IList bindingValues)
        {
            // TODO - it would be nice if users could modify a preference
            // setting enabling the ability to load additional paths

            // Container for paths that will be imported in the PythonEngine
            List <string> paths = new List <string>();

            // Attempt to get the Standard Python Library
            string stdLib = PythonStandardLibPath();

            if (code != prev_code)
            {
                ScriptEngine PythonEngine = Python.CreateEngine();
                if (!string.IsNullOrEmpty(stdLib))
                {
                    paths = PythonEngine.GetSearchPaths().ToList();
                    paths.Add(stdLib);
                }

                // If any paths were successfully retrieved, append them
                if (paths.Count > 0)
                {
                    PythonEngine.SetSearchPaths(paths);
                }

                ScriptSource script = PythonEngine.CreateScriptSourceFromString(code);
                script.Compile();
                prev_script = script;
                prev_code   = code;
            }

            ScriptEngine engine = prev_script.Engine;
            ScriptScope  scope  = engine.CreateScope();

            // For backwards compatibility: "sys" was imported by default due to a bug so we keep it that way
            scope.ImportModule("sys");

            ProcessAdditionalBindings(scope, bindingNames, bindingValues, engine);

            int amt = Math.Min(bindingNames.Count, bindingValues.Count);

            for (int i = 0; i < amt; i++)
            {
                scope.SetVariable((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]));
            }

            try
            {
                OnEvaluationBegin(engine, scope, code, bindingValues);
                prev_script.Execute(scope);
            }
            catch (Exception e)
            {
                OnEvaluationEnd(false, engine, scope, code, bindingValues);
                var    eo    = engine.GetService <ExceptionOperations>();
                string error = eo.FormatException(e);
                throw new Exception(error);
            }

            OnEvaluationEnd(true, engine, scope, code, bindingValues);

            var result = scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null;

            return(OutputMarshaler.Marshal(result));
        }
Esempio n. 55
0
        // using python script in c#
        public dynamic CreateScriptFromFile(string path)
        {
            ScriptSource source = m_Engine.CreateScriptSourceFromFile(path);

            return(source.Execute(m_Scope));
        }
Esempio n. 56
0
        protected override int ResetLoop()
        {
            var scriptFile = File.ReadAllText(ScriptFileName);

            if (string.IsNullOrEmpty(scriptFile))
            {
                Log($"Load Script Error", LogLevel.Error);
                return(-1);
            }

            _scriptScope.SetVariable("state", RunningState.Resetting);
            foreach (var obj in Station.Machine.DiExs)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }
            foreach (var obj in Station.Machine.DoExs)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }
            foreach (var obj in Station.Machine.VioExs)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }
            foreach (var obj in Station.Machine.CylinderExs)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }
            foreach (var obj in Station.Machine.AxisExs)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }
            foreach (var obj in Station.Machine.Platforms)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }
            foreach (var obj in Station.Machine.Devices)
            {
                _scriptScope.SetVariable(obj.Value.Name, obj.Value);
            }

            if (_scriptSource == null)
            {
                _lastRunDateTime = DateTime.Now;

                _scriptSource = _scriptEngine.CreateScriptSourceFromString(scriptFile);
                _scriptSource.Execute(_scriptScope);
            }
            else
            {
                var fileInfo = new FileInfo($@".\Scripts\{Name}.py");
                if (fileInfo.LastWriteTime > _lastRunDateTime)
                {
                    _scriptSource = _scriptEngine.CreateScriptSourceFromString(scriptFile);
                    _scriptSource.Execute(_scriptScope);
                }
                else
                {
                    _scriptSource.Execute(_scriptScope);
                }
            }
            return(-1);
        }
Esempio n. 57
0
 public static void Shutdown()
 {
     if (watcher != null)
     {
         watcher = null;
         watcher.Changed -= watcher_Changed;
         watcher.EnableRaisingEvents = false;
     }
     source = null;
     compiledCode = null;
     rendererClass = null;
     rendererImpl = null;
     pyEngine = null;
     objOps = null;
 }
Esempio n. 58
0
 public PluginScript(string name, ScriptSource script, ScriptScope scope)
 {
     Name   = name;
     Script = script;
     Scope  = scope;
 }
Esempio n. 59
0
        public void Execute(MacroEntry macro)
        {
            _macro = macro;

            if (Thread != null && Thread.IsAlive)
            {
                Stop();
            }

            MainCommands.SetQuietMode(Options.CurrentOptions.DefaultMacroQuietMode);

            _cancellationToken = new CancellationTokenSource();

            if (_importCache == null)
            {
                _importCache = InitializeImports(_engine);
            }

            ScriptSource source = _engine.CreateScriptSourceFromString(_macro.Macro, SourceCodeKind.Statements);

            Dictionary <string, object> importCache = new Dictionary <string, object>(_importCache);

            IsFaulted = false;

            Thread = new Thread(() =>
            {
                Thread = Thread.CurrentThread;

                try
                {
                    StartedEvent?.Invoke();

                    AliasCommands.SetDefaultAliases();

                    ScriptScope macroScope = _engine.CreateScope(importCache);

                    _stopWatch.Reset();
                    _stopWatch.Start();

                    do
                    {
                        _cancellationToken.Token.ThrowIfCancellationRequested();

                        source.Execute(macroScope);

                        _stopWatch.Stop();

                        bool willLoop = _macro.Loop && !IsFaulted && !_cancellationToken.IsCancellationRequested;

                        if (!willLoop)
                        {
                            break;
                        }

                        if (Options.CurrentOptions.Debug)
                        {
                            UO.Commands.SystemMessage(string.Format(Strings.Loop_time___0_, _stopWatch.Elapsed));
                        }

                        int diff = 50 - (int)_stopWatch.ElapsedMilliseconds;

                        if (diff > 0)
                        {
                            Thread.Sleep(diff);
                        }
                    }while (_macro.Loop && !IsFaulted);
                }
                catch (TaskCanceledException)
                {
                    IsFaulted = true;
                }
                catch (ThreadInterruptedException)
                {
                    IsFaulted = true;
                }
                catch (ThreadAbortException)
                {
                    IsFaulted = true;
                }
                catch (Exception e)
                {
                    IsFaulted = true;
                    Exception = e;

                    ExceptionEvent?.Invoke(e);
                }
                finally
                {
                    StoppedEvent?.Invoke();
                }
            })
            {
                IsBackground = true
            };

            try
            {
                Thread.Start();
            }
            catch (ThreadStateException)
            {
                // TODO
            }
            catch (ThreadStartException)
            {
                // TODO
            }
        }
Esempio n. 60
0
        public static void try5(string[] args)
        {
            ScriptEngine pyEngine = Python.CreateEngine();
            dynamic      pyScope  = pyEngine.CreateScope();

            ScriptSource source = pyEngine.CreateScriptSourceFromFile("CdiClient.py");

            source.Compile().Execute(pyScope);
            ObjectOperations ops = pyEngine.CreateOperations(pyScope);

            // create member objects for worker object:  watermark provider, tracer, logger
            WatermarkProvider watermarkProvider = new WatermarkProvider();

            pyScope.SetVariable("watermarkProvider", watermarkProvider);

            dynamic cdiWorker = pyEngine.Execute("CdiClient()", pyScope);   // create an instance of the worker obj

            // TODO -- check that all of the right entrypoints are available.

            Console.WriteLine("static function doc: {0}", pyScope.SampleStaticFunction.__doc__);
            Console.WriteLine("indirect class doc: {0}", pyScope.CdiClient.__doc__);
            Console.WriteLine("direct class doc: {0}", cdiWorker.__doc__);
            Console.WriteLine("class function doc: {0}", cdiWorker.ProcessOneEvent.__doc__);

            //CheckForEntryPoint();
            Console.WriteLine("NoOp:  {0}", ops.ContainsMember(cdiWorker, "NoOp"));
            Console.WriteLine("FooBar:  {0}", ops.ContainsMember(cdiWorker, "FooBar"));

            IList <string> memberNames = ops.GetMemberNames(cdiWorker);

            foreach (string s in memberNames)
            {
                Console.WriteLine("    names:  {0}", s);
            }

            IList <string> signatures = ops.GetCallSignatures(cdiWorker);

            foreach (string s in signatures)
            {
                Console.WriteLine("    sig:  {0}", s);
            }


            dynamic result;

            result = ops.InvokeMember(cdiWorker, "NoOp", new object[] { "hi mom" });
            result = ops.InvokeMember(cdiWorker, "NoOp", new object[] { "hi dad" });
            result = ops.InvokeMember(cdiWorker, "NoOp", new object[] { "watch this" });

            for (int i = 0; i < 10; i++)
            {
                MockEHEvent   ehEvent = new MockEHEvent();
                WatermarkData wmData  = new WatermarkData();
                System.Threading.Thread.Sleep(args.Length > 0 ? int.Parse(args[0]) : 100);
                result = ops.InvokeMember(cdiWorker, "ProcessOneEvent", new object[] { ehEvent, wmData });
            }

            WatermarkDelegate del = delegate() { Console.WriteLine("delegate"); };

            result = ops.InvokeMember(cdiWorker, "ProcessDelegate", new object[] { del });

            WatermarkDelegateWithVal delVal = delegate(string s) { Console.WriteLine("delegate {0}", s); };

            result = ops.InvokeMember(cdiWorker, "ProcessDelegateWithVal", new object[] { delVal });
        }