static void Main(string[] args) { string script = @"package blahPackage { class blahClass { function add(a, b) { return a + b; } } }"; using (var provider = new JScriptCodeProvider()) { var results = provider.CompileAssemblyFromSource(new CompilerParameters(), script); var assembly = results.CompiledAssembly; var myblahtype = assembly.GetType("blahPackage.blahClass"); var myblah = Activator.CreateInstance(myblahtype); var result = myblahtype.InvokeMember("add", System.Reflection.BindingFlags.InvokeMethod, null, myblah, new object[] { 2, 3 }); Console.WriteLine("Output : " + result.ToString()); Console.ReadLine(); } }
public void CompileAndExecuteFile(string[] file, string[] args) { CodeDomProvider provider = new JScriptCodeProvider(); var compilerparams =new CompilerParameters {GenerateInMemory = true, GenerateExecutable = true}; //add to the list of assemblies referenced by the compiled script //see MockUp.cs var assembly_ref = Path.GetFullPath("Onyx.JS.api.dll"); compilerparams.ReferencedAssemblies.Add(assembly_ref); CompilerResults results = provider.CompileAssemblyFromFile(compilerparams, file); if (results.Errors.HasErrors) { //ArrayList templist = new ArrayList(); foreach (CompilerError error in results.Errors) { Console.WriteLine(error.ErrorText + "\nin file:" + error.FileName + "(" + error.Line + "," + error.Column + ")"); } } else { try { results.CompiledAssembly.EntryPoint.Invoke(null, BindingFlags.Static, null, new object[] {args}, null); } catch (Exception x) { Console.WriteLine(x.Message); Console.WriteLine(x.StackTrace); } } }
public static CompilerResults CompileFromJScriptSourceFile(String sourceFile, CompilerParameters cParams) { using (CodeDomProvider provider = new JScriptCodeProvider()) { CompilerResults res = provider.CompileAssemblyFromFile(cParams, sourceFile); return res; } }
public CaptchaEvaluator() { ICodeCompiler compiler = new JScriptCodeProvider().CreateCompiler(); CompilerParameters parameters = new CompilerParameters {GenerateInMemory = true}; CompilerResults results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("CaptchaEvaluator.CaptchaEvaluator"); }
/// <summary> /// 初始化脚本引擎 /// </summary> private void InitJscriptEngine() { JScriptCodeProvider compiler = new JScriptCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results; results = compiler.CompileAssemblyFromSource(parameters, _JscriptCode); Assembly assembly = results.CompiledAssembly; _EvaluatorType = assembly.GetType("JsEvalClass.JsEvalClass"); _Evaluator = Activator.CreateInstance(_EvaluatorType); }
static Evaluator() { var compiler = new JScriptCodeProvider().CreateCompiler(); var parameters = new CompilerParameters { GenerateInMemory = true }; var results = compiler.CompileAssemblyFromSource(parameters, JscriptSource); var assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); }
public static void Initialize() { CodeDomProvider compiler = new JScriptCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.ReferencedAssemblies.Add("system.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(parameters, _jscriptEvalClass); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("JScriptEvaluator"); _evaluatorInstance = Activator.CreateInstance(_evaluatorType); }
public JScriptEvaluator() { CodeDomProvider provider = new Microsoft.JScript.JScriptCodeProvider(); CompilerParameters parameters; parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results; results = provider.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); }
static Evaluator() { JScriptCodeProvider compiler = new JScriptCodeProvider(); CompilerParameters parameters; parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results; results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); }
static Evaluator() { CompilerParameters compilerParams = new CompilerParameters(); compilerParams.TreatWarningsAsErrors = false; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; JScriptCodeProvider provider = new JScriptCodeProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(compilerParams, _jscriptSource); foreach (Module module in compile.CompiledAssembly.GetModules()) { foreach (Type type in module.GetTypes()) { foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { if (methodInfo.Name == "Eval") { _evaluator = methodInfo; return; } } } } }
public Evaluator(Evaluator theEvaluator) { ICodeCompiler compiler; compiler = new JScriptCodeProvider().CreateCompiler(); CompilerParameters parameters; parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results; results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("EvaluatorNS.Evaluator"); //_evaluatorCtxType = assembly.GetType("Evaluator.Context"); _evaluator = Activator.CreateInstance(_evaluatorType); // create a new form instance // _scriptableForm = new ScriptableForm(); // create a new set of hosts lock (hosts) { string rootMoniker = string.Format("{0}://{1}", rootHostName, Guid.NewGuid().ToString()); _host = new VsaScriptingHost(VsaScriptingLanguages.JScript, "Evaluator", rootMoniker, _evaluatorType.Namespace, true); Engine = (VsaEngine)(object)_host.Engine; globalScope = Engine.GetGlobalScope(); thisGlobalObj = Microsoft.JScript.Eval.JScriptEvaluate("this;", Engine) as GlobalScope; hosts.Add(_host); _host.AddType(typeof(System.Object)); _host.AddType(typeof(System.String)); AddGlobalItem("$engine", Engine); AddGlobalItem("$superE", theEvaluator); // hosts.AddRange(HostFactory.Create(@"MyScriptingHost", @"Scripting", true, Environment.CurrentDirectory)); } // wire up to the events of each host foreach (VsaScriptingHost host in hosts) { host.AssemblyReferencesNeeded += new ScriptingHostEventHandler(OnAssemblyReferencesNeeded); host.CompilerException += new ScriptingHostCompilerExceptionEventHandler(OnCompilerException); host.GlobalItemsNeeded += new ScriptingHostEventHandler(OnGlobalItemsNeeded); } // execute the hosts foreach (VsaScriptingHost host in hosts) host.Execute(); // show the form //_scriptableForm.ShowDialog(); }
public static CompilerException Compile(string modDirectory, string outputDirectory) { CommonToolUtilities.RefreshHashes(); string modName = Path.GetDirectoryName(modDirectory); string jsonFile, modInfo; CodeDomProvider cdcp = new CSharpCodeProvider(); string ext = "*.cs"; #region validating ModInfo.json jsonFile = modDirectory + "\\ModInfo.json"; if (!File.Exists(jsonFile)) { File.WriteAllText(jsonFile, "{\"name\":\"" + modName + "\",\"author\":\"<unknown>\"}"); Console.WriteLine("Warning: You do not have a ModInfo.json file.\n\tUsing the default ModInfo..."); } try { JsonData json = JsonMapper.ToObject(File.ReadAllText(jsonFile)); if (!json.Has("name")) throw new CompilerException("Missing ModInfo filed 'name'"); else modName = (string)json["name"]; if (!json.Has("author")) throw new CompilerException("Missing ModInfo filed 'author'"); if (json.Has("code")) { JsonData jCode = json["code"]; if (jCode.Has("codeType")) switch (jCode["codeType"].ToString().ToLower().Trim()) { case "vb": case "vb.net": case "basic": case "basic.net": case "vbasic": case "vbasic.net": case "visualbasic": case "visualbasic.net": case "visual basic": case "visual basic.net": cdcp = new VBCodeProvider(); ext = "*.vb"; Console.WriteLine("Using Visual Basic.NET (VBCodeDomProvider)..."); break; case "js": case "js.net": case "jscript": case "jscript.net": case "javascript": case "javascript.net": cdcp = new JScriptCodeProvider(); ext = "*.js"; Console.WriteLine("Using JScript.NET (JScriptCodeProvider)..."); break; case "cs": case "c#": case "csharp": case "visual cs": case "visual c#": case "visual csharp": // inited as C# Console.WriteLine("Using C# (CSharpCodeProvider)..."); break; default: Console.WriteLine("Language not explicitely defined, using C# (CSharpCodeProvider)..."); break; } } //if (!json.Has("version")) // throw new CompileException("Missing ModInfo field 'version'"); //if (!json.Has("info")) // throw new CompileException("Missing ModInfo field 'info'"); modInfo = (string)json; } catch (Exception e) { throw new CompilerException("Invalid file: ModInfo.json", e); } #endregion #region compile the code List<string> toCompile = new List<string>(); foreach (string file in Directory.EnumerateFiles(modDirectory, ext, SearchOption.AllDirectories)) toCompile.Add(file); CompilerParameters cp = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = false, OutputAssembly = outputDirectory + "\\" + modName + ".tapimod" }; string xna = Environment.GetEnvironmentVariable("XNAGSv4") + "\\References\\Windows\\x86\\", wpf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\Profile\\Client\\", here = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); cp.ReferencedAssemblies.Add("tAPI.exe"); cp.ReferencedAssemblies.Add("Microsoft.JScript.dll"); cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll"); cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); cp.ReferencedAssemblies.Add("Accessibility.dll"); cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.ReferencedAssemblies.Add("System.Drawing.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("System.Numerics.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add(wpf + "PresentationCore.dll"); cp.ReferencedAssemblies.Add(wpf + "PresentationFramework.dll"); cp.ReferencedAssemblies.Add(wpf + "WindowsBase.dll"); cp.ReferencedAssemblies.Add(xna + "Microsoft.Xna.Framework.dll"); cp.ReferencedAssemblies.Add(xna + "Microsoft.Xna.Framework.Xact.dll"); cp.ReferencedAssemblies.Add(xna + "Microsoft.Xna.Framework.Game.dll"); cp.ReferencedAssemblies.Add(xna + "Microsoft.Xna.Framework.Graphics.dll"); CompilerResults cr = cdcp.CompileAssemblyFromFile(cp, toCompile.ToArray()); if (cr.Errors.HasErrors) return CompilerException.CreateException(cr.Errors); #endregion #region save to .tapimod file /* * How a .tapimod file looks like: * * - version (uint) * * - modinfo (string) * * - file amount (int) * * files: * - file name (string) * - file data length (int) * * files: * - file data (byte[]) * * - assembly data */ // VBCodeProvider automatically adds '.dll' string mod = outputDirectory + (cdcp is VBCodeProvider ? ".tapimod.dll" : ".tapimod"); List<Tuple<string, byte[]>> files = new List<Tuple<string, byte[]>>(); foreach (string fileName in Directory.EnumerateFiles(modDirectory, "*.*", SearchOption.AllDirectories)) if (!Path.GetExtension(fileName).EndsWith(ext.Substring(2))) files.Add(new Tuple<string, byte[]>(fileName.Substring(modDirectory.Length + 1).Replace('\\', '/'), File.ReadAllBytes(fileName))); BinBuffer bb = new BinBuffer(); bb.Write(Constants.versionAssembly); bb.Write(modInfo); bb.Write(files.Count); foreach (Tuple<string, byte[]> pfile in files) { bb.Write(pfile.Item1); bb.Write(pfile.Item2.Length); } foreach (Tuple<string, byte[]> pfile in files) bb.Write(pfile.Item2); bb.Pos = 0; File.WriteAllBytes(cdcp is VBCodeProvider ? Path.ChangeExtension(mod, null) : mod, bb.ReadBytes(bb.GetSize())); // generate false hashes CommonToolUtilities.AddHashes(modName, modDirectory); #endregion return null; }
public Compiler_JS() { CompileProvider = new JScriptCodeProvider() as CodeDomProvider; }
public static Assembly LoadMacroAssembly(MacroModule mod) { if(mod.Type==MacroType.Assembly) { return Assembly.LoadFrom(mod.Path); } else if(mod.Type==MacroType.JavaScript) { ICodeCompiler compiler = new JScriptCodeProvider().CreateCompiler(); CompilerParameters param = new CompilerParameters(); param.CompilerOptions += "/debug"; param.GenerateInMemory = true; param.GenerateExecutable = true; //param.ReferencedAssemblies.Add("mscorlib"); //�v��́H param.ReferencedAssemblies.Add("System.Drawing.dll"); param.ReferencedAssemblies.Add(GetMyExePath()); param.ReferencedAssemblies.Add(GetGTerminalPath()); foreach(string x in mod.AdditionalAssemblies) if(x.Length>0) param.ReferencedAssemblies.Add(x); CompilerResults result = compiler.CompileAssemblyFromFile(param, mod.Path); if(result.Errors.Count>0) { StringBuilder bld = new StringBuilder(); bld.Append(GApp.Strings.GetString("Message.MacroExec.FailedToCompileScript")); foreach(CompilerError err in result.Errors) { bld.Append(String.Format("Line {0} Column {1} : {2}\n", err.Line, err.Column, err.ErrorText)); } throw new Exception(bld.ToString()); } return result.CompiledAssembly; } else throw new Exception("Unsupported macro module type " + mod.Type.ToString() + " is specified."); }
public static Assembly LoadMacroAssembly(MacroModule mod) { if (mod.Type == MacroType.Assembly) { return Assembly.LoadFrom(mod.Path); } else if (mod.Type == MacroType.JavaScript) { JScriptCodeProvider compiler = new JScriptCodeProvider(); CompilerParameters param = new CompilerParameters(); param.IncludeDebugInformation = true; param.GenerateInMemory = false; //これがプラグインをロードできるかどうかの決め手になった。周辺をすべて理解したわけではないが、とりあえずこれでよしとする。深入りしている時間はあまりないし param.GenerateExecutable = true; StringCollection sc = param.ReferencedAssemblies; bool[] assyAdded = new bool[9]; foreach (Assembly assy in AppDomain.CurrentDomain.GetAssemblies()) { try { string assyFilePath = new Uri(assy.CodeBase).LocalPath; string assyFileName = Path.GetFileName(assyFilePath).ToLower(CultureInfo.InvariantCulture); switch (assyFileName) { case "system.drawing.dll": assyAdded[0] = true; break; case "system.windows.forms.dll": assyAdded[1] = true; break; case "poderosa.plugin.dll": assyAdded[2] = true; break; case "poderosa.core.dll": assyAdded[3] = true; break; case "granados.dll": assyAdded[4] = true; break; case "poderosa.protocols.dll": assyAdded[5] = true; break; case "poderosa.terminalemulator.dll": assyAdded[6] = true; break; case "poderosa.terminalsession.dll": assyAdded[7] = true; break; case "poderosa.macro.dll": assyAdded[8] = true; break; case "poderosa.monolithic.exe": // FIXME: it is better to use the name of the entry assembly. // but how can we know the entry assembly is the monolithic type ? assyAdded[2] = assyAdded[3] = assyAdded[4] = assyAdded[5] = assyAdded[6] = assyAdded[7] = assyAdded[8] = true; break; default: continue; } Debug.WriteLine("(LoadMacroAssembly) add to ReferencedAssemblies: " + assyFilePath); sc.Add(assyFilePath); } catch (Exception) { } } foreach (bool flag in assyAdded) { if (!flag) { throw new Exception(MacroPlugin.Instance.Strings.GetString("Message.MacroExec.MissingAssemblies")); } } foreach (string x in mod.AdditionalAssemblies) if (x.Length > 0) sc.Add(x); CompilerResults result = compiler.CompileAssemblyFromFile(param, mod.Path); if (result.Errors.Count > 0) { StringBuilder bld = new StringBuilder(); bld.Append(MacroPlugin.Instance.Strings.GetString("Message.MacroExec.FailedToCompileScript")); foreach (CompilerError err in result.Errors) { bld.Append(String.Format("Line {0} Column {1} : {2}\n", err.Line, err.Column, err.ErrorText)); } throw new Exception(bld.ToString()); } Debug.WriteLineIf(DebugOpt.Macro, "Compiled:" + result.PathToAssembly + " FullName:" + result.CompiledAssembly.FullName); //AppDomain.CurrentDomain.Load(result.CompiledAssembly.FullName, result.Evidence); return result.CompiledAssembly; } else throw new Exception("Unsupported macro module type " + mod.Type.ToString() + " is specified."); }
public ICompilerResult Compile() { CompilerParameters options = new CompilerParameters(); if (_target != null) AddCompilerOption("/target:" + _target); if (_platform != null) AddCompilerOption("/platform:" + _platform); //options.GenerateExecutable = _generateExecutable; options.GenerateExecutable = IsTargetExecutable(_target); options.GenerateInMemory = _generateInMemory; options.IncludeDebugInformation = _debugInformation; // WarningLevel : from http://msdn.microsoft.com/en-us/library/13b90fz7.aspx // 0 Turns off emission of all warning messages. // 1 Displays severe warning messages. // 2 Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members. // 3 Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false. // 4 (the default) Displays all level 3 warnings plus informational warnings. options.WarningLevel = _warningLevel; options.OutputAssembly = _outputAssembly; options.CompilerOptions = _compilerOptions; //foreach (string assembly in _referencedAssemblies) foreach (ReferencedAssembly assembly in _referencedAssemblies) options.ReferencedAssemblies.Add(assembly.File); foreach (ResourceFile resource in _embeddedResources) options.EmbeddedResources.Add(resource.File); CodeDomProvider provider = new JScriptCodeProvider(); CompilerResults result = provider.CompileAssemblyFromFile(options, _sources.ToArray()); provider.Dispose(); return new CodeDomProviderCompilerResult(result); }
public JScriptEval() { var compiler = new JScriptCodeProvider(); var parameters = new CompilerParameters { GenerateInMemory = true }; string jscriptSource = @"package Evaluator { class Evaluator { public function Eval(expr : String) { return eval(expr); } } }"; var results = compiler.CompileAssemblyFromSource(parameters, jscriptSource); var assembly = results.CompiledAssembly; evaluatorType = assembly.GetType("Evaluator.Evaluator"); evaluator = Activator.CreateInstance(evaluatorType); }
//public void AddCopyOutputDirectories(IEnumerable<XElement> elements) //{ // foreach (XElement element in elements) // { // CopyOutputDirectory cod = new CopyOutputDirectory(); // cod.Directory = zpath.PathMakeRooted(element.zAttribValue("value"), gsDefaultDir); // AddFiles(cod.Files, element.zXPathElements("File"), gsDefaultDir); // _copyOutputDirectories.Add(cod); // } //} //public void CloseProcess() //{ // SetFinalOutputAssembly(); // if (_finalOutputAssembly == null) return; // string processName = zpath.PathGetFileName(_finalOutputAssembly); // foreach (Process process in Process.GetProcessesByName(processName)) // { // if (string.Compare(process.MainModule.FileName, _finalOutputAssembly, true) != 0) continue; // zprocess.CloseProcess(process); // } //} public void Compile() { if (!_generateInMemory && _outputAssembly == null) throw new PBException("output assembly is not defined"); SetFinalOutputAssembly(); if (_finalOutputDir != null) zDirectory.CreateDirectory(_finalOutputDir); //WriteLine(1, "Compile \"{0}\"", gsFinalOutputAssembly); //_defaultDir ////WriteLine(1, "Compiler _defaultDir \"{0}\"", _defaultDir); WriteLine(2, "Compile \"{0}\"", _finalOutputAssembly); WriteLine(2, " DebugInformation {0}", _debugInformation); WriteLine(2, " GenerateInMemory {0}", _generateInMemory); WriteLine(2, " GenerateExecutable {0}", _generateExecutable); WriteLine(2, " WarningLevel {0}", _warningLevel); WriteLine(2, " CompilerOptions \"{0}\"", _compilerOptions); _appConfig = GetCompilerFileName("app.config"); if (_appConfig != null) WriteLine(2, " app.config \"{0}\"", _appConfig.File); CompilerParameters options = new CompilerParameters(); options.CompilerOptions = _compilerOptions; options.GenerateInMemory = _generateInMemory; options.OutputAssembly = _finalOutputAssembly; options.GenerateExecutable = _generateExecutable; options.IncludeDebugInformation = _debugInformation; // WarningLevel : from http://msdn.microsoft.com/en-us/library/13b90fz7.aspx // 0 Turns off emission of all warning messages. // 1 Displays severe warning messages. // 2 Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members. // 3 Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false. // 4 (the default) Displays all level 3 warnings plus informational warnings. options.WarningLevel = _warningLevel; //foreach (string s in gAssemblyList.Values) foreach (CompilerAssembly assembly in _assemblyList.Values) { WriteLine(2, " Assembly \"{0}\" resolve {1}", assembly.File, assembly.Resolve); options.ReferencedAssemblies.Add(assembly.File); if (assembly.Resolve) AssemblyResolve.Add(assembly.File, assembly.ResolveName); } CompilerFile[] resources = GetCompilerFilesType(".resx"); //string[] compiledResources = CompileResources(resources, gsFinalOutputDir); string[] compiledResources = CompileResources(resources); foreach (string compiledResource in compiledResources) { WriteLine(2, " Resource \"{0}\"", compiledResource); options.EmbeddedResources.Add(compiledResource); } WriteLine(2, " Resource error {0}", _resourceResults.Errors.Count); if (_resourceResults.HasError) return; //CSharpCodeProvider provider = new CSharpCodeProvider(gProviderOption); CodeDomProvider provider = null; string sourceExt = null; //gLanguage CSharp, JScript if (_language == null) throw new PBException("error undefined language"); string language = _language.ToLower(); if (language == "csharp") { provider = new CSharpCodeProvider(_providerOption); sourceExt = ".cs"; } else if (language == "jscript") { provider = new JScriptCodeProvider(); sourceExt = ".js"; } else throw new PBException("error unknow language \"{0}\"", _language); //string[] sSources = GetFilesType(".cs"); string[] sSources = GetFilesType(sourceExt); //string currentDirectory = zDirectory.GetCurrentDirectory(); //Directory.SetCurrentDirectory(zapp.GetAppDirectory()); //cTrace.Trace("Compiler.Compile() : change current directory to {0}", cu.GetAppDirectory()); _results = provider.CompileAssemblyFromFile(options, sSources); WriteLine(2, " Compile error warning {0}", _results.Errors.Count); WriteLine(2, " Compile has error {0}", _results.Errors.HasErrors); WriteLine(2, " Compile has warning {0}", _results.Errors.HasWarnings); //Directory.SetCurrentDirectory(currentDirectory); //cTrace.Trace("Compiler.Compile() : restore current directory to {0}", currentDirectory); provider.Dispose(); //CopyAssemblyToOutputDir(); //if (gResults.PathToAssembly != null && !gbGenerateInMemory) //{ // List<string> copiedFiles = CopyReferencedAssembliesToDirectory(zpath.PathGetDirectory(gResults.PathToAssembly)); // _outputFiles.AddRange(copiedFiles); //} //CopyFileToOutputDir(); //if (gResults.PathToAssembly != null) //{ // List<string> copiedFiles = CopyFilesToDirectory(zpath.PathGetDirectory(gResults.PathToAssembly)); // _outputFiles.AddRange(copiedFiles); //} if (_results.PathToAssembly != null) CopyResultFilesToDirectory(); CopyOutputToDirectories(); }
static void BuildSource(string sourcePath, string outputPath, JsonData modInfo, CompileException cex, Dictionary<string, string> dictNames) { string[] modPathSplit = sourcePath.Split('\\', '/'); string modName = modPathSplit[modPathSplit.Length - 1].Split('.')[0]; if (modInfo.Has("MSBuild")) if ((bool)modInfo["MSBuild"]) { // done by msbuild anyway ModsCompile.BuildSource(sourcePath, outputPath, modInfo, cex, dictNames); return; } bool generatePDB = false; if (modInfo.Has("includePDB")) generatePDB = (bool)modInfo["includePDB"]; // but this has to change - other CodeDomProviders (default stays C#) CodeDomProvider cdp = new CSharpCodeProvider(); foreach (string fileName in Directory.EnumerateFiles(sourcePath, "*.json", SearchOption.AllDirectories)) { string fname = fileName.Substring(sourcePath.Length + 1).Replace('\\', '/'); if (fname == "ModInfo.json") continue; try { JsonData json2 = JsonMapper.ToObject(File.ReadAllText(fileName)); if (fname.ToLower().StartsWith("item/")) ValidateJson.Item(modName, fileName, json2, cex); if (fname.ToLower().StartsWith("npc/")) ValidateJson.NPC(modName, fileName, json2, cex); if (fname.ToLower().StartsWith("projectile/")) ValidateJson.Projectile(modName, fileName, json2, cex); //TODO: check all the JSON files other than ModInfo.json for required fields } catch (Exception e) { cex.AddProblem(fileName, "Invalid JSON file.\n" + e.Message); } } CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); cp.IncludeDebugInformation = generatePDB; cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.ReferencedAssemblies.Add("System.Numerics.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Drawing.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Xact.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Game.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Graphics.dll"); if (modInfo != null) { if (modInfo.Has("language")) switch (((string)modInfo["language"]).ToLowerInvariant()) { case "js": case "js.net": case "jscript": case "jscript.net": case "javascript": case "javascript.net": cdp = new JScriptCodeProvider(); break; case "vb": case "vb.net": case "visualbasic": case "visualbasic.net": case "visual basic": case "visual basic.net": cdp = new VBCodeProvider(); break; } if (modInfo.Has("modReferences")) { if (Directory.Exists(Mods.pathDirMods + "/.Temp")) Directory.Delete(Mods.pathDirMods + "/.Temp", true); Directory.CreateDirectory(Mods.pathDirMods + "/.Temp"); JsonData jRefs = (JsonData)modInfo["modReferences"]; for (int i = 0; i < jRefs.Count; i++) { string jRef = (string)jRefs[i]; if (!dictNames.ContainsKey(jRef)) continue; string modfile = dictNames[jRef]; cp.ReferencedAssemblies.Add(Mods.pathDirMods + "/.Temp/" + jRef + ".dll"); string[] split = jRef.Split('\\'); if (modfile.EndsWith(".tapimod")) { using (FileStream fileStream = new FileStream(modfile, FileMode.Open)) { BinBuffer bb2 = new BinBuffer(new BinBufferStream(fileStream)); bb2.ReadInt(); bb2.ReadString(); int count = bb2.ReadInt(); int skip = 0; while (count-- > 0) { bb2.ReadString(); skip += bb2.ReadInt(); } while (skip-- > 0) bb2.ReadByte(); File.WriteAllBytes(Mods.pathDirMods + "/.Temp/" + jRef + ".dll", bb2.ReadBytes(bb2.BytesLeft())); } } else if (modfile.EndsWith(".tapi")) { using (ZipFile zip = ZipFile.Read(modfile)) { if (zip.ContainsEntry("Mod.tapimod")) { ZipEntry ze = zip["Mod.tapimod"]; using (MemoryStream ms = new MemoryStream()) { ze.Extract(ms); ms.Position = 0; BinBuffer bb2 = new BinBuffer(new BinBufferStream(ms)); bb2.ReadInt(); bb2.ReadString(); int count = bb2.ReadInt(); int skip = 0; while (count-- > 0) { bb2.ReadString(); skip += bb2.ReadInt(); } while (skip-- > 0) bb2.ReadByte(); File.WriteAllBytes(Mods.pathDirMods + "/.Temp/" + jRef + ".dll", bb2.ReadBytes(bb2.BytesLeft())); } } } } } } if (modInfo.Has("dllReferences")) { JsonData jRefs = (JsonData)modInfo["dllReferences"]; for (int i = 0; i < jRefs.Count; i++) { string jRef = (string)jRefs[i]; if (File.Exists(sourcePath + "/" + jRef)) // remove .dll -> can also reference .exes cp.ReferencedAssemblies.Add(sourcePath + "/" + jRef); else cp.ReferencedAssemblies.Add(jRef); // somewhere else, like the GAC } } } cp.OutputAssembly = outputPath + (cdp is VBCodeProvider ? "" : ".dll"); // VBCodeProvider automatically adds '.dll' List<string> toCompile = new List<string>(); foreach (string fileName in Directory.EnumerateFiles(sourcePath, cdp.FileExtension, SearchOption.AllDirectories)) toCompile.Add(fileName); CompilerResults cr = cdp.CompileAssemblyFromFile(cp, toCompile.ToArray()); if (Directory.Exists(Mods.pathDirMods + "/.Temp")) Directory.Delete(Mods.pathDirMods + "/.Temp", true); if (cr.Errors.HasErrors) { foreach (CodeDomError ce in cr.Errors) { StringBuilder sb = new StringBuilder(); if (ce.FileName != "") { sb.Append("(" + ce.Column + "," + ce.Line + "): " + ce.ErrorText); sb.Append("\n" + File.ReadLines(ce.FileName).Skip(ce.Line - 1).Take(1).First().Replace("\t", " ")); sb.Append('\n'); for (int i = 0; i < ce.Column - 1; i++) sb.Append(' '); sb.Append('^'); cex.AddProblem(ce.FileName, sb.ToString()); } else // general error (without file) - .dll not found, etc cex.AddProblem(outputPath, (ce.IsWarning ? "warning" : "error") + " " + ce.ErrorNumber + ": " + ce.ErrorText); } } if (cex.problems.Count != 0) { if (File.Exists(outputPath + ".dll")) File.Delete(outputPath + ".dll"); throw cex; } }
public static CompilerResults CompileFromJScriptSourceStream(Stream sourceStream, CompilerParameters cParams) { String tmpFile = Path.GetTempFileName(); using (FileStream output = new FileStream(tmpFile, FileMode.Create)) { byte[] buffer = new byte[sourceStream.Length]; sourceStream.Seek(0, SeekOrigin.Begin); sourceStream.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, buffer.Length); } using (CodeDomProvider provider = new JScriptCodeProvider()) { CompilerResults res = provider.CompileAssemblyFromFile(cParams, tmpFile); File.Delete(tmpFile); return res; } }
// ���\�b�h // �t�@�C������ǂݎ�����R�[�h��R���p�C�����܂��B // �o�̓t�@�C���� null �Ƃ���ƃI���������ŃR���p�C����s���܂��B // �R�[�h�̎�ނ͍ŏ��̃t�@�C���̊g���q�Ŕ��ʂ��܂��B public CompilerResults Compile(FileInfo[] sourceFiles, FileInfo dest, EcmProject project) { if(sourceFiles == null || sourceFiles.Length == 0) return null; CodeDomProvider compiler = null; string codeFrame = null; if(sourceFiles[0].Extension.Equals(EcmProject.CSharpFileSuffix)){ if(string.IsNullOrEmpty(CSCVersionConfig)){ compiler = new CSharpCodeProvider(); } else { compiler = new CSharpCodeProvider(new Dictionary<string, string>(){{"CompilerVersion", CSCVersionConfig}}); } codeFrame = CsCodeFrame; } else if(sourceFiles[0].Extension.Equals(EcmProject.JScriptFileSuffix)){ compiler = new JScriptCodeProvider(); codeFrame = JsCodeFrame; } else { throw new Exception("�s���ȃt�@�C���g���q�ł��B�R���p�C�����錾�ꂪ����ł��܂���B"); } string[] sourceData = new string[sourceFiles.Length]; for(int i=0; i< sourceFiles.Length; i++){ string tempData = ""; using(FileStream fs = sourceFiles[i].Open(FileMode.Open, FileAccess.Read, FileShare.Read)){ using(StreamReader sr = new StreamReader(fs)){ tempData = sr.ReadToEnd(); sr.Close(); } fs.Close(); } string fileName = Path.GetFileNameWithoutExtension(sourceFiles[i].Name).Replace("-", ""); sourceData[i] = string.Format(codeFrame, project.GetPluginNameSpace(), fileName.ToLower(), tempData); } CompilerParameters cp = new CompilerParameters(myCurrentReferenceAsmNames); if(dest ==null){ cp.GenerateInMemory = true; } else { cp.GenerateInMemory = false; cp.OutputAssembly = dest.FullName; } // Util.Throw(myCurrentReferenceAsmNames); CompilerResults cr = compiler.CompileAssemblyFromSource(cp, sourceData); return cr; }
/// <summary> /// Performs the actual compiling of the <see cref="Assembly"/>. Will be called by the /// <see cref="ScriptAssemblyCache"/> if the source didn't exist in the cache. /// </summary> /// <param name="sourceCode">The source code to compile.</param> /// <param name="filePath">The file path to give the generated <see cref="Assembly"/>.</param> /// <returns>The generated <see cref="Assembly"/>. Can be null if there was any errors generating it.</returns> protected virtual Assembly CompileSourceToAssembly(string sourceCode, string filePath) { CompilerResults results; // Set up the compiler parameters var p = new CompilerParameters { GenerateInMemory = false, IncludeDebugInformation = false, OutputAssembly = filePath }; // Compile using (var provider = new JScriptCodeProvider()) { results = provider.CompileAssemblyFromSource(p, sourceCode); } // Store the compilation errors if (results.Errors.Count > 0) { const string errmsg = "Error compiling JScript assembly: {0}"; if (log.IsErrorEnabled) { foreach (var err in results.Errors.OfType<CompilerError>()) { log.ErrorFormat(errmsg, err); } } Debug.Assert(!results.Errors.HasErrors, "One or more errors when compiling JScript assembly."); _compilationErrors = results.Errors.OfType<CompilerError>().ToImmutable(); } else _compilationErrors = _emptyCompilerErrors; // Return the compiled assembly return results.CompiledAssembly; }