Exemplo n.º 1
0
        private void CompileAndExecute(string[] files, string[] args, IScriptManagerCallback callback, string[] filesToEmbed)
        {
            try
            {
                // Create an AppDomain to compile and execute the code
                // This enables us to cancel the execution if needed
                executionDomain = AppDomain.CreateDomain("ExecutionDomain");
                var manager = (IScriptManager)executionDomain.CreateInstanceFromAndUnwrap(typeof(BaseApp).Assembly.Location, typeof(ScriptManager).FullName);
                manager.CompileAndExecuteFile(files, args, this, filesToEmbed);
            }
            catch (UnsupportedLanguageExecption e)
            {
                ShowErrorMessageFromResource("UnsupportedLanguage", e.Extension);
            }
            catch (AppDomainUnloadedException e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                ShowErrorMessage(e.Message);
            }

            TerminateExecutionLoop();
        }
        public void CompileAndExecuteFile(string file, string[] args, IScriptManagerCallback callback)
        {
            var t = new Template();
            string extension = Path.GetExtension(file);

            if (extension == ".ccc")
            {
                if (Path.GetFileName(file).IndexOf(".debug.ccc") != -1)
                {
                    string filename = Path.GetFileName(file);
                    File.WriteAllText(filename + ".debug.cs", t.GenerateSourceFile(file));
                }

                string result = t.Compile(file);
                string postExecuteBlock = t.ExtractPostExecuteBlock(result);
                if (postExecuteBlock != string.Empty)
                {
                    result = t.RemovePostExecuteBlock(result);

                }
                var files = t.Split(result);

                foreach (var f in files)
                {
                    if (t.Values.ContainsKey("output" + f.FileId))
                    {
                        File.WriteAllText(t["output" + f.FileId], f.Content);
                    }
                }

                if (t.Values.ContainsKey("output"))
                {
                    if (t["output"] != string.Empty)
                    {
                        File.WriteAllText(t["output"], result);
                    }
                }
                else
                {
                    File.WriteAllText(Path.ChangeExtension(file, "ccc.txt"), result);
                }

                if (postExecuteBlock != string.Empty)
                {
                    if (Path.GetFileName(file).IndexOf(".debug.ccc") != -1)
                    {
                        string filename = Path.GetFileName(file);
                        File.WriteAllText(filename + ".debug.exe.cs", postExecuteBlock);
                    }

                    result = t.CompileCode(postExecuteBlock);
                    if (Path.GetFileName(file).IndexOf(".debug.ccc") != -1)
                    {
                        string filename = Path.GetFileName(file);
                        File.WriteAllText(filename + ".debug.exe.txt", result);
                    }
                }
            }else if (extension == ".ccs")
            {
                t.CompileCode(File.ReadAllText(file));
            }
        }
Exemplo n.º 3
0
        private void CompileAndExecute(string[] files, string[] args, IScriptManagerCallback callback, string[] filesToEmbed)
        {
            try
            {
                // Create an AppDomain to compile and execute the code
                // This enables us to cancel the execution if needed
                executionDomain = AppDomain.CreateDomain("ExecutionDomain");
                var manager = (IScriptManager)executionDomain.CreateInstanceFromAndUnwrap(typeof(BaseApp).Assembly.Location, typeof(ScriptManager).FullName);
                manager.CompileAndExecuteFile(files, args, this, filesToEmbed);
            }
            catch(UnsupportedLanguageExecption e)
            {
                ShowErrorMessageFromResource("UnsupportedLanguage", e.Extension);
            }
            catch(AppDomainUnloadedException e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message);
            }
            catch(Exception e)
            {
                ShowErrorMessage(e.Message);
            }

            TerminateExecutionLoop();
        }
Exemplo n.º 4
0
        public void CompileAndExecuteFile(string[] files, string[] args, IScriptManagerCallback callback, string[] filesToEmbed)
        {
            const int numITemplateFiles = 5;

            string[] extraFiles = new string[files.Length + numITemplateFiles];

            for (int i = 0; i < files.Length; i++)
            {
                extraFiles[i] = files[i];
            }
            StreamReader sr = null;
            StreamWriter sw = null;

            try
            {
                string tempFile = Path.Combine(Path.GetTempPath(), "Folder.cs");
                sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Folder.cs"));
                sw = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Option.cs");
                sr       = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Option.cs"));
                sw       = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 1] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Output.cs");
                sr       = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Output.cs"));
                sw       = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 2] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Project.cs");
                sr       = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Project.cs"));
                sw       = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 3] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Script.cs");
                sr       = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Script.cs"));
                sw       = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 4] = tempFile;
            }
            catch
            {
                if (sr != null)
                {
                    sr.Close();
                }
                if (sw != null)
                {
                    sw.Close();
                }
            }
            files = extraFiles;
            string outputFileName = "";
            string nrfFileName    = "";

            foreach (string arg in args)
            {
                if (arg.IndexOf("outputFileName=") >= 0)
                {
                    outputFileName = arg.Substring("outputFileName=".Length);
                }
                else if (arg.IndexOf("nrfFileName=") >= 0)
                {
                    nrfFileName = arg.Substring("nrfFileName=".Length);
                }
            }
            if (outputFileName.Length == 0)
            {
                throw new ApplicationException("Output file type is missing.");
            }
            bool isExe = (outputFileName.IndexOf(".exe") > 0);
            //Currently only csharp scripting is supported
            CodeDomProvider provider;

            string extension = Path.GetExtension(files[0]);

            switch (extension)
            {
            case ".cs":
            case ".ncs":
                provider = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            case ".vb":
            case ".nvb":
                provider = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            case ".njs":
            case ".js":
                provider = (CodeDomProvider)Activator.CreateInstance("Microsoft.JScript", "Microsoft.JScript.JScriptCodeProvider").Unwrap();
                break;

            default:
                throw new UnsupportedLanguageExecption(extension);
            }
            var compiler       = provider.CreateCompiler();
            var compilerparams = new CompilerParameters
            {
                GenerateInMemory   = false,
                GenerateExecutable = isExe,
                OutputAssembly     = outputFileName
            };
            // Embed resource file
            string optionPath         = Path.Combine(Path.GetTempPath(), "options.xml");
            string allCompilerOptions = @"/res:" + optionPath + ",";

            //compilerparams.CompilerOptions = @"/res:"+ optionPath;

            // Embed extra files, but not the first one which is the .cs file to compile, and
            // not the files which implement the ITemplate functions
            for (int i = 1; i < filesToEmbed.Length; i++)
            {
                string embeddedFilePath = Path.Combine(Controller.TempPath, filesToEmbed[i]);

                if (!File.Exists(embeddedFilePath) && embeddedFilePath.Length > 0)
                {
                    System.Windows.Forms.MessageBox.Show(Controller.Instance.MainForm, "File not found: " + embeddedFilePath + ". Compile aborted.", "Missing file", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
                string resFilePath     = Path.Combine(Path.GetDirectoryName(embeddedFilePath), Path.GetFileNameWithoutExtension(embeddedFilePath) + ".xml");
                string resFileNameOnly = Path.GetFileNameWithoutExtension(embeddedFilePath) + ".xml";
                CreateResourceFile(embeddedFilePath, resFilePath);
                File.Copy(resFilePath, resFileNameOnly, true);
                allCompilerOptions += resFilePath + ",";
                //allCompilerOptions += @"/res:"+ resFileNameOnly +",";
                //allCompilerOptions += @"/res:"+ optionPath +",";
            }
            // Remove the trailing comma
            compilerparams.CompilerOptions = allCompilerOptions.Substring(0, allCompilerOptions.Length - 1);

            //Add assembly references from nscript.nrf or <file>.nrf
            if (File.Exists(nrfFileName))
            {
                AddReferencesFromFile(compilerparams, nrfFileName);
            }
            else
            {
                //Use nscript.nrf
                string nrfFile = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "nscript.nrf");

                if (File.Exists(nrfFile))
                {
                    AddReferencesFromFile(compilerparams, nrfFile);
                }
            }
            CompilerResults results = compiler.CompileAssemblyFromFileBatch(compilerparams, files);

            if (results.Errors.HasErrors)
            {
                System.Collections.ArrayList templist = new System.Collections.ArrayList();

                foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                {
                    templist.Add(new CompilerError(error));
                }
                callback.OnCompilerError((CompilerError[])templist.ToArray(typeof(CompilerError)));
            }
        }
Exemplo n.º 5
0
 public System.CodeDom.Compiler.CompilerResults CompileFile(string file, string[] strReferenceAssembliesToAdd, IScriptManagerCallback callback)
 {
     System.CodeDom.Compiler.CompilerResults crResults = CompileSourceCode(file, strReferenceAssembliesToAdd);
     if (crResults.Errors.HasErrors)
     {
         System.Collections.ArrayList templist = new System.Collections.ArrayList();
         foreach (System.CodeDom.Compiler.CompilerError error in crResults.Errors)
         {
             templist.Add(new CompilerError(error));
         }
         callback.OnCompilerError((CompilerError[])templist.ToArray(typeof(CompilerError)));
         return null;
     }
     else
     {
         return crResults;
     }
 }
Exemplo n.º 6
0
 public void CompileAndExecuteFile(string file, string[] args, string[] strReferenceAssembliesToAdd, IScriptManagerCallback callback)
 {
     System.CodeDom.Compiler.CompilerResults crResults = CompileSourceCode(file,strReferenceAssembliesToAdd);
     if (crResults.Errors.HasErrors)
     {
         System.Collections.ArrayList templist = new System.Collections.ArrayList();
         foreach(System.CodeDom.Compiler.CompilerError error in crResults.Errors)
         {
             templist.Add(new CompilerError(error));
         }
         callback.OnCompilerError((CompilerError[])templist.ToArray(typeof(CompilerError)));
     }
     else
     {
         crResults.CompiledAssembly.EntryPoint.Invoke(null, BindingFlags.Static, null, new object[]{args}, null);
     }
 }
Exemplo n.º 7
0
 public System.CodeDom.Compiler.CompilerResults CompileFile(string file, string[] strReferenceAssembliesToAdd, IScriptManagerCallback callback)
 {
     System.CodeDom.Compiler.CompilerResults crResults = CompileSourceCode(file, strReferenceAssembliesToAdd);
     if (crResults.Errors.HasErrors)
     {
         System.Collections.ArrayList templist = new System.Collections.ArrayList();
         foreach (System.CodeDom.Compiler.CompilerError error in crResults.Errors)
         {
             templist.Add(new CompilerError(error));
         }
         callback.OnCompilerError((CompilerError[])templist.ToArray(typeof(CompilerError)));
         return(null);
     }
     else
     {
         return(crResults);
     }
 }
Exemplo n.º 8
0
 public void CompileAndExecuteFile(string file, string[] args, string[] strReferenceAssembliesToAdd, IScriptManagerCallback callback)
 {
     System.CodeDom.Compiler.CompilerResults crResults = CompileSourceCode(file, strReferenceAssembliesToAdd);
     if (crResults.Errors.HasErrors)
     {
         System.Collections.ArrayList templist = new System.Collections.ArrayList();
         foreach (System.CodeDom.Compiler.CompilerError error in crResults.Errors)
         {
             templist.Add(new CompilerError(error));
         }
         callback.OnCompilerError((CompilerError[])templist.ToArray(typeof(CompilerError)));
     }
     else
     {
         crResults.CompiledAssembly.EntryPoint.Invoke(null, BindingFlags.Static, null, new object[] { args }, null);
     }
 }
Exemplo n.º 9
0
        public void CompileAndExecuteFile(string[] files, string[] args, IScriptManagerCallback callback, string[] filesToEmbed)
        {
            const int numITemplateFiles = 5;
            string[] extraFiles = new string[files.Length + numITemplateFiles];

            for (int i = 0; i < files.Length; i++)
            {
                extraFiles[i] = files[i];
            }
            StreamReader sr = null;
            StreamWriter sw = null;

            try
            {
                string tempFile = Path.Combine(Path.GetTempPath(), "Folder.cs");
                sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Folder.cs"));
                sw = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Option.cs");
                sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Option.cs"));
                sw = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 1] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Output.cs");
                sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Output.cs"));
                sw = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 2] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Project.cs");
                sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Project.cs"));
                sw = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 3] = tempFile;

                tempFile = Path.Combine(Path.GetTempPath(), "Script.cs");
                sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"SlyceScripter.Config.Script.cs"));
                sw = File.CreateText(tempFile);
                sw.Write(sr.ReadToEnd());
                sr.Close();
                sw.Flush();
                sw.Close();
                extraFiles[files.Length + 4] = tempFile;
            }
            catch
            {
                if (sr != null) { sr.Close(); }
                if (sw != null) { sw.Close(); }
            }
            files = extraFiles;
            string outputFileName = "";
            string nrfFileName = "";

            foreach (string arg in args)
            {
                if (arg.IndexOf("outputFileName=") >= 0)
                {
                    outputFileName = arg.Substring("outputFileName=".Length);
                }
                else if (arg.IndexOf("nrfFileName=") >= 0)
                {
                    nrfFileName = arg.Substring("nrfFileName=".Length);
                }
            }
            if (outputFileName.Length == 0)
            {
                throw new ApplicationException("Output file type is missing.");
            }
            bool isExe = (outputFileName.IndexOf(".exe") > 0);
            //Currently only csharp scripting is supported
            CodeDomProvider provider;

            string extension = Path.GetExtension(files[0]);

            switch (extension)
            {
                case ".cs":
                case ".ncs":
                    provider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                case ".vb":
                case ".nvb":
                    provider = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case ".njs":
                case ".js":
                    provider = (CodeDomProvider)Activator.CreateInstance("Microsoft.JScript", "Microsoft.JScript.JScriptCodeProvider").Unwrap();
                    break;
                default:
                    throw new UnsupportedLanguageExecption(extension);
            }
            var compiler = provider.CreateCompiler();
            var compilerparams = new CompilerParameters
                                                                            {
                                                                                GenerateInMemory = false,
                                                                                GenerateExecutable = isExe,
                                                                                OutputAssembly = outputFileName
                                                                            };
            // Embed resource file
            string optionPath = Path.Combine(Path.GetTempPath(), "options.xml");
            string allCompilerOptions = @"/res:" + optionPath + ",";
            //compilerparams.CompilerOptions = @"/res:"+ optionPath;

            // Embed extra files, but not the first one which is the .cs file to compile, and
            // not the files which implement the ITemplate functions
            for (int i = 1; i < filesToEmbed.Length; i++)
            {
                string embeddedFilePath = Path.Combine(Controller.TempPath, filesToEmbed[i]);

                if (!File.Exists(embeddedFilePath) && embeddedFilePath.Length > 0)
                {
                    System.Windows.Forms.MessageBox.Show(Controller.Instance.MainForm, "File not found: " + embeddedFilePath + ". Compile aborted.", "Missing file", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
                string resFilePath = Path.Combine(Path.GetDirectoryName(embeddedFilePath), Path.GetFileNameWithoutExtension(embeddedFilePath) + ".xml");
                string resFileNameOnly = Path.GetFileNameWithoutExtension(embeddedFilePath) + ".xml";
                CreateResourceFile(embeddedFilePath, resFilePath);
                File.Copy(resFilePath, resFileNameOnly, true);
                allCompilerOptions += resFilePath + ",";
                //allCompilerOptions += @"/res:"+ resFileNameOnly +",";
                //allCompilerOptions += @"/res:"+ optionPath +",";
            }
            // Remove the trailing comma
            compilerparams.CompilerOptions = allCompilerOptions.Substring(0, allCompilerOptions.Length - 1);

            //Add assembly references from nscript.nrf or <file>.nrf
            if (File.Exists(nrfFileName))
            {
                AddReferencesFromFile(compilerparams, nrfFileName);
            }
            else
            {
                //Use nscript.nrf
                string nrfFile = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "nscript.nrf");

                if (File.Exists(nrfFile))
                {
                    AddReferencesFromFile(compilerparams, nrfFile);
                }
            }
            CompilerResults results = compiler.CompileAssemblyFromFileBatch(compilerparams, files);

            if (results.Errors.HasErrors)
            {
                System.Collections.ArrayList templist = new System.Collections.ArrayList();

                foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                {
                    templist.Add(new CompilerError(error));
                }
                callback.OnCompilerError((CompilerError[])templist.ToArray(typeof(CompilerError)));
            }
        }