public SourceCodeBundle(ScriptBundleLoader manager, IEnumerable <string> sourceCodes) { //this.manager = manager; var domain = System.AppDomain.CurrentDomain; this.assemblyReferences = domain .GetAssemblies() .Where(a => !(a is System.Reflection.Emit.AssemblyBuilder) && !string.IsNullOrEmpty(a.Location)) .Select(a => a.Location) .ToArray(); var options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.ReferencedAssemblies.AddRange(assemblyReferences); var compiler = new CodeCompiler(); var result = compiler.CompileAssemblyFromSourceBatch(options, sourceCodes.ToArray()); foreach (var err in result.Errors) { manager.actLog(err.ToString()); } this._assembly = result.CompiledAssembly; }
public static Assembly Compile(string source) { var options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!assembly.IsDynamic) { options.ReferencedAssemblies.Add(assembly.Location); } } var compiler = new CSharpCompiler.CodeCompiler(); var result = compiler.CompileAssemblyFromSource(options, source); foreach (var err in result.Errors) { Debug.Log(err); } return(result.CompiledAssembly); }
private string compilerErrorMessages = ""; // Displayed on the GUI private void Compile(string redBoxerClass, string blueBoxerClass) { try { compilerErrorMessages = ""; // clear any previous messages // ********** Create an instance of the C# compiler //CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CSharpCompiler.CodeCompiler codeCompiler = new CSharpCompiler.CodeCompiler(); // ********** add compiler parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize /warn:0"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Core.dll"); compilerParams.ReferencedAssemblies.Add(Assembly.GetCallingAssembly().Location); string redBoxerSource = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, redBoxerClass) + ".cs"); string blueBoxerSource = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, blueBoxerClass) + ".cs"); // ********** actually compile the code ??????? THIS LINE WORKS IN UNITY EDITOR --- BUT NOT IN BUILD ?????????? CompilerResults resultsRedBoxer = codeCompiler.CompileAssemblyFromSource(compilerParams, redBoxerSource); CompilerResults resultsBlueBoxer = codeCompiler.CompileAssemblyFromSource(compilerParams, blueBoxerSource); // ********** Do we have any compiler errors if (resultsRedBoxer.Errors.Count > 0 || resultsBlueBoxer.Errors.Count > 0) { foreach (CompilerError error in resultsRedBoxer.Errors) { compilerErrorMessages = compilerErrorMessages + error.ErrorText + '\n'; } } else { // ********** get a hold of the actual assembly that was generated Assembly generatedRedAssembly = resultsRedBoxer.CompiledAssembly; Assembly generatedBlueAssembly = resultsBlueBoxer.CompiledAssembly; if (generatedRedAssembly != null && generatedBlueAssembly != null) { // get type of class Calculator from just loaded assembly Type redClassType = generatedRedAssembly.GetType(redBoxerClass); Type blueClassType = generatedBlueAssembly.GetType(blueBoxerClass); RedStrategy = (AbstractBoxingStrategy)Activator.CreateInstance(redClassType); BlueStrategy = (AbstractBoxingStrategy)Activator.CreateInstance(blueClassType); // Say success! compilerErrorMessages = "Success!"; } } } catch (Exception o) { Debug.LogError("" + o.Message + "\n" + o.Source + "\n" + o.StackTrace + "\n"); throw o; } Debug.Log(compilerErrorMessages); }
public static Assembly Compile(string source) { var provider = new CodeCompiler(); var param = new CompilerParameters(); // Add ALL of the assembly references var prevAssemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < prevAssemblies.Length; i++) { try { param.ReferencedAssemblies.Add(prevAssemblies[i].Location); } catch (System.NotSupportedException e) { Debug.Log(e); } } //foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { // param.ReferencedAssemblies.Add(assembly.Location); //} // Or, uncomment just the assemblies you need... // System namespace for common types like collections. //param.ReferencedAssemblies.Add("System.dll"); // This contains methods from the Unity namespaces: //param.ReferencedAssemblies.Add("UnityEngines.dll"); // This assembly contains runtime C# code from your Assets folders: // (If you're using editor scripts, they may be in another assembly) //param.ReferencedAssemblies.Add("CSharp.dll"); // Generate a dll in memory param.GenerateExecutable = false; param.GenerateInMemory = true; // Compile the source var result = provider.CompileAssemblyFromFile(param, source); if (result.Errors.Count > 0) { var msg = new StringBuilder(); foreach (CompilerError error in result.Errors) { msg.AppendFormat("Error ({0}): {1}\n", error.ErrorNumber, error.ErrorText); } throw new Exception(msg.ToString()); } // Return the assembly return(result.CompiledAssembly); }
// Use this for initialization void Start() { //Setup compiler CSharpCompiler.CodeCompiler compiler = new CSharpCompiler.CodeCompiler(); System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.OutputAssembly = "MyAssembly.dll"; //-- Add ALL assemblies to compiler. This is a security issue as user would have access to System.IO.File to delete data... //var domain = System.AppDomain.CurrentDomain; //string[] assemblyReferences = domain.GetAssemblies().Select(a => a.Location).ToArray(); //options.ReferencedAssemblies.AddRange(assemblyReferences); //-- Add only some specific assemblies options.ReferencedAssemblies.Add("UnityEngine"); //Add UnityEngine assembly options.ReferencedAssemblies.Add("Assembly-CSharp"); //Add Assembly which holds all our scripts after build (THIS script is also located in this assembly) //Compile var result = compiler.CompileAssemblyFromFileBatch(options, new[] { Application.streamingAssetsPath + "/BasicExampleScript.cs" //Add other scripts here, separated by commas }); //Create instances for all classes we just compiled //foreach (var type in result.CompiledAssembly.GetTypes()) //{ // if (typeof(Component).IsAssignableFrom(type)) this.gameObject.AddComponent(type); //If type is a MonoBehaviour, add it to the gameobject // else System.Activator.CreateInstance(type); //Otherwise create a new instance of the class, using the default class constructor //} //Add specific MonoBehaviour from our compiled scripts Type _mb = result.CompiledAssembly.GetType("MyMonoBehaviour"); this.gameObject.AddComponent(_mb); Debug.Log(result.CompiledAssembly.GetName()); //Create an instance of a specific class Type _classType = result.CompiledAssembly.GetType("SomePublicClass"); var classInstance = Activator.CreateInstance(_classType); //Since SomePublicClass uses IMyClass interface (see below), we can cast to it :) IMyClass myClassInstance = (IMyClass)classInstance; myClassInstance.DoSomething(); //...and call a function defined in IMyClass Debug.Log("Sum:" + myClassInstance.Sum(40, 2)); //Another function in SomePublicClass which returns an int }
void CompileFiles() { filePaths = filePaths.Where(x => File.Exists(x)).ToArray(); var options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.ReferencedAssemblies.AddRange(assemblyReferences); var compiler = new CodeCompiler(); var result = compiler.CompileAssemblyFromFileBatch(options, filePaths.ToArray()); foreach (var err in result.Errors) { manager.logWriter.WriteLine(err); } this.assembly = result.CompiledAssembly; }
public Assembly Compile(string source) { //clear console errorText.text = ""; //set up compiler options CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; //add assemblies foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!assembly.IsDynamic) { compilerParameters.ReferencedAssemblies.Add(assembly.Location); } } //compiler code and get results CSharpCompiler.CodeCompiler virtualCompiler = new CSharpCompiler.CodeCompiler(); CompilerResults compilationResults = virtualCompiler.CompileAssemblyFromSource(compilerParameters, source); //do results have any errors? foreach (var err in compilationResults.Errors) { CompilerError e = (CompilerError)err; //cast a generic object to CompilerError //log errors to the console Debug.Log(e.ErrorText); //display errors to the console on the screen errorText.text += " " + e.ErrorText; } //return compiled (or not) code return(compilationResults.CompiledAssembly); }
void CompileFiles() { var options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = false; options.ReferencedAssemblies.AddRange(assemblyReferences); options.CompilerOptions = "/target:library /optimize"; options.OutputAssembly = DLLName + ".dll"; //options. var compiler = new CodeCompiler(); var result = compiler.CompileAssemblyFromSourceBatch(options, sources.ToArray()); foreach (var err in result.Errors) { manager.logWriter.WriteLine(err); } this.assembly = result.CompiledAssembly; var name = this.assembly.GetName(); }
void CompileFiles() { filePaths = filePaths.Where(x => File.Exists(x)).ToArray(); var options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.ReferencedAssemblies.AddRange(assemblyReferences); var compiler = new CodeCompiler(); var result = compiler.CompileAssemblyFromFileBatch(options, filePaths.ToArray()); // To stop coroutine at the present task if (result.Errors.Count > 0) { VirtualScriptEditor.Instance.isThereErrors = true; VirtualScriptEditor.Instance.errors = ""; } bool pair = false; foreach (var err in result.Errors) { //manager.logWriter.WriteLine(err); UnityErrorTextWriter errorWriter = new UnityErrorTextWriter(); errorWriter.Write(err); if (pair) { VirtualScriptEditor.Instance.errors += err + "\n"; } pair = !pair; } this.assembly = result.CompiledAssembly; }
protected Assembly CreateAssembly(string name, string[] code) { /* * The For now we will create one assembly for onLoad code call * on memory to cache and avoid IO problems. * To allow user add references a new keyword was created * Ex: * reference System.Data.dll * reference CustomAssembly.dll * reference Custom2 * * All the *using* and *reference* have to be befora all the statement code */ var parameters = new CompilerParameters(); var final = new List <string> { "using System;", "using RiveScript;" }; parameters.GenerateInMemory = true; parameters.GenerateExecutable = false; parameters.ReferencedAssemblies.Add("System.dll");//Add basic assemblies parameters.ReferencedAssemblies.Add("System.Core.dll"); parameters.ReferencedAssemblies.Add("UnityEngine.dll"); //parameters.ReferencedAssemblies.Add ("System.CodeDom.Compiler.dll"); //Add refernce to RiveScript assembly parameters.ReferencedAssemblies.Add(riveAssembly); //Add reference to current execution assemblie if (false == ExtensionsMethods.IsNullOrWhiteSpace(currentAssembly)) { parameters.ReferencedAssemblies.Add(currentAssembly); } IndentedTextWriter w; //Find all references and usings for (int i = 0; i < code.Length; i++) { var line = code[i]; if (ExtensionsMethods.IsNullOrWhiteSpace(line)) { continue; } line = line.Trim(); if (line.StartsWith("reference")) { var ra = line.Replace("reference", "") .Replace(" ", "") .Replace(";", ""); ra = ra.EndsWith(".dll") ? ra : (ra + ".dll"); parameters.ReferencedAssemblies.Add(ra); code[i] = ""; } else if (line.StartsWith("using") && false == line.StartsWith("using (") && false == line.StartsWith("using(")) { final.Add(line); //Early add usings code[i] = ""; } } final.Add("namespace " + ns); final.Add("{"); final.Add(" public class " + name); final.Add(" {"); final.Add(" public static string method(RiveScript rs, string[] args)"); final.Add(" {"); final.AddRange(code); final.Add(" }"); final.Add(" }"); final.Add("}"); var provider = new CSharpCompiler.CodeCompiler(); var result = provider.CompileAssemblyFromSource(parameters, String.Join(Environment.NewLine, final.ToArray())); if (result.Errors.HasErrors) { var sr = ""; foreach (CompilerError error in result.Errors) { sr += string.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText); } throw new InvalidOperationException("ERR: object " + name + " - " + sr); } return(result.CompiledAssembly); }
// Token: 0x06000D55 RID: 3413 RVA: 0x0005AF34 File Offset: 0x00059134 public static string ResolveScriptAssembly(string codeDir, ModContainer mod) { DirectoryInfo directoryInfo = new DirectoryInfo(codeDir); if (!directoryInfo.Exists) { MLog.Error("Code directory " + codeDir + " does not exist!"); return(string.Empty); } string assemblyPath = ModPaths.GetAssemblyPath(mod, directoryInfo.Name); if (File.Exists(assemblyPath)) { return(assemblyPath); } CompilerParameters compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, OutputAssembly = assemblyPath }; compilerParameters.ReferencedAssemblies.AddRange((from a in AppDomain.CurrentDomain.GetAssemblies().Where(delegate(Assembly a) { bool result; try { result = !string.IsNullOrEmpty(a.Location); } catch (NotSupportedException) { result = false; } return(result); }) select a.Location).ToArray <string>()); string[] array = (from f in directoryInfo.GetFiles("*.cs", SearchOption.AllDirectories) select f.FullName).ToArray <string>(); if (array.Length == 0) { MLog.Error("Code directory " + codeDir + " does not contain any source files!"); } CSharpCompiler.CodeCompiler codeCompiler = new CSharpCompiler.CodeCompiler(); CompilerResults compilerResults = codeCompiler.CompileAssemblyFromFileBatch(compilerParameters, array); foreach (object obj in compilerResults.Errors) { CompilerError compilerError = (CompilerError)obj; string message = compilerError.ToString(); if (compilerError.IsWarning) { MLog.Warn(message); } else { MLog.Error(message); } } if (compilerResults.Errors.HasErrors) { MLog.Error("There were errors compiling the ScriptAssembly at " + codeDir + "!"); } return(assemblyPath); }
void CompileFiles() { //filePaths = filePaths.Where(x => File.Exists(x)).ToArray(); CompilerParameters cp = new CompilerParameters(); //options.GenerateExecutable = false; //options.GenerateInMemory = true; cp.ReferencedAssemblies.AddRange(assemblyReferences); // cp.ReferencedAssemblies.Add("system.dll"); // cp.ReferencedAssemblies.Add("system.xml.dll"); // cp.ReferencedAssemblies.Add("system.data.dll"); // cp.ReferencedAssemblies.Add("system.windows.forms.dll"); // cp.ReferencedAssemblies.Add("system.drawing.dll"); //#if UNITY_EDITOR // cp.ReferencedAssemblies.Add(@"dll\UnityEngine.dll"); // cp.ReferencedAssemblies.Add(@"Assets\Plugins\GameLibrary.dll"); // cp.ReferencedAssemblies.Add(@"dll\UnityEngine.UI.dll"); // Debug.Log("Unity Editor"); //#endif //#if UNITY_STANDALONE // cp.ReferencedAssemblies.Add(@"BeginReality_Data\Managed\UnityEngine.dll"); // cp.ReferencedAssemblies.Add(@"BeginReality_Data\Managed\GameLibrary.dll"); // cp.ReferencedAssemblies.Add(@"BeginReality_Data\Managed\UnityEngine.UI.dll"); // Debug.Log("STANDALONE"); //#endif cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; cp.GenerateExecutable = false; var compiler = new CodeCompiler(); //CompilerResults cr = compiler.CompileAssemblyFromFileBatch(cp, filePaths.ToArray()); CompilerResults cr = compiler.CompileAssemblyFromSource(cp, code.ToString()); string errors = ""; if (cr.Errors.HasErrors) { foreach (CompilerError error in cr.Errors) { ConsoleReport.LogReport("Ocorreu um erro na linha " + (error.Line - 7).ToString() + " e coluna " + error.Column.ToString()); errors = errors + error.ErrorText + " linha: " + (error.Line - 7).ToString() + "\n"; } throw new Exception(errors); } //foreach (var err in result.Errors) { // manager.logWriter.WriteLine(err); //} this.assembly = cr.CompiledAssembly; object o = assembly.CreateInstance("CSCodeEvaler"); Type t = assembly.GetType("CSCodeEvaler"); if (t != null) { MethodInfo mi = t.GetMethod("EvalCode"); mi.Invoke(o, null); } }