Exemple #1
0
        public bool InitScript()
        {
            Cursor.Current = Cursors.WaitCursor;

            if (pnd.pyCode.Length > 0)
            {
                try
                {
                    string             code     = TemplateCode.Replace("/*CODE*/", pnd.pyCode);
                    CSharpCodeProvider provider = new CSharpCodeProvider();
                    ICodeCompiler      compiler = provider.CreateCompiler();

                    CompilerParameters compilerparams = new CompilerParameters();
                    compilerparams.GenerateExecutable = false;
                    compilerparams.GenerateInMemory   = true;
                    compilerparams.ReferencedAssemblies.Add("System.dll");
                    compilerparams.ReferencedAssemblies.Add("System.Windows.Forms.dll");

                    string thisAss = Assembly.ReflectionOnlyLoad(Assembly.GetExecutingAssembly().FullName).Location;
                    compilerparams.ReferencedAssemblies.Add(thisAss);

                    CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code);
                    _compiledAssembly = !results.Errors.HasErrors ? results.CompiledAssembly : null;
                    if (_compiledAssembly != null)
                    {
                        _type     = _compiledAssembly.GetType("PetriNetSimulator2.ClassWithScriptCode");
                        _instance = Activator.CreateInstance(_type, this);
                        return(true);
                    }
                    else
                    {
                        _expressionError = "";
                        foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                        {
                            _expressionError += String.Format("Line {0}\t: {1}\n",
                                                              error.Line - 5,
                                                              error.ErrorText);
                        }

                        this.Script_OnWriteWithColor(_expressionError + "\n", System.Drawing.Color.Red);
                        return(false);
                    }


                    Cursor.Current = Cursors.Default;
                    return(true);
                }
                catch (Exception e)
                {
                    this.Script_OnWriteWithColor("Error starting C# module\n", System.Drawing.Color.Red);
                    this.Script_OnWriteWithColor(e.Message + "\n", System.Drawing.Color.Red);
                    _compiledAssembly = null;
                    _instance         = null;
                    _type             = null;
                }
            }
            Cursor.Current = Cursors.Default;
            return(false);
        }