public static bool ImportJSFile(string file) { if (File.Exists(file)) { try { var str = file; var pa = new CompilerParameters { GenerateInMemory = true }; var result = MJScriptCodeProvider.CompileAssemblyFromSource(parameters, str); var ass = result.CompiledAssembly; var s = ass.GetType(); var obj = s.InvokeMember("Test", BindingFlags.InvokeMethod, null, null, new object[] { "this ok" }); Console.WriteLine("OBJ::" + obj); return(true); } catch (Exception) { return(false); } } return(false); }
public static dynamic CreateJsInstance(string jsFilePath, string jsClassName = "JsProgram") { var opt = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; //opt.ReferencedAssemblies.Add("System.dll"); //Assembly.LoadFile(FileHelper.GetFullPath("~/CS.Utility.dll")); //Assembly.LoadFile(FileHelper.GetFullPath("~/CS.CodeRobot.Generator.dll")); var x = "1".ToInt(0); opt.ReferencedAssemblies.Add(FileHelper.GetFullPath("~/CS.Utility.dll")); opt.ReferencedAssemblies.Add(FileHelper.GetFullPath("~/CS.CodeRobot.Generator.dll")); //非GAC必须全路径 var content = File.ReadAllText(jsFilePath); var result = JsCompiler.CompileAssemblyFromSource(opt, content); if (result.Errors.Count > 0) { log.Error($"[Compile Error:{result.Errors.Count}]"); foreach (var error in result.Errors) { log.Error(error); } return(null); } var js = result.CompiledAssembly; dynamic instace = js.CreateInstance(jsClassName); return(instace); }
public CompilerResults Build(string dirWithSrc) { string[] sources = GetSourcesFromDir(dirWithSrc, new string[] { ".js" }); var csc = new JScriptCodeProvider(); var parameters = new CompilerParameters(); parameters.OutputAssembly = OutputFile; parameters.GenerateExecutable = Executable; parameters.GenerateInMemory = GenerateInMemory; parameters.IncludeDebugInformation = IncludeDebugInfo; parameters.ReferencedAssemblies.AddRange(IncludedLibraries.ToArray()); parameters.EmbeddedResources.AddRange(EmbeddedResources.ToArray()); parameters.LinkedResources.AddRange(LinkedResources.ToArray()); if (MainClass != null) { parameters.MainClass = MainClass; } CompilerResults results = csc.CompileAssemblyFromSource(parameters, sources); return(results); }
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 static CompilerResults CompileFromJScriptSourceCode(String sourceCode, CompilerParameters cParams) { using (CodeDomProvider provider = new JScriptCodeProvider()) { CompilerResults res = provider.CompileAssemblyFromSource(cParams, sourceCode); 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); }
/// <summary> /// Compiles the specified Javascript files. /// </summary> /// <param name="files">The absolute file paths to .js files.</param> public IDictionary <string, JavascriptCompilerResult> Compile(params string[] files) { var compilerResults = new Dictionary <string, JavascriptCompilerResult>(); foreach (var file in files) { using (var reader = File.OpenText(file)) { var source = reader.ReadToEnd(); var results = _provider.CompileAssemblyFromSource(_parameters, source); var javascriptCompilerResult = new JavascriptCompilerResult(); foreach (var error in results.Errors.Cast <CompilerError>().Where(error => !_ignoredRules.Contains(error.ErrorNumber))) { javascriptCompilerResult.Errors.Add(error); } compilerResults.Add(file, javascriptCompilerResult); } } return(compilerResults); }
static JsEvaluator() { //VsaEngine eng = new VsaEngine(true); //Closure //en CodeDomProvider c = new JScriptCodeProvider(); CompilerParameters parameters = new CompilerParameters();; parameters.GenerateInMemory = true; CompilerResults results = c.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); }
/// <summary> /// Include and compile a JScript Module(s). Can be the contents of a file read with File.ReadContents(). /// </summary> /// <param name="source">The JScript source.</param> /// <param name="assemblies">An array of any additional assemblies required.</param> /// <param name="dllName">An optional path to create a dll output, use "" to perform in-memory.</param> /// <returns>"FAILED" or "SUCCESS"</returns> public static Primitive IncludeJScript(Primitive source, Primitive assemblies, Primitive dllName) { try { CompilerParameters compilerParams = SetReferences(assemblies, dllName, true); JScriptCodeProvider provider = new JScriptCodeProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(compilerParams, source); return(PostCompile(compile)); } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); } return("FAILED"); }
private 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); }
private static object GetEvaluator() { CompilerParameters parameters; parameters = new CompilerParameters(); parameters.GenerateInMemory = true; JScriptCodeProvider jp = new JScriptCodeProvider(); CompilerResults results = jp.CompileAssemblyFromSource(parameters, _evaluatorSourceCode); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.Evaluator"); return(Activator.CreateInstance(_evaluatorType)); }
static public void Main() { string[] source = new string[] { @"import System; class JsProgram { function Print(mes){ Console.WriteLine(mes); } function Hello(world){ Print(world); } function proc(){ var world = ""World""; var bool = true; if(bool == true){ Print(""True is True""); } else{ Print(""False is True""); } Hello(world); } }" }; var compiler = new JScriptCodeProvider(); var opt = new CompilerParameters(); opt.ReferencedAssemblies.Add("System.dll"); opt.GenerateExecutable = false; opt.GenerateInMemory = true; var result = compiler.CompileAssemblyFromSource(opt, source); if (result.Errors.Count > 0) { Console.WriteLine("Compile Error"); return; } var js = result.CompiledAssembly; dynamic jsProg = js.CreateInstance("JsProgram"); jsProg.proc(); /* * True is True * World */ }
static Evaluator() { 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("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); }
/// <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); }
// Methods static Evaluator() { _CheckMono(); var parameters = new CompilerParameters { GenerateInMemory = true }; CompilerParameters options = parameters; CompilerResults results = _provider.CompileAssemblyFromSource(options, new[] { JSCRIPT_SOURCE }); if (results.Errors.Count > 0) { string message = ""; foreach (CompilerError error in results.Errors) { message = message + error; message = message + "\n"; } throw new ApplicationException(message); } _evaluator_type = results.CompiledAssembly.GetType("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluator_type); }
//public static void Test_GetNewIndexedDirectory_01() //{ // Trace.WriteLine("Test_GetNewIndexedDirectory_01"); // string dir = @"c:\pib\_dl\_jd\_new\pdf"; // Trace.WriteLine("dir \"{0}\"", dir); // string newDir = zfile.GetNewIndexedDirectory(dir); // Trace.WriteLine("new dir \"{0}\"", newDir); //} public static void Test_JScript_01() { Trace.WriteLine("Test_JScript_01"); CodeDomProvider provider = new JScriptCodeProvider(); CompilerParameters para = new CompilerParameters(); para.GenerateInMemory = true; // string jscode = // @"class Sample // { // var mytext=’This is JScript’; // }"; string jscode = zfile.ReadAllText("magazine3k.js"); //string jscode = "function test_javascript_01() { return \"toto\"; }"; CompilerResults result = provider.CompileAssemblyFromSource(para, jscode); Assembly assembly = result.CompiledAssembly; Type jsType = assembly.GetType("magazine3k.test"); //object jsObject = Activator.CreateInstance(jsType); //object retValue = jsType.InvokeMember("text", BindingFlags.GetField, null, jsObject, null); //wr.WriteLine("text : {0}", retValue); //object retValue = jsType.InvokeMember("test_01", BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, null, null, null); // BindingFlags.CreateInstance BindingFlags.GetField | BindingFlags.SetField BindingFlags.GetProperty | BindingFlags.SetProperty //object retValue = jsType.InvokeMember("test_01", BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, null); object retValue = jsType.InvokeMember("test_01", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, null); Trace.WriteLine("magazine3k.test.test_01() : {0}", retValue); jsType = assembly.GetType("magazine3k.magazine3k"); object jsObject = Activator.CreateInstance(jsType); jsType.InvokeMember("init", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, jsObject, null); Trace.WriteLine("magazine3k.magazine3k.init()"); string s = "wjSWs:VK00ZX.BmUr+K5yxa.hK1sA?UYYqB51IUqPKffxQ"; retValue = jsType.InvokeMember("encrypt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, jsObject, new object[] { s }); Trace.WriteLine("magazine3k.magazine3k.encrypt(\"{0}\") : \"{1}\"", s, retValue); }
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); }
/// <summary> /// Compile .NET script to .Net assembly (.dll) /// </summary> /// <param name="Script">CS script</param> /// <returns>Filename to .dll assembly</returns> internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset) { string ext = "." + lang.ToString(); // Output assembly name scriptCompileCounter++; string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine( m_scriptEngine.World.RegionInfo.RegionID.ToString(), FilePrefix + "_compiled_" + asset + ".dll")); try { File.Delete(OutFile); } catch (Exception e) // NOTLEGIT - Should be just FileIOException { throw new Exception("Unable to delete old existing " + "script-file before writing new. Compile aborted: " + e.ToString()); } // DEBUG - write source to disk if (WriteScriptSourceToDebugFile) { string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(OutFile) + ext; try { File.WriteAllText(Path.Combine(Path.Combine( ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), srcFileName), Script); } catch (Exception ex) //NOTLEGIT - Should be just FileIOException { m_log.Error("[Compiler]: Exception while " + "trying to write script source to file \"" + srcFileName + "\": " + ex.ToString()); } } // Do actual compile CompilerParameters parameters = new CompilerParameters(); parameters.IncludeDebugInformation = true; string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll")); if (lang == enumCompileType.yp) { parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll")); } parameters.GenerateExecutable = false; parameters.OutputAssembly = OutFile; parameters.IncludeDebugInformation = CompileWithDebugInformation; //parameters.WarningLevel = 1; // Should be 4? parameters.TreatWarningsAsErrors = false; CompilerResults results; switch (lang) { case enumCompileType.vb: results = VBcodeProvider.CompileAssemblyFromSource( parameters, Script); break; case enumCompileType.cs: case enumCompileType.lsl: lock (CScodeProvider) { results = CScodeProvider.CompileAssemblyFromSource( parameters, Script); } break; case enumCompileType.js: results = JScodeProvider.CompileAssemblyFromSource( parameters, Script); break; case enumCompileType.yp: results = YPcodeProvider.CompileAssemblyFromSource( parameters, Script); break; default: throw new Exception("Compiler is not able to recongnize " + "language type \"" + lang.ToString() + "\""); } // Check result // Go through errors // // WARNINGS AND ERRORS // int display = 5; if (results.Errors.Count > 0) { string errtext = String.Empty; foreach (CompilerError CompErr in results.Errors) { // Show 5 errors max // if (display <= 0) { break; } display--; string severity = "Error"; if (CompErr.IsWarning) { severity = "Warning"; } KeyValuePair <int, int> lslPos; lslPos = FindErrorPosition(CompErr.Line, CompErr.Column); string text = CompErr.ErrorText; // Use LSL type names if (lang == enumCompileType.lsl) { text = ReplaceTypes(CompErr.ErrorText); } // The Second Life viewer's script editor begins // countingn lines and columns at 0, so we subtract 1. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n", lslPos.Key - 1, lslPos.Value - 1, CompErr.ErrorNumber, text, severity); } if (!File.Exists(OutFile)) { throw new Exception(errtext); } } // // NO ERRORS, BUT NO COMPILED FILE // if (!File.Exists(OutFile)) { string errtext = String.Empty; errtext += "No compile error. But not able to locate compiled file."; throw new Exception(errtext); } // m_log.DebugFormat("[Compiler] Compiled new assembly "+ // "for {0}", asset); // Because windows likes to perform exclusive locks, we simply // write out a textual representation of the file here // // Read the binary file into a buffer // FileInfo fi = new FileInfo(OutFile); if (fi == null) { string errtext = String.Empty; errtext += "No compile error. But not able to stat file."; throw new Exception(errtext); } Byte[] data = new Byte[fi.Length]; try { FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read); fs.Read(data, 0, data.Length); fs.Close(); } catch (Exception) { string errtext = String.Empty; errtext += "No compile error. But not able to open file."; throw new Exception(errtext); } // Convert to base64 // string filetext = System.Convert.ToBase64String(data); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(filetext); FileStream sfs = File.Create(OutFile + ".text"); sfs.Write(buf, 0, buf.Length); sfs.Close(); string posmap = String.Empty; if (m_positionMap != null) { foreach (KeyValuePair <KeyValuePair <int, int>, KeyValuePair <int, int> > kvp in m_positionMap) { KeyValuePair <int, int> k = kvp.Key; KeyValuePair <int, int> v = kvp.Value; posmap += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value); } } buf = enc.GetBytes(posmap); FileStream mfs = File.Create(OutFile + ".map"); mfs.Write(buf, 0, buf.Length); mfs.Close(); return(OutFile); }