public ObfuscationAttributeTests() { TestHelper.CleanInput(); Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = true; string assemblyAPath = Path.Combine(TestHelper.InputPath, "AssemblyA.dll"); cp.OutputAssembly = assemblyAPath; CompilerResults cr = provider.CompileAssemblyFromFile(cp, Path.Combine(TestHelper.InputPath, "AssemblyA.cs")); if (cr.Errors.Count > 0) { Assert.True(false, "Unable to compile test assembly: AssemblyA"); } cp.ReferencedAssemblies.Add(assemblyAPath); cp.OutputAssembly = Path.Combine(TestHelper.InputPath, "AssemblyB.dll"); cr = provider.CompileAssemblyFromFile(cp, Path.Combine(TestHelper.InputPath, "AssemblyB.cs")); if (cr.Errors.Count > 0) { Assert.True(false, "Unable to compile test assembly: AssemblyB"); } }
public static void BuildAssembly(string name, string suffix = null, string options = null, bool treatWarningsAsErrors = true) { Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = treatWarningsAsErrors; if (!string.IsNullOrEmpty(options)) { cp.CompilerOptions = options; } string dllName = string.IsNullOrEmpty(suffix) ? name : name + suffix; string fileName = GetAssemblyPath(dllName); if (File.Exists(fileName)) { return; } cp.OutputAssembly = fileName; CompilerResults cr = provider.CompileAssemblyFromFile(cp, Path.Combine(InputPath, name + ".cs")); if (cr.Errors.HasErrors) { Assert.True(false, "Unable to compile test assembly: " + dllName + ":" + cr.Errors[0].ErrorText); } }
public void sd() { // CodeDom已被Roslyn API取代。目前.net core平台不支持CodeDom string csPaths = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "temp_gen_grpc_code"); var dllFiles = Directory.GetFiles(csPaths, "*.cs"); string strDll = "GrpcSrvTemp.dll"; CodeDomProvider COD = new Microsoft.CSharp.CSharpCodeProvider(); COD = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters COM = new CompilerParameters { //生成DLL,True为生成exe文件,false为生成dll文件 GenerateExecutable = false, OutputAssembly = strDll, }; COM.ReferencedAssemblies.Add("mscorlib.dll"); COM.ReferencedAssemblies.Add("System.dll"); COM.ReferencedAssemblies.Add("System.Interactive.Async.dll"); COM.ReferencedAssemblies.Add(@"Google.Protobuf.dll"); COM.ReferencedAssemblies.Add(@"Grpc.Core.dll"); CompilerResults COMR = COD.CompileAssemblyFromFile(COM, dllFiles); //下面我们就可以根据生成的Dll反射为相关对象,供我们使用了. //Assembly a = Assembly.LoadFrom(strDll); //Type t = a.GetType("b"); //object obj = Activator.CreateInstance(t); //t.GetMethod("run").Invoke(obj, null); }
/// @brief Compiles in memory an assembly containing the plugin. /// @returns If successful, returns the assembly compiled, if not, returns null. public Assembly CompileToMemory() { CompilerParameters cp = new CompilerParameters( new[] { "System.Windows.Forms.dll", "System.dll", "System.Data.dll", "System.Drawing.dll", "System.Xml.dll" }, //references added by default _pluginData.AssemblyNameOnly, //name of the compiled assembly false); //false = no debug cp.ReferencedAssemblies.Add(System.Windows.Forms.Application.ExecutablePath); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.CompilerOptions = "/optimize"; cp.WarningLevel = 4; //to do not consider C00618 warning (obsolete PluginBaseV0_0 class) //cp.MainClass = "Gear.PluginSupport." + _pluginData.InstanceName; //traverse list adding not null nor empty texts foreach (string s in _pluginData.References) { if (!string.IsNullOrEmpty(s)) { cp.ReferencedAssemblies.Add(s); } } CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); //compile the assembly CompilerResults results = provider.CompileAssemblyFromFile(cp, _pluginData.Codes); //check if there are errors if (results.Errors.HasErrors | results.Errors.HasWarnings) { errorsCollection = results.Errors; return(null); } return(results.CompiledAssembly); }
private void Compile_Clicked(object sender, EventArgs e) { saveToolStripMenuItem_Click(sender, e); if ((DialogResult)saver.Tag == DialogResult.OK) { using (Microsoft.CSharp.CSharpCodeProvider compiler = new Microsoft.CSharp.CSharpCodeProvider()) { System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFile( new System.CodeDom.Compiler.CompilerParameters( Compiler.UsedAssemblies.Select(name => name.Location).ToArray(), saver.FileName.Substring(0, saver.FileName.LastIndexOf('\\') + 1) + "a.exe", true) { MainClass = "MyNamespace.Program", GenerateExecutable = true }, saver.FileNames ); if (results.Errors.Count > 0) { foreach (var error in results.Errors) { MessageBox.Show(error.ToString()); } } else { MessageBox.Show(results.PathToAssembly); } } } }
public static void BuildAssembly(string name, string suffix, string options) { Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider( ); CompilerParameters cp = new CompilerParameters( ); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = true; if (!String.IsNullOrEmpty(options)) { cp.CompilerOptions = options; } string dllName = String.IsNullOrEmpty(suffix) ? name : name + suffix; string assemblyPath = Path.Combine(InputPath, dllName + ".dll"); cp.OutputAssembly = assemblyPath; CompilerResults cr = provider.CompileAssemblyFromFile(cp, Path.Combine(InputPath, name + ".cs")); if (cr.Errors.HasErrors) { Assert.Fail("Unable to compile test assembly: " + dllName); } }
public static Assembly CompileExecutableFile(CompilerParameters cp, String[] filepaths) { CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerResults cr = provider.CompileAssemblyFromFile(cp, filepaths); return(processCompilationResult(cr)); }
internal static async Task Build(string sourceDir, string outputFile, Nuget.Repository repository) { string outputDir = Path.GetDirectoryName(outputFile); var sourceFiles = new DirectoryInfo(sourceDir).GetFiles("*.*", SearchOption.AllDirectories); var metaData = GetMetaData(sourceFiles); var nugetSources = metaData[nugetSourceKeyWord].Distinct() .Select(Nuget.GetSource) .ToList(); if (!nugetSources.Any()) { nugetSources = new List <Nuget.ISource> { Nuget.GetDefaultSource() }; } var nugetPackages = metaData[nugetPackageKeyWord].Distinct().ToList(); var installedNugetPackages = await repository.EnsurePackagesAreInstalled(nugetSources, nugetPackages); // compile var csharpProvider = new Microsoft.CSharp.CSharpCodeProvider(); var externalReferences = installedNugetPackages.SelectMany(_ => _.GetReferenceAssemblies()).ToArray(); foreach (var i in externalReferences) { Copy(i, Path.Combine(outputDir, Path.GetFileName(i))); } var internalReferences = new[] { "System.Runtime.dll", "System.dll", "System.Xml.dll", "Microsoft.CSharp.dll", "System.Core.dll", }; var options = new CompilerParameters() { OutputAssembly = outputFile, GenerateExecutable = true, IncludeDebugInformation = false, GenerateInMemory = false, MainClass = "Program", }; options.ReferencedAssemblies.AddRange(internalReferences.Concat(externalReferences).ToArray()); var results = csharpProvider.CompileAssemblyFromFile(options, sourceFiles.Where(Util.IsCSharpFile).Select(_ => _.FullName).ToArray()); if (results.Errors.Cast <object>().Any()) { var s = String.Join("\r\n", results.Errors.Cast <object>().ToArray()); throw new Exception(s); } }
/// <summary> /// loads the *.cs file and compile it, logs compilation result /// </summary> /// <param name="path">path to .cs file</param> public void LoadScript(string path) { System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromFile(this.par, new string[] { path }); Logging.Logger.AddImportant("kompilace skritpu, pocet chyb: " + results.Errors.Count.ToString()); if (results.Errors.Count > 0) { foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) { Logging.Logger.AddWarning("chyba ve skriptu " + err.ErrorNumber + " na radce " + err.Line + ": " + err.ErrorText); } } else { scriptAssembly = results.CompiledAssembly; try { CreateInstance(); } catch (Exception ex) { Logging.Logger.AddInfo("Chyba pri vytvareni instance scriptu " + path + " - " + ex.ToString()); } Logging.Logger.AddInfo("skript prelozen \n" + scriptAssembly.ToString()); } }
public bool execScript(string dirPath) { Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider(); // Setup default params for compiler CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerParams.ReferencedAssemblies.Add("NoxShared.dll"); // Compile C# script CompilerResults results = csharp.CompileAssemblyFromFile(compilerParams, Directory.GetFiles(dirPath, "*.cs")); // Error handling if (results.Errors.Count > 0) { foreach (CompilerError e in results.Errors) System.Diagnostics.Debug.WriteLine(String.Format("{0} {1}: {2}", e.FileName, e.Line, e.ErrorText)); return false; } // Save assembly in class variable scriptAssembly = results.CompiledAssembly; // Create Script Instance if (initScript()) { // Run Script return runScript(); } return false; }
public Assembly CreateAssembly(string filename, IList references) { compilerErrors = null; string extension = Path.GetExtension(filename); CodeDomProvider codeProvider = null; switch (extension) { case ".cs": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; case ".vb": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; default: throw new InvalidOperationException("Script files must have a .cs or .vb."); } CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); foreach (string reference in references) { if (!compilerParams.ReferencedAssemblies.Contains(reference)) { compilerParams.ReferencedAssemblies.Add(reference); } } CompilerResults results = codeProvider.CompileAssemblyFromFile(compilerParams, filename); if (results.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (CompilerError item in results.Errors) { sb.AppendFormat("{0} line:{1} {2}\r\n", item.FileName, item.Line, item.ErrorText); } compilerErrors = results.Errors; throw new Exception( "Compiler error(s)\r\n" + sb.ToString()); } Assembly createdAssembly = results.CompiledAssembly; return(createdAssembly); }
/// <summary> /// Generates an Assembly from a script filename /// </summary> /// <param name="filename">The filename of the script</param> /// <param name="references">Assembly references for the script</param> /// <returns>The generated assembly</returns> public Assembly CreateAssembly(string filename, IList references) { // ensure that compilerErrors is null compilerErrors = null; string extension = Path.GetExtension(filename); // Select the correct CodeDomProvider based on script file extension CodeDomProvider codeProvider = null; switch (extension) { case ".cs": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; case ".vb": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; default: throw new InvalidOperationException("Script files must have a .cs or .vb."); } // Set compiler parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); // Add custom references foreach (string reference in references) { if (!compilerParams.ReferencedAssemblies.Contains(reference)) { compilerParams.ReferencedAssemblies.Add(reference); } } // Do the compilation CompilerResults results = codeProvider.CompileAssemblyFromFile(compilerParams, filename); //Do we have any compiler errors if (results.Errors.Count > 0) { compilerErrors = results.Errors; throw new Exception( "Compiler error(s) encountered and saved to AssemblyFactory.CompilerErrors"); } Assembly createdAssembly = results.CompiledAssembly; return createdAssembly; }
public Assembly CreateAssembly(string filename, IList references) { compilerErrors = null; string extension = Path.GetExtension(filename); CodeDomProvider codeProvider = null; switch (extension) { case ".cs": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; case ".vb": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; default: throw new InvalidOperationException("Script files must have a .cs or .vb."); } CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); foreach (string reference in references) { if (!compilerParams.ReferencedAssemblies.Contains(reference)) { compilerParams.ReferencedAssemblies.Add(reference); } } CompilerResults results = codeProvider.CompileAssemblyFromFile(compilerParams, filename); if (results.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (CompilerError item in results.Errors) { sb.AppendFormat("{0} line:{1} {2}\r\n", item.FileName, item.Line, item.ErrorText); } compilerErrors = results.Errors; throw new Exception( "Compiler error(s)\r\n" + sb.ToString()); } Assembly createdAssembly = results.CompiledAssembly; return createdAssembly; }
public static object GenWrapper(object filename) { var tmpl = Path.Combine(ApplicationDirectory, "Executable.cs.template"); var fn = RequiresNotNull <string>(filename); using (var p = new Microsoft.CSharp.CSharpCodeProvider()) { var supportfn = filename + ".cs"; File.WriteAllText(supportfn, string.Format( @" namespace IronScheme {{ partial class ExecutableTemplate {{ const string PATH = @""{0}""; const string RESOURCE = @""{1}""; }} }}", ApplicationDirectory, fn)); var cp = new CompilerParameters { EmbeddedResources = { fn }, OutputAssembly = Path.GetFileNameWithoutExtension(fn) + ".exe", ReferencedAssemblies = { "System.dll", "System.Configuration.dll" }, GenerateExecutable = true, //IncludeDebugInformation = true }; Console.Write("compiling executable wrapper '{0}'.... ", cp.OutputAssembly); var results = p.CompileAssemblyFromFile(cp, tmpl, supportfn); if (results.Errors.Count > 0) { Console.WriteLine("failed."); foreach (var error in results.Errors) { Console.Error.WriteLine(error); } } else { Console.WriteLine("done."); Console.Write("generating config file .... "); File.WriteAllText(cp.OutputAssembly + ".config", string.Format( @"<?xml version=""1.0""?> <configuration> <appSettings> <add key=""IronScheme.Directory"" value=""{0}""/> </appSettings> </configuration>", ApplicationDirectory)); Console.WriteLine("done."); } File.Delete(supportfn); } return(Unspecified); }
internal static CompilerResults BuildAssembly(string fileName) { var csBuilder = new Microsoft.CSharp.CSharpCodeProvider(); var options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.IncludeDebugInformation = false; options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); return(csBuilder.CompileAssemblyFromFile(options, fileName)); }
/// <summary> /// Compiles the script from the specified pathname into an Assembly. /// </summary> /// <param name="scriptPathName">Script pathname.</param> /// <param name="dllPathName">Full pathname for output DLL.</param> /// <param name="report">Errors and warnings reported by the compiler.</param> /// <returns>Reference to script instance, or null on failure.</returns> private static Assembly CompileCode(string scriptPathName, string dllPathName, out FileLoadReport report) { report = new FileLoadReport(scriptPathName); // To get C#6 (and later) features, a NuGet package must be installed, and // some "black magic" must be invoked. // See https://stackoverflow.com/a/40311406/294248 and nearby answers. Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parms = new CompilerParameters(); // We want a DLL, not an EXE. parms.GenerateExecutable = false; // Save to disk so other AppDomain can load it. parms.GenerateInMemory = false; // Be vocal about warnings. parms.WarningLevel = 3; // Optimization is nice. parms.CompilerOptions = "/optimize"; // Output file name. Must be named appropriately so it can be found. parms.OutputAssembly = dllPathName; // Add dependencies. parms.ReferencedAssemblies.AddRange(sRefAssem); #if DEBUG // This creates a .pdb file, which allows breakpoints to work. parms.IncludeDebugInformation = true; #endif // Using the "from file" version has an advantage over the "from source" // version in that the debugger can find the source file, so things like // breakpoints work correctly. CompilerResults cr = csProvider.CompileAssemblyFromFile(parms, scriptPathName); CompilerErrorCollection cec = cr.Errors; foreach (CompilerError ce in cr.Errors) { report.Add(ce.Line, ce.Column, ce.IsWarning ? FileLoadItem.Type.Warning : FileLoadItem.Type.Error, ce.ErrorText); } if (cr.Errors.HasErrors) { return(null); } else { Debug.WriteLine("Compilation successful"); return(cr.CompiledAssembly); } }
public ObfuscationAttributeTests () { TestHelper.CleanInput (); Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider (); CompilerParameters cp = new CompilerParameters (); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = true; string assemblyAPath = Path.Combine (TestHelper.InputPath, "AssemblyA.dll"); cp.OutputAssembly = assemblyAPath; CompilerResults cr = provider.CompileAssemblyFromFile (cp, Path.Combine (TestHelper.InputPath, "AssemblyA.cs")); if (cr.Errors.Count > 0) Assert.True (false, "Unable to compile test assembly: AssemblyA"); cp.ReferencedAssemblies.Add (assemblyAPath); cp.OutputAssembly = Path.Combine (TestHelper.InputPath, "AssemblyB.dll"); cr = provider.CompileAssemblyFromFile (cp, Path.Combine (TestHelper.InputPath, "AssemblyB.cs")); if (cr.Errors.Count > 0) Assert.True (false, "Unable to compile test assembly: AssemblyB"); }
public static BasePlugin LoadSourcePlugin(string path) { var cp = new Microsoft.CSharp.CSharpCodeProvider(compilerOptions); var par = new System.CodeDom.Compiler.CompilerParameters(); par.GenerateExecutable = false; par.GenerateInMemory = true; par.IncludeDebugInformation = true; //par.CompilerOptions = "/optimize"; par.TreatWarningsAsErrors = false; var us = Assembly.GetExecutingAssembly(); par.ReferencedAssemblies.Add(us.Location); foreach (var asn in us.GetReferencedAssemblies()) { par.ReferencedAssemblies.Add(asn.Name); } var result = cp.CompileAssemblyFromFile(par, path); var errors = result.Errors; if (errors != null) { if (errors.HasErrors) { Tools.WriteLine("Failed to compile source plugin:"); } foreach (System.CodeDom.Compiler.CompilerError error in errors) { if (error.IsWarning) { Tools.WriteLine(error.ToString()); } else { Tools.WriteLine(error.ToString()); } } if (errors.HasErrors) { return(null); } } return(LoadPluginAssembly(result.CompiledAssembly)); }
private void Compile(int index, params string[] references) { CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); string file = (string)CodeFiles[index]; string asm = (string)AsmFiles[index]; CompilerParameters prms = new CompilerParameters(references, asm); CompilerResults results = provider.CompileAssemblyFromFile(prms, file); foreach (string output in results.Output) { Console.WriteLine(output); } Assert.IsFalse(results.Errors.HasErrors); }
private static Assembly CompileCode(string fileName) { // Create a code provider // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones) // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?) Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider(); // Setup our options CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net) options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best! // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows // thus they can only do the things you want them to. // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it) // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to // the "script" options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); // Compile our code CompilerResults result; result = csProvider.CompileAssemblyFromFile(options, fileName); if (result.Errors.HasErrors) { Console.WriteLine(result.ToString()); // TODO: report back to the user that the script has errored return(null); } if (result.Errors.HasWarnings) { // TODO: tell the user about the warnings, might want to prompt them if they want to continue // runnning the "script" } return(result.CompiledAssembly); }
public static void BuildAssembly(string name, string suffix = null, string options = null ) { Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider( ); CompilerParameters cp = new CompilerParameters( ); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = true; if ( !String.IsNullOrEmpty( options ) ) cp.CompilerOptions = options; string dllName = String.IsNullOrEmpty( suffix ) ? name : name + suffix; cp.OutputAssembly = GetAssemblyPath (dllName); CompilerResults cr = provider.CompileAssemblyFromFile( cp, Path.Combine( InputPath, name + ".cs" ) ); if ( cr.Errors.HasErrors ) { Assert.True(false, "Unable to compile test assembly: " + dllName); } }
public string Result(Form1 form1) { List <string> sourceFiles = new List <string>(); sourceFiles.Add(getObfuscateFilename()); sourceFiles.Add(getAssemblyFilename(form1)); sourceFiles.RemoveAll(s => s == "");//V122 // Invoke compilation. CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFiles.ToArray()); string result = ""; if (cr.Errors.Count > 0) { result = string.Format("Errors building {0}", cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { result += "\n" + ce.ToString(); } Console.WriteLine(result); } return(result); }
//------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Parse & compile a C# prime project. /// </summary> internal static Project Build( Parameters parameters ) { TempDirectory tempDirectory = new TempDirectory(); string[] intermediateSource = null; if (parameters.EnableCsPrime) { intermediateSource = CsPrimeParser.Parse( parameters.SourceFiles, /* sourceDebuggingSupport = */ true ); } ArrayList referencedAssemblies = new ArrayList(); // Add some implicit referenced assemblies. referencedAssemblies.Add(Path.Combine(parameters.ClrDir, "System.dll")); if (parameters.EnableCsPrime) { // Needed so that the project can access MS.Internal.Csp.CsPrimeRuntime. // (The parser generates references to it.) referencedAssemblies.Add(System.Windows.Forms.Application.ExecutablePath); } referencedAssemblies.AddRange(parameters.ReferencedAssemblies); CompilerParameters cp = new CompilerParameters( (string[])referencedAssemblies.ToArray(typeof(string)) ); cp.GenerateExecutable = true; cp.IncludeDebugInformation = true; // GenerateInMemory: // If true: Neither cordbg nor Rascal can find symbols. // If false: TempDirectory.Dispose throws an exception if it tries to // clear the directory, because the CLR still has the .exe file open. if (parameters.DebugModeHack) { cp.GenerateInMemory = false; tempDirectory.SetToLeak(); // Since cleanup seems impossible } else { cp.GenerateInMemory = true; } // In order to generate a .pdb that Rascal can use, OutputAssembly // must be set to something (i.e. not the default which creates a // temporary file). // // (Hence the futzing with TempDirectory). cp.OutputAssembly = Path.Combine(tempDirectory.PathName, "csp.project.exe"); if (parameters.MainClass != null) { cp.MainClass = parameters.MainClass; } Microsoft.CSharp.CSharpCodeProvider codeCompiler = new Microsoft.CSharp.CSharpCodeProvider(); CompilerResults results; if (parameters.EnableCsPrime) { results = codeCompiler.CompileAssemblyFromSource(cp, intermediateSource); } else { results = codeCompiler.CompileAssemblyFromFile(cp, parameters.SourceFiles); } if (results.Output.Count > 0) { Console.WriteLine("Output from compiler:"); foreach (String s in results.Output) { Console.WriteLine(s); } } if (results.Errors.Count > 0) { Console.WriteLine("Aborting."); return(null); } return(new Project( results.CompiledAssembly, tempDirectory, parameters.BreakBeforeInvoke )); }
private void CompilePluginsDirectory() { var compiler = new Microsoft.CSharp.CSharpCodeProvider(); var parms = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true }; parms.ReferencedAssemblies.Add("System.Core.dll"); parms.ReferencedAssemblies.Add("EQEmu.dll"); var files = Directory.GetFiles(".\\Plugins"); if (files.Count() > 0) { files = files.Where(x => x.Contains(".cs")).ToArray(); if (files.Count() > 0) { var results = compiler.CompileAssemblyFromFile(parms, files); if (results.Errors.HasErrors) { string errorMessage = "There were compilation errors from source files in the plugin directory:" + System.Environment.NewLine; ; foreach (var err in results.Errors) { errorMessage += err.ToString() + System.Environment.NewLine; } var window = new TextWindow(errorMessage); window.ShowDialog(); } else { //the get accessor loads the assembly into the appdomain var assembly = results.CompiledAssembly; } } } }
/// <summary> /// Compiles the module. /// </summary> /// <param name="codeTexts">The code texts.</param> /// <param name="module">The module.</param> /// <param name="references">The references.</param> /// <param name="objParams">The object parameters.</param> /// <param name="pluginSystemVersion">The plugin system version.</param> /// <returns></returns> static public PluginCommon CompileModule(string[] codeTexts, string module, string[] references, object objParams, string pluginSystemVersion) { string compiledName = AssemblyUtils.CompiledPluginName(module, pluginSystemVersion, string.Concat("-", AssemblyUtils.TimeStampForFile(DateTime.Now), ".dll")); //string compiledName = CompiledPluginName(module, pluginSystemVersion, // string.Concat("-", Path.GetRandomFileName().Substring(0, 8), ".dll")); CompilerParameters cp = new CompilerParameters(new[] { "System.Windows.Forms.dll", "System.dll", "System.Data.dll", "System.Drawing.dll", "System.Xml.dll" }, chachePath + compiledName, #if DEBUG true); #else false); #endif cp.TempFiles = new TempFileCollection(chachePath, false); //set directory cp.ReferencedAssemblies.Add(System.Windows.Forms.Application.ExecutablePath); cp.GenerateExecutable = false; cp.GenerateInMemory = false; cp.CompilerOptions = "/optimize"; cp.WarningLevel = 4; //to do not consider C00618 warning (obsolete PluginBaseV0_0 class) cp.MainClass = "Gear.PluginSupport." + module; //traverse list adding not null nor empty texts foreach (string s in references) { if (!string.IsNullOrEmpty(s)) { cp.ReferencedAssemblies.Add(s); } } CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); try { if (!Directory.Exists(chachePath)) { Directory.CreateDirectory(chachePath); } else { try { Directory.Delete(chachePath, true); Directory.CreateDirectory(chachePath); } catch (Exception e) { CompilerError c = new CompilerError(string.Empty, 0, 0, "Pre-build", e.Message); m_Errors = new CompilerErrorCollection(new CompilerError[] { c }); return(null); } } //write the codes to compile later string[] sourceFiles = new string[codeTexts.Length]; for (int i = 0; i < codeTexts.Length; i++) { sourceFiles[i] = string.Format(chachePath + "{0}-{1}.cs", AssemblyUtils.CompiledPluginName(module, pluginSystemVersion, string.Empty), i); File.WriteAllText(sourceFiles[i], codeTexts[i]); } AppDomainSetup adSetup = new AppDomainSetup(); adSetup.ApplicationBase = System.Environment.CurrentDirectory; adSetup.ApplicationName = "Plugin space App"; adSetup.ShadowCopyFiles = "true"; adSetup.CachePath = chachePath; AppDomain pluginDomain = AppDomain.CreateDomain("pluginDomain", null, adSetup); //compile the assembly CompilerResults results = provider.CompileAssemblyFromFile(cp, sourceFiles); if (results.Errors.HasErrors | results.Errors.HasWarnings) { m_Errors = results.Errors; return(null); } string compiledAssembly = results.CompiledAssembly.FullName; //PrintAssembliesLoaded(AppDomain.CurrentDomain, results.CompiledAssembly, true); //byte[] rawAssembly = loadFile(@".\cache\" + compiledName); //Assembly assemblyPlugin = pluginDomain.Load(rawAssembly, null); //PrintAssembliesLoaded(pluginDomain, assemblyPlugin, true); // TODO ASB: see links to help about running in a different AppDomain //http://stackoverflow.com/questions/5380246/loading-services-from-other-dll-and-run-them-isolated/5380317#5380317 //http://stackoverflow.com/questions/599731/use-the-serializable-attribute-or-subclassing-from-marshalbyrefobject //explore how to use MarshalByRefObject: http://www.softwareinteractions.com/blog/2010/2/7/loading-and-unloading-net-assemblies.html //http://stackoverflow.com/questions/1687245/use-appdomain-to-load-unload-external-assemblies object target = pluginDomain.CreateInstanceAndUnwrap( compiledAssembly, //string assemblyName module, //string typeName false, //bool ignoreCase BindingFlags.Public | BindingFlags.Instance, //BindingFlags bindingAttr null, //Binder binder (objParams != null) ? //object[] args new object[] { objParams } : null, null, //CultureInfo culture null); //object[] activationAttributes PrintAssembliesLoaded(pluginDomain, results.CompiledAssembly, false); if (target == null) { CompilerError c = new CompilerError(string.Empty, 0, 0, "CS0103", "The name '" + module + "' does not exist in the current context." + " Does the class name is the same that is declared in c# code?"); m_Errors = new CompilerErrorCollection(new CompilerError[] { c }); return(null); } else if (!PluginSystem.InstanceOneOfValidClasses(target)) { CompilerError c = new CompilerError(string.Empty, 0, 0, "CS0029", "Cannot implicitly convert type '" + target.GetType().FullName + "' to '" + PluginSystem.GetPluginBaseType(pluginSystemVersion).FullName + "'"); m_Errors = new CompilerErrorCollection(new CompilerError[] { c }); return(null); } m_Errors = null; return((PluginCommon)target); } catch (Exception e) { CompilerError c = new CompilerError(string.Empty, 0, 0, "Runtime", string.Format("Plugin '{0}' - {1}", module, e.Message)); m_Errors = new CompilerErrorCollection(new CompilerError[] { c }); return(null); } }
private IAssemblyInfo Build(IBuilderContext builderContext, string libraryFile, params string[] sources) { var assemblyInfo = LoadAssemblyInfo(builderContext, sources); HashSet <string> references = new HashSet <string>(); Dictionary <string, string> providerOptions = new Dictionary <string, string>(); providerOptions.Add("CompilerVersion", "v4.0"); CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions); CompilerParameters cp = new CompilerParameters(); if (UseDefaultReferences) { foreach (string defaultReference in DefaultReferences) { references.Add(GetAssemblyDllPath(defaultReference)); } } foreach (string assemblyFile in _references) { references.Add(assemblyFile); } foreach (Assembly assembly in _assemblies) { if (!assembly.IsDynamic) { references.Add(assembly.Location); } } cp.ReferencedAssemblies.AddRange(references.ToArray()); // Generate an library cp.GenerateExecutable = false; // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 4; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. // TODO : figure out why it does not work when uncommenting the following line // cp.CompilerOptions = "/optimize"; // Specify the assembly file name to generate if (libraryFile == null) { cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; } else { cp.GenerateInMemory = false; cp.IncludeDebugInformation = true; cp.OutputAssembly = libraryFile; } // Notes: // Avoid getting spoiled by environment variables. // C# will give compilation errors if a LIB variable contains non-existing directories. Environment.SetEnvironmentVariable("LIB", null); // Invoke compilation of the source file. CompilerResults cr = provider.CompileAssemblyFromFile(cp, assemblyInfo.SourceFiles.ToArray()); if (cr.Errors.HasErrors || cr.Errors.HasWarnings) { string errorMessage = ""; foreach (CompilerError ce in cr.Errors) { if (ce.IsWarning) { EventOutputWarning?.Invoke(ce + Environment.NewLine); } else { EventOutputError?.Invoke(ce + Environment.NewLine); } errorMessage += ce + Environment.NewLine; } if (cr.Errors.HasErrors) { if (builderContext.CompileErrorBehavior == BuilderCompileErrorBehavior.ThrowException) { throw new Error(errorMessage); } return(assemblyInfo); } } assemblyInfo.Assembly = cr.CompiledAssembly; assemblyInfo.Id = assemblyInfo.Assembly.Location; return(assemblyInfo); }
public static Assembly compilePlugin(string pluginFilePath) { CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateInMemory = true; compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("KARAS.dll"); CompilerResults compilerResults; compilerResults = codeDomProvider.CompileAssemblyFromFile (compilerParameters, pluginFilePath); if (compilerResults.Errors.Count > 0) { string compileErrorText = "Failed to compile script :\"" + pluginFilePath + "\"\n"; foreach (CompilerError compilerError in compilerResults.Errors) compileErrorText += compilerError + "\n"; throw new ApplicationException(compileErrorText); } return compilerResults.CompiledAssembly; }
private bool CompileScripts( ) { if( _assets.ScriptItems.Count != 0 ) { string folder = Path.Combine( Global.World.BuildFolderPath, "Content" ); if( !Directory.Exists( folder ) ) Directory.CreateDirectory( folder ); string[] scripts = new string[_assets.ScriptItems.Count]; int i = 0; foreach( ScriptAssetItem scriptItem in _assets.ScriptItems.Values ) { scripts[i] = scriptItem.FilePath; i++; } string dllPath = Path.Combine( folder, "scripts.dll" ); Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider( ); System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters( ); parameters.GenerateExecutable = false; parameters.OutputAssembly = dllPath; parameters.ReferencedAssemblies.Add( "mscorlib.dll" ); parameters.ReferencedAssemblies.Add( "LunarEngine.dll" ); parameters.ReferencedAssemblies.Add( "Farseer Physics 3.0.dll" ); parameters.ReferencedAssemblies.Add( Assembly.GetAssembly( typeof( Microsoft.Xna.Framework.Input.Keys ) ).Location ); parameters.ReferencedAssemblies.Add( Assembly.GetAssembly( typeof( Microsoft.Xna.Framework.Game ) ).Location ); if( File.Exists( Global.World.PluginsFilePath ) ) { using( StreamReader file = new StreamReader( File.OpenRead( Global.World.PluginsFilePath ) ) ) { while( !file.EndOfStream ) { string path = Path.Combine( Global.World.WorldFolderPath, file.ReadLine( ) ); if( File.Exists( path ) ) parameters.ReferencedAssemblies.Add( path ); else { MessageBox.Show( Path.GetFileName( path ) + " plugin is missing!" ); return false; } } } } System.CodeDom.Compiler.CompilerResults results = codeProvider.CompileAssemblyFromFile( parameters, scripts ); _scriptEditor.DisplayErrors( results.Errors ); if( results.Errors.HasErrors || results.Errors.HasWarnings ) { _scriptEditor.FocusErrorsDock( ); if( results.Errors.HasErrors ) return false; } } _compiledScripts = true; _itemBuildScripts.Enabled = false; return true; }
/// <summary> /// Builds the assembly. /// </summary> /// <remarks>Throws an exception in case of any errors.</remarks> /// <returns>The created and loaded assembly.</returns> public Assembly Build() { Dictionary <string, string> providerOptions = new Dictionary <string, string>(); providerOptions.Add("CompilerVersion", "v4.0"); CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions); // Collect references HashSet <string> references = new HashSet <string>(); foreach (var defaultReference in DefaultReferences) { references.Add(defaultReference.Location); } foreach (var assemblyFile in References) { references.Add(assemblyFile); } foreach (var assembly in Assemblies) { if (!assembly.IsDynamic) { references.Add(assembly.Location); } } // Setup compilation options CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.WarningLevel = 4; cp.TreatWarningsAsErrors = false; cp.ReferencedAssemblies.AddRange(references.ToArray()); if (string.IsNullOrEmpty(OutputPath)) { cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; } else { cp.GenerateInMemory = false; cp.IncludeDebugInformation = true; cp.OutputAssembly = OutputPath; } // HACK: C# will give compilation errors if a LIB variable contains non-existing directories Environment.SetEnvironmentVariable("LIB", null); // Run the compilation CompilerResults cr = provider.CompileAssemblyFromFile(cp, SourceFiles.ToArray()); // Process warnings if (cr.Errors.HasWarnings) { foreach (CompilerError ce in cr.Errors) { if (ce.IsWarning) { Log.Warning(string.Format("{0} at {1}: {2}", ce.FileName, ce.Line, ce.ErrorText)); } } } // Process errors if (cr.Errors.HasErrors) { foreach (CompilerError ce in cr.Errors) { if (!ce.IsWarning) { Log.Error(string.Format("{0} at line {1}: {2}", ce.FileName, ce.Line, ce.ErrorText)); } } throw new Exception("Failed to build assembly."); } return(cr.CompiledAssembly); }
private IAssemblyInfo Build(IBuilderContext builderContext, string libraryFile, params string[] sources) { var assemblyInfo = LoadAssemblyInfo(builderContext, sources); HashSet <string> references = new HashSet <string>(); Dictionary <string, string> providerOptions = new Dictionary <string, string>(); providerOptions.Add("CompilerVersion", "v4.0"); CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions); CompilerParameters cp = new CompilerParameters(); if (UseDefaultReferences) { foreach (string defaultReference in DefaultReferences) { references.Add(GetAssemblyDllPath(defaultReference)); } } foreach (string assemblyFile in _references) { references.Add(assemblyFile); } foreach (Assembly assembly in _assemblies) { if (!assembly.IsDynamic) { references.Add(assembly.Location); } } cp.ReferencedAssemblies.AddRange(references.ToArray()); // Generate an library cp.GenerateExecutable = false; // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 4; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. // TODO : figure out why it does not work when uncommenting the following line // cp.CompilerOptions = "/optimize"; // If any defines are specified, pass them to the CSC. if (_defines.Any()) { cp.CompilerOptions = "-DEFINE:" + string.Join(",", _defines); } // Specify the assembly file name to generate if (libraryFile == null) { cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; } else { cp.GenerateInMemory = false; cp.IncludeDebugInformation = true; cp.OutputAssembly = libraryFile; } // Notes: // Avoid getting spoiled by environment variables. // C# will give compilation errors if a LIB variable contains non-existing directories. Environment.SetEnvironmentVariable("LIB", null); // Configure Temp file collection to avoid deleting its temp file. We will delete them ourselves after the compilation // For some reasons, this seems to add just enough delays to avoid the following first chance exception(probably caused by some handles in csc.exe) // System.IO.IOException: 'The process cannot access the file 'C:\Users\xxx\AppData\Local\Temp\sa205152\sa205152.out' because it is being used by another process.' // That exception wasn't causing real problems but was really annoying when debugging! // Executed several times sharpmake and this first chance exception no longer occurs when KeepFiles is true. cp.TempFiles.KeepFiles = true; // Invoke compilation of the source file. CompilerResults cr = provider.CompileAssemblyFromFile(cp, assemblyInfo.SourceFiles.ToArray()); // Manually delete the files in the temp files collection. cp.TempFiles.Delete(); if (cr.Errors.HasErrors || cr.Errors.HasWarnings) { string errorMessage = ""; foreach (CompilerError ce in cr.Errors) { if (ce.IsWarning) { EventOutputWarning?.Invoke("{0}" + Environment.NewLine, ce.ToString()); } else { EventOutputError?.Invoke("{0}" + Environment.NewLine, ce.ToString()); } errorMessage += ce + Environment.NewLine; } if (cr.Errors.HasErrors) { if (builderContext == null || builderContext.CompileErrorBehavior == BuilderCompileErrorBehavior.ThrowException) { throw new Error(errorMessage); } return(assemblyInfo); } } assemblyInfo.Assembly = cr.CompiledAssembly; assemblyInfo.Id = assemblyInfo.Assembly.Location; return(assemblyInfo); }
System.Reflection.Assembly _CompileSource(string Input, bool InputIsFile, bool exe, string outputname) { string[] asmrefs = new string[AssemblyReferences.Count]; List<string> assemblydirs = new List<string>(); char[] slashes = new char[] { '/', '\\' }; for (int i = 0; i < asmrefs.Length; i++) { string ar = AssemblyReferences[i]; int ils = ar.LastIndexOfAny(slashes); if (-1 != ils) { assemblydirs.Add(ar.Substring(0, ils)); ar = ar.Substring(ils + 1); } asmrefs[i] = ar; } StringBuilder localcompileropts = new StringBuilder(); { for (int i = 0; i < assemblydirs.Count; i++) { localcompileropts.Append(" /lib:\"" + assemblydirs[i] + "\""); } } System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters(asmrefs); cp.IncludeDebugInformation = _compilerdbg; System.CodeDom.Compiler.CompilerResults cr = null; bool alreadylogged = false; string reason = ""; for (int rotor = 1; ; rotor++) { #if DEBUG if (rotor > 3) { throw new System.IO.FileNotFoundException("ArrayComboList.CompileSource dynamic C# compilation: Unable to create DLL" + reason); } #endif try { cp.OutputAssembly = outputname; cp.GenerateExecutable = exe; cp.GenerateInMemory = false; cp.CompilerOptions = getcompileropts() + localcompileropts.ToString(); { System.Threading.Mutex mdc = new System.Threading.Mutex(false, "DynCmp"); try { mdc.WaitOne(); } catch (System.Threading.AbandonedMutexException) { } try { Dictionary<string, string> providerOptions = new Dictionary<string, string>(); providerOptions["CompilerVersion"] = "v3.5"; using (Microsoft.CSharp.CSharpCodeProvider cscp = new Microsoft.CSharp.CSharpCodeProvider(providerOptions)) { if (InputIsFile) { cr = cscp.CompileAssemblyFromFile(cp, Input); } else { cr = cscp.CompileAssemblyFromSource(cp, Input); } } } finally { mdc.ReleaseMutex(); mdc.Close(); } } if (cr.Errors.HasErrors) { try { lock (typeof(Compiler)) { if (InputIsFile) { System.IO.File.Copy(Input, "error.cs", true); // overwrite=true } else { System.IO.File.WriteAllText("error.cs", Input); } } } catch { } for (int i = 0; i < cr.Errors.Count; i++) { if (!cr.Errors[i].IsWarning) { throw new Exception("CompileSource code compile error: " + cr.Errors[i].ToString()); } } throw new Exception("CompileSource code compile error: " + cr.Errors[0].ToString()); } if (0 != cr.NativeCompilerReturnValue) { //LogLine("CompileSource code compile did not return 0 (returned " + cr.NativeCompilerReturnValue.ToString() + "): "); for (int i = 0; i < cr.Output.Count; i++) { string ss = cr.Output[i].Trim(); if (0 != ss.Length) { //LogLine(" C" + rotor.ToString() + "- " + cr.Output[i]); } } } #if DEBUG if (rotor > 1) { System.Threading.Thread.Sleep(1000 * (rotor - 1)); } #else System.Threading.Thread.Sleep(1000 * rotor); #endif break; // Good. } catch (System.IO.IOException e) { if (!alreadylogged) { alreadylogged = true; //LogLine("Rotor retry: " + e.ToString()); } reason = ": " + e.ToString(); continue; } } return cr.CompiledAssembly; }
public Assembly compileSourceCode_Sync(string sourceCode) { if (sourceCode.notValid()) { return(null); } try { Environment.CurrentDirectory = PublicDI.config.CurrentExecutableDirectory; CompiledAssembly = null; beforeCompile.invoke(); DebugMode.ifInfo("Compiling Source Code (Size: {0})", sourceCode.size()); SourceCode = sourceCode; if (sourceCode.lines().starting("//CLR_3.5").notEmpty()) // allow setting compilation into 2.0 CLR { CompilationVersion = "v3.5"; } var providerOptions = new Dictionary <string, string>().add("CompilerVersion", CompilationVersion); var csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions); var compilerParams = new CompilerParameters(); compilerParams.OutputAssembly = "_o2_Script.dll".tempFile(); compilerParams.IncludeDebugInformation = generateDebugSymbols; compilerParams.GenerateInMemory = !generateDebugSymbols; foreach (var referencedAssembly in ReferencedAssemblies) { compilerParams.ReferencedAssemblies.Add(referencedAssembly); } CompilerResults = (generateDebugSymbols) ? csharpCodeProvider.CompileAssemblyFromFile(compilerParams, sourceCode.saveWithExtension(".cs")) : csharpCodeProvider.CompileAssemblyFromSource(compilerParams, sourceCode); if (CompilerResults.Errors.Count > 0 || CompilerResults.CompiledAssembly == null) { CompilationErrors = ""; foreach (CompilerError error in CompilerResults.Errors) { //CompilationErrors.Add(CompilationErrors.line(error.ToString()); var errorMessage = String.Format("{0}::{1}::{2}::{3}::{4}", error.Line, error.Column, error.ErrorNumber, error.ErrorText, error.FileName); CompilationErrors = CompilationErrors.line(errorMessage); "[CSharp_FastCompiler] Compilation Error: {0}".error(errorMessage); } DebugMode.ifError("Compilation failed"); onCompileFail.invoke(); } else { CompiledAssembly = CompilerResults.CompiledAssembly; if (CompiledAssembly.Location.fileExists()) { CompileEngine.setCachedCompiledAssembly_toMD5(sourceCode, CompiledAssembly); } DebugMode.ifDebug("Compilation was OK"); onCompileOK.invoke(); } return(CompiledAssembly); } catch (Exception ex) { ex.log("[compileSourceCode_Sync"); return(null); } }
/// <summary> /// On error: Throw exception. /// </summary> private static void CompileScript(string scriptPath, string assemblyPath) { using (CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider()) { string[] assemblyNames = new string[]{ "mscorlib.dll", "System.dll", "System.Data.dll", "System.Drawing.dll", "System.Xml.dll", "System.Core.dll", "System.Windows.Forms.dll", Path.Combine(Lib.AppDir, "NoConsoleLib.dll") }; CompilerParameters compilerParameters = new CompilerParameters(assemblyNames) { OutputAssembly = assemblyPath, GenerateExecutable = false, GenerateInMemory = false, WarningLevel = 3, CompilerOptions = "/optimize", IncludeDebugInformation = COMPILED_SCRIPT_INCLUDE_DEBUG_INFORMATION, //TempFiles = new TempFileCollection(".", true) }; CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromFile( compilerParameters, new string[] { scriptPath }); /* This prints low-level messages like this, as well as error messages: * * G:\tmp\CsCompilerTest\WorkingDir> "C:\Windows\Microsoft.NET\Framework\v4.0.30319 * \csc.exe" /t:library /utf8output /out:"C:\Users\Adam Sawicki\AppData\Local\Temp\ * 0pdzupen.dll" /debug- /optimize+ /w:3 /optimize "C:\Users\Adam Sawicki\AppData\ * Local\Temp\0pdzupen.0.cs" * Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 * Copyright (C) Microsoft Corporation. All rights reserved. */ //foreach (String message in compilerResults.Output) // Console.WriteLine(message); /* This prints error messages in form of: * * c:\Users\Adam Sawicki\AppData\Local\Temp\4kbqoyz2.0.cs(7,9) : error CS0103: The * name 'Console' does not exist in the current context */ //foreach (CompilerError error in compilerResults.Errors) // Console.WriteLine(error.ToString()); if (compilerResults.NativeCompilerReturnValue != 0) { StringBuilder sb = new StringBuilder("Compilation failed.\n"); foreach (CompilerError error in compilerResults.Errors) sb.AppendLine(error.ToString()); throw new Exception(sb.ToString()); } } }
private void WriteProject(SolutionNode solution, ProjectNode project) { string solutionDir = Path.Combine(solution.FullPath, Path.Combine("autotools", solution.Name)); string projectDir = Path.Combine(solutionDir, project.Name); string projectVersion = project.Version; bool hasAssemblyConfig = false; chkMkDir(projectDir); ArrayList compiledFiles = new ArrayList(), contentFiles = new ArrayList(), embeddedFiles = new ArrayList(), binaryLibs = new ArrayList(), pkgLibs = new ArrayList(), systemLibs = new ArrayList(), runtimeLibs = new ArrayList(), extraDistFiles = new ArrayList(), localCopyTargets = new ArrayList(); // If there exists a .config file for this assembly, copy it to the project folder // TODO: Support copying .config.osx files // TODO: support processing the .config file for native library deps string projectAssemblyName = project.Name; if(project.AssemblyName != null) projectAssemblyName = project.AssemblyName; if(File.Exists(Path.Combine(project.FullPath, projectAssemblyName) + ".dll.config")){ hasAssemblyConfig = true; System.IO.File.Copy(Path.Combine(project.FullPath, projectAssemblyName + ".dll.config"), Path.Combine(projectDir, projectAssemblyName + ".dll.config"), true); extraDistFiles.Add(project.AssemblyName + ".dll.config"); } foreach(ConfigurationNode conf in project.Configurations) { if(conf.Options.KeyFile != string.Empty){ // Copy snk file into the project's directory // Use the snk from the project directory directly string source = Path.Combine(project.FullPath, conf.Options.KeyFile); string keyFile = conf.Options.KeyFile; Regex re = new Regex(".*/"); keyFile = re.Replace(keyFile, ""); string dest = Path.Combine(projectDir, keyFile); // Tell the user if there's a problem copying the file try{ mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); }catch(System.IO.IOException e){ Console.WriteLine(e.Message); } } } // Copy compiled, embedded and content files into the project's directory foreach(string filename in project.Files) { string source = Path.Combine(project.FullPath, filename); string dest = Path.Combine(projectDir, filename); if(filename.Contains("AssemblyInfo.cs")){ // If we've got an AssemblyInfo.cs, pull the version number from it string[] sources = { source }; string[] args = { "" }; Microsoft.CSharp.CSharpCodeProvider cscp = new Microsoft.CSharp.CSharpCodeProvider(); string tempAssemblyFile = Path.Combine(Path.GetTempPath(), project.Name + "-temp.dll"); System.CodeDom.Compiler.CompilerParameters cparam = new System.CodeDom.Compiler.CompilerParameters (args, tempAssemblyFile); System.CodeDom.Compiler.CompilerResults cr = cscp.CompileAssemblyFromFile(cparam, sources); foreach(System.CodeDom.Compiler.CompilerError error in cr.Errors) Console.WriteLine("Error! '{0}'", error.ErrorText); string projectFullName = cr.CompiledAssembly.FullName; Regex verRegex = new Regex("Version=([\\d\\.]+)"); Match verMatch = verRegex.Match(projectFullName); if(verMatch.Success) projectVersion = verMatch.Groups[1].Value; // Clean up the temp file if(File.Exists(tempAssemblyFile)) File.Delete(tempAssemblyFile); } // Tell the user if there's a problem copying the file try{ mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); }catch(System.IO.IOException e){ Console.WriteLine(e.Message); } switch(project.Files.GetBuildAction(filename)) { case BuildAction.Compile: compiledFiles.Add(filename); break; case BuildAction.Content: contentFiles.Add(filename); extraDistFiles.Add(filename); break; case BuildAction.EmbeddedResource: embeddedFiles.Add(filename); extraDistFiles.Add(filename); break; } } // Set up references for(int refNum = 0; refNum < project.References.Count; refNum++) { ReferenceNode refr = (ReferenceNode)project.References[refNum]; Assembly refAssembly = Assembly.LoadWithPartialName(refr.Name); // Determine which pkg-config (.pc) file refers to this assembly string assemblyFullName = string.Empty; if(refAssembly != null) assemblyFullName = refAssembly.FullName; string assemblyFileName = string.Empty; if(assemblyFullName != string.Empty && assemblyFullNameToPath.Contains(assemblyFileName)) assemblyFileName = (string)assemblyFullNameToPath[assemblyFullName]; SystemPackage package = null; if(assemblyFileName != string.Empty && assemblyPathToPackage.Contains(assemblyFileName)) package = (SystemPackage)assemblyPathToPackage[assemblyFileName]; // If we know the .pc file and it is not "mono" (already in the path), add a -pkg: argument if(package != null && package.Name != "mono" && !pkgLibs.Contains(package.Name)) pkgLibs.Add(package.Name); string fileRef = FindFileReference(refr.Name, (ProjectNode)refr.Parent); if(refr.LocalCopy || solution.ProjectsTable.ContainsKey(refr.Name) || fileRef != null || refr.Path != null ){ // Attempt to copy the referenced lib to the project's directory string filename = refr.Name + ".dll"; string source = filename; if(refr.Path != null) source = Path.Combine(refr.Path, source); source = Path.Combine(project.FullPath, source); string dest = Path.Combine(projectDir, filename); /* Since we depend on this binary dll to build, we will add a compile- * time dependency on the copied dll, and add the dll to the list of files * distributed with this package */ binaryLibs.Add(refr.Name + ".dll"); extraDistFiles.Add(refr.Name + ".dll"); // TODO: Support copying .config.osx files // TODO: Support for determining native dependencies if(File.Exists(source + ".config")){ System.IO.File.Copy(source + ".config", Path.GetDirectoryName(dest), true); extraDistFiles.Add(refr.Name + ".dll.config"); } try { System.IO.File.Copy(source, dest, true); }catch(System.IO.IOException){ /* If a file is referenced and marked for local copy, but does not exist, * let's assume it will be built some time between now and when this * project is built. * * We put a hook into the Makefile.am to copy the dll to this project's * directory */ ProjectNode sourcePrj = ((ProjectNode)(solution.ProjectsTable[refr.Name])); string target = filename + ":\n\tcp ../" + Path.Combine(sourcePrj.Name, filename) + " $@\n"; if(solution.ProjectsTable.ContainsKey(refr.Name)) localCopyTargets.Add(target); } }else{ // Else, let's assume it's in the GAC or the lib path string assemName = string.Empty; int index = refr.Name.IndexOf(","); if ( index > 0) assemName = refr.Name.Substring(0, index); else assemName = refr.Name; systemLibs.Add(assemName); } } string lineSep = " \\\n\t"; string compiledFilesString = string.Empty; if(compiledFiles.Count > 0) compiledFilesString = lineSep + string.Join(lineSep, (string[])compiledFiles.ToArray(typeof(string))); string embeddedFilesString = ""; if(embeddedFiles.Count > 0) embeddedFilesString = lineSep + string.Join(lineSep, (string[])embeddedFiles.ToArray(typeof(string))); string contentFilesString = ""; if(contentFiles.Count > 0) contentFilesString = lineSep + string.Join(lineSep, (string[])contentFiles.ToArray(typeof(string))); string extraDistFilesString = ""; if(extraDistFiles.Count > 0) extraDistFilesString = lineSep + string.Join(lineSep, (string[])extraDistFiles.ToArray(typeof(string))); string pkgLibsString = ""; if(pkgLibs.Count > 0) pkgLibsString = lineSep + string.Join(lineSep, (string[])pkgLibs.ToArray(typeof(string))); string binaryLibsString = ""; if(binaryLibs.Count > 0) binaryLibsString = lineSep + string.Join(lineSep, (string[])binaryLibs.ToArray(typeof(string))); string systemLibsString = ""; if(systemLibs.Count > 0) systemLibsString = lineSep + string.Join(lineSep, (string[])systemLibs.ToArray(typeof(string))); string localCopyTargetsString = ""; if(localCopyTargets.Count > 0) localCopyTargetsString = string.Join("\n", (string[])localCopyTargets.ToArray(typeof(string))); string monoPath = ""; foreach( string runtimeLib in runtimeLibs ){ monoPath += ":`pkg-config --variable=libdir " + runtimeLib + "`"; } // Add the project name to the list of transformation // parameters XsltArgumentList argList = new XsltArgumentList(); argList.AddParam("projectName", "", project.Name); argList.AddParam("solutionName", "", solution.Name); argList.AddParam("assemblyName", "", projectAssemblyName); argList.AddParam("compiledFiles", "", compiledFilesString); argList.AddParam("embeddedFiles", "", embeddedFilesString); argList.AddParam("contentFiles", "", contentFilesString); argList.AddParam("extraDistFiles", "", extraDistFilesString); argList.AddParam("pkgLibs", "", pkgLibsString); argList.AddParam("binaryLibs", "", binaryLibsString); argList.AddParam("systemLibs", "", systemLibsString); argList.AddParam("monoPath", "", monoPath); argList.AddParam("localCopyTargets", "", localCopyTargetsString); argList.AddParam("projectVersion", "", projectVersion); argList.AddParam("hasAssemblyConfig", "", hasAssemblyConfig ? "true" : ""); // Transform the templates transformToFile(Path.Combine(projectDir, "configure.ac"), argList, "/Autotools/ProjectConfigureAc"); transformToFile(Path.Combine(projectDir, "Makefile.am"), argList, "/Autotools/ProjectMakefileAm"); transformToFile(Path.Combine(projectDir, "autogen.sh"), argList, "/Autotools/ProjectAutogenSh"); if(project.Type == Core.Nodes.ProjectType.Library) transformToFile(Path.Combine(projectDir, project.Name + ".pc.in"),argList,"/Autotools/ProjectPcIn"); if(project.Type == Core.Nodes.ProjectType.Exe || project.Type == Core.Nodes.ProjectType.WinExe) transformToFile(Path.Combine(projectDir, project.Name.ToLower() + ".in"),argList,"/Autotools/ProjectWrapperScriptIn"); // Create stubs for NEWS, README, ChangeLog // These are required by automake ArrayList automakeFiles = new ArrayList(); automakeFiles.Add( "NEWS" ); automakeFiles.Add( "README" ); automakeFiles.Add( "ChangeLog" ); mkStubFiles(projectDir, automakeFiles); // Populate the AUTHORS file from the list of authors // This is also required by automake FileStream authorsFileStream = new FileStream(Path.Combine(projectDir, "AUTHORS"),FileMode.Create); StreamWriter authorsWriter = new StreamWriter(authorsFileStream); foreach(AuthorNode author in project.Authors) authorsWriter.WriteLine(author.Signature); authorsWriter.Flush(); authorsFileStream.Close(); }
CompilePackageAssembly( bool enforceBamAssemblyVersions = true, bool enableClean = true) { // validate build root if (null == Graph.Instance.BuildRoot) { throw new Exception("Build root has not been specified"); } var gatherSourceProfile = new TimeProfile(ETimingProfiles.GatherSource); gatherSourceProfile.StartProfile(); IdentifyAllPackages(enforceBamAssemblyVersions: enforceBamAssemblyVersions); var cleanFirst = CommandLineProcessor.Evaluate(new Options.CleanFirst()); if (enableClean && cleanFirst && System.IO.Directory.Exists(Graph.Instance.BuildRoot)) { Log.Info("Deleting build root '{0}'", Graph.Instance.BuildRoot); try { // make sure no files are read-only, which may have happened as part of collation preserving file attributes var dirInfo = new System.IO.DirectoryInfo(Graph.Instance.BuildRoot); foreach (var file in dirInfo.EnumerateFiles("*", System.IO.SearchOption.AllDirectories)) { file.Attributes &= ~System.IO.FileAttributes.ReadOnly; } System.IO.Directory.Delete(Graph.Instance.BuildRoot, true); } catch (System.IO.IOException ex) { Log.Info("Failed to delete build root, because {0}. Continuing", ex.Message); } } BuildModeUtilities.ValidateBuildModePackage(); var definitions = new StringArray(); // gather source files var sourceCode = new StringArray(); int packageIndex = 0; foreach (var package in Graph.Instance.Packages) { Log.DebugMessage("{0}: '{1}' @ '{2}'", packageIndex, package.Version, (package.PackageRepositories.Count > 0) ? package.PackageRepositories[0] : "Not in a repository"); // to compile with debug information, you must compile the files // to compile without, we need to file contents to hash the source if (Graph.Instance.CompileWithDebugSymbols) { var scripts = package.GetScriptFiles(); sourceCode.AddRange(scripts); Log.DebugMessage(scripts.ToString("\n\t")); } else { foreach (var scriptFile in package.GetScriptFiles()) { using (var reader = new System.IO.StreamReader(scriptFile)) { sourceCode.Add(reader.ReadToEnd()); } Log.DebugMessage("\t'{0}'", scriptFile); } } foreach (var define in package.Definitions) { if (!definitions.Contains(define)) { definitions.Add(define); } } ++packageIndex; } // add/remove other definitions definitions.Add(VersionDefineForCompiler); definitions.Add(HostPlatformDefineForCompiler); definitions.Sort(); gatherSourceProfile.StopProfile(); var assemblyCompileProfile = new TimeProfile(ETimingProfiles.AssemblyCompilation); assemblyCompileProfile.StartProfile(); // assembly is written to the build root var cachedAssemblyPathname = System.IO.Path.Combine(Graph.Instance.BuildRoot, ".CachedPackageAssembly"); cachedAssemblyPathname = System.IO.Path.Combine(cachedAssemblyPathname, Graph.Instance.MasterPackage.Name) + ".dll"; var hashPathName = System.IO.Path.ChangeExtension(cachedAssemblyPathname, "hash"); string thisHashCode = null; var cacheAssembly = !CommandLineProcessor.Evaluate(new Options.DisableCacheAssembly()); string compileReason = null; if (Graph.Instance.CompileWithDebugSymbols) { compileReason = "debug symbols were enabled"; } else { // can an existing assembly be reused? thisHashCode = GetPackageHash(sourceCode, definitions, Graph.Instance.MasterPackage.BamAssemblies); if (cacheAssembly) { if (System.IO.File.Exists(hashPathName)) { using (var reader = new System.IO.StreamReader(hashPathName)) { var diskHashCode = reader.ReadLine(); if (diskHashCode.Equals(thisHashCode)) { Log.DebugMessage("Cached assembly used '{0}', with hash {1}", cachedAssemblyPathname, diskHashCode); Log.Detail("Re-using existing package assembly"); Graph.Instance.ScriptAssemblyPathname = cachedAssemblyPathname; assemblyCompileProfile.StopProfile(); return; } else { compileReason = "package source has changed since the last compile"; } } } else { compileReason = "no previously compiled package assembly exists"; } } else { compileReason = "user has disabled package assembly caching"; } } // use the compiler in the current runtime version to build the assembly of packages var clrVersion = System.Environment.Version; var compilerVersion = System.String.Format("v{0}.{1}", clrVersion.Major, clrVersion.Minor); Log.Detail("Compiling package assembly (C# compiler {0}{1}), because {2}.", compilerVersion, Graph.Instance.ProcessState.TargetFrameworkVersion != null ? (", targetting " + Graph.Instance.ProcessState.TargetFrameworkVersion) : string.Empty, compileReason); var providerOptions = new System.Collections.Generic.Dictionary <string, string>(); providerOptions.Add("CompilerVersion", compilerVersion); if (Graph.Instance.ProcessState.RunningMono) { Log.DebugMessage("Compiling assembly for Mono"); } using (var provider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions)) { var compilerParameters = new System.CodeDom.Compiler.CompilerParameters(); compilerParameters.TreatWarningsAsErrors = true; compilerParameters.WarningLevel = 4; compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = false; if (Graph.Instance.CompileWithDebugSymbols) { compilerParameters.OutputAssembly = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Graph.Instance.MasterPackage.Name) + ".dll"; } else { compilerParameters.OutputAssembly = cachedAssemblyPathname; } var compilerOptions = "/checked+ /unsafe-"; if (Graph.Instance.CompileWithDebugSymbols) { compilerParameters.IncludeDebugInformation = true; compilerOptions += " /optimize-"; } else { compilerOptions += " /optimize+"; } compilerOptions += " /platform:anycpu"; // define strings compilerOptions += " /define:" + definitions.ToString(';'); compilerParameters.CompilerOptions = compilerOptions; if (provider.Supports(System.CodeDom.Compiler.GeneratorSupport.Resources)) { // Bam assembly // TODO: Q: why is it only for the master package? Why not all of them, which may have additional dependencies? foreach (var assembly in Graph.Instance.MasterPackage.BamAssemblies) { var assemblyFileName = System.String.Format("{0}.dll", assembly.Name); var assemblyPathName = System.IO.Path.Combine(Graph.Instance.ProcessState.ExecutableDirectory, assemblyFileName); compilerParameters.ReferencedAssemblies.Add(assemblyPathName); } // DotNet assembly foreach (var desc in Graph.Instance.MasterPackage.DotNetAssemblies) { var assemblyFileName = System.String.Format("{0}.dll", desc.Name); compilerParameters.ReferencedAssemblies.Add(assemblyFileName); } if (Graph.Instance.ProcessState.RunningMono) { compilerParameters.ReferencedAssemblies.Add("Mono.Posix.dll"); } } else { throw new Exception("C# compiler does not support Resources"); } // this will create the build root directory as necessary IOWrapper.CreateDirectory(System.IO.Path.GetDirectoryName(compilerParameters.OutputAssembly)); var results = Graph.Instance.CompileWithDebugSymbols ? provider.CompileAssemblyFromFile(compilerParameters, sourceCode.ToArray()) : provider.CompileAssemblyFromSource(compilerParameters, sourceCode.ToArray()); if (results.Errors.HasErrors || results.Errors.HasWarnings) { var message = new System.Text.StringBuilder(); message.AppendFormat("Failed to compile package '{0}'. There are {1} errors.", Graph.Instance.MasterPackage.FullName, results.Errors.Count); message.AppendLine(); foreach (System.CodeDom.Compiler.CompilerError error in results.Errors) { message.AppendFormat("\t{0}({1}): {2} {3}", error.FileName, error.Line, error.ErrorNumber, error.ErrorText); message.AppendLine(); } if (!Graph.Instance.CompileWithDebugSymbols) { message.AppendLine(); ICommandLineArgument debugOption = new Options.UseDebugSymbols(); message.AppendFormat("Use the {0}/{1} command line option with bam for more accurate error messages.", debugOption.LongName, debugOption.ShortName); message.AppendLine(); } message.AppendLine(); ICommandLineArgument createDebugProjectOption = new Options.CreateDebugProject(); message.AppendFormat("Use the {0}/{1} command line option with bam to create an editable IDE project containing the build scripts.", createDebugProjectOption.LongName, createDebugProjectOption.ShortName); message.AppendLine(); throw new Exception(message.ToString()); } if (!Graph.Instance.CompileWithDebugSymbols) { if (cacheAssembly) { using (var writer = new System.IO.StreamWriter(hashPathName)) { writer.WriteLine(thisHashCode); } } else { // will not throw if the file doesn't exist System.IO.File.Delete(hashPathName); } } Log.DebugMessage("Written assembly to '{0}'", compilerParameters.OutputAssembly); Graph.Instance.ScriptAssemblyPathname = compilerParameters.OutputAssembly; } assemblyCompileProfile.StopProfile(); }
public static BasePlugin LoadSourcePlugin(string path) { var cp = new Microsoft.CSharp.CSharpCodeProvider(compilerOptions); var par = new System.CodeDom.Compiler.CompilerParameters(); par.GenerateExecutable = false; par.GenerateInMemory = true; par.IncludeDebugInformation = true; //par.CompilerOptions = "/optimize"; par.TreatWarningsAsErrors = false; var us = Assembly.GetExecutingAssembly(); par.ReferencedAssemblies.Add(us.Location); //Add the libraries path as well as where TDSM is located var directory = Path.GetDirectoryName(us.Location); par.CompilerOptions = String.Format("/lib:{0}", Globals.LibrariesPath, directory); // var execs = GetFiles(directory, "*.dll|*.exe"); foreach (var asn in us.GetReferencedAssemblies()) { var name = asn.Name; var execs = GetFiles(directory, name + ".dll|" + name + ".exe"); if (execs != null && execs.Length > 0) { name = execs[0]; } par.ReferencedAssemblies.Add(name); } var result = cp.CompileAssemblyFromFile(par, path); var errors = result.Errors; if (errors != null) { if (errors.HasErrors) { ProgramLog.Error.Log("Failed to compile source plugin:"); } foreach (System.CodeDom.Compiler.CompilerError error in errors) { if (error.IsWarning) { ProgramLog.BareLog(ProgramLog.Debug, error.ToString()); } else { ProgramLog.BareLog(ProgramLog.Error, error.ToString()); } } if (errors.HasErrors) { return(null); } } return(LoadPluginAssembly(result.CompiledAssembly)); }
private void Compile_Clicked(object sender, EventArgs e) { saveToolStripMenuItem_Click(sender, e); if ((DialogResult)saver.Tag == DialogResult.OK) { using (Microsoft.CSharp.CSharpCodeProvider compiler = new Microsoft.CSharp.CSharpCodeProvider()) { System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFile( new System.CodeDom.Compiler.CompilerParameters( Compiler.UsedAssemblies.Select(name => name.Location).ToArray(), saver.FileName.Substring(0, saver.FileName.LastIndexOf('\\') + 1) + "a.exe", true) { MainClass = "MyNamespace.Program", GenerateExecutable = true }, saver.FileNames ); if (results.Errors.Count > 0) foreach (var error in results.Errors) MessageBox.Show(error.ToString()); else MessageBox.Show(results.PathToAssembly); } } }
public static Assembly CompileFromFile(params string[] files) { var csharpParserType = EditorBinding.csharpParserType; if (csharpParserType != null) { //var method = csharpParserType.GetMethod("CompileScript", new Type[] { typeof(IEnumerable<string>) }); //if(method != null) { // List<string> scripts = new List<string>(); // foreach(var file in files) { // scripts.Add(File.ReadAllText(file)); // } // var compileResult = method.Invoke(null, new object[] { scripts as IEnumerable<string> }) as CompileResult; // if(compileResult.assembly == null) { // //compileResult.LogErrors(); // throw new Exception(compileResult.GetErrorMessage()); // } // return compileResult.assembly; //} var method = csharpParserType.GetMethod("CompileFiles", new Type[] { typeof(IEnumerable <string>) }); if (method != null) { var compileResult = method.Invoke(null, new object[] { files as IEnumerable <string> }) as CompileResult; if (compileResult.assembly == null) { //compileResult.LogErrors(); throw new Exception(compileResult.GetErrorMessage()); } return(compileResult.assembly); } } #if !NET_STANDARD_2_0 var provider = new Microsoft.CSharp.CSharpCodeProvider(); var param = new System.CodeDom.Compiler.CompilerParameters(); foreach (var assembly in EditorReflectionUtility.GetAssemblies()) { try { if (!string.IsNullOrEmpty(assembly.Location)) { param.ReferencedAssemblies.Add(assembly.Location); } } catch { continue; } } // Generate a dll in memory param.GenerateExecutable = false; param.GenerateInMemory = true; param.TreatWarningsAsErrors = false; param.IncludeDebugInformation = true; //No Waring //param.WarningLevel = 0; // Compile the source var result = provider.CompileAssemblyFromFile(param, files); if (result.Errors.Count > 0) { var msg = new System.Text.StringBuilder(); bool hasError = false; foreach (System.CodeDom.Compiler.CompilerError error in result.Errors) { //Debug.LogError("Error (" + error.ErrorNumber + "): " + error.ErrorText + "\n"); if (error.IsWarning) { Debug.LogWarningFormat("Warning ({0}): {1}\nin line: {2}", error.ErrorNumber, error.ErrorText, error.Line); } else { hasError = true; msg.AppendFormat("Error ({0}): {1}\nin line: {2}:{3}\nin file:{4}\n", error.ErrorNumber, error.ErrorText, error.Line, error.Column, error.FileName); } } if (hasError) { throw new Exception(msg.ToString()); } } // Return the assembly return(result.CompiledAssembly); #else Debug.Log("Compiling script is disable due to unsupported in .NET Standard 2.0, change API compativility level to .NET 4.x to enable it or import CSharp Parser add-ons to compile with Roslyn instead."); return(null); #endif }
public Assembly compileSourceCode_Sync(string sourceCode) { if (sourceCode.notValid()) return null; try { Environment.CurrentDirectory = PublicDI.config.CurrentExecutableDirectory; CompiledAssembly = null; beforeCompile.invoke(); DebugMode.ifInfo("Compiling Source Code (Size: {0})", sourceCode.size()); SourceCode = sourceCode; if (sourceCode.lines().starting("//CLR_3.5").notEmpty()) // allow setting compilation into 2.0 CLR { CompilationVersion = "v3.5"; } var providerOptions = new Dictionary<string, string>().add("CompilerVersion", CompilationVersion); var csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions); var compilerParams = new CompilerParameters(); compilerParams.OutputAssembly = "_o2_Script.dll".tempFile(); compilerParams.IncludeDebugInformation = generateDebugSymbols; compilerParams.GenerateInMemory = !generateDebugSymbols; foreach (var referencedAssembly in ReferencedAssemblies) compilerParams.ReferencedAssemblies.Add(referencedAssembly); CompilerResults = (generateDebugSymbols) ? csharpCodeProvider.CompileAssemblyFromFile(compilerParams, sourceCode.saveWithExtension(".cs")) : csharpCodeProvider.CompileAssemblyFromSource(compilerParams, sourceCode); if (CompilerResults.Errors.Count > 0 || CompilerResults.CompiledAssembly == null) { CompilationErrors = ""; foreach (CompilerError error in CompilerResults.Errors) { //CompilationErrors.Add(CompilationErrors.line(error.ToString()); var errorMessage = String.Format("{0}::{1}::{2}::{3}::{4}", error.Line, error.Column, error.ErrorNumber, error.ErrorText, error.FileName); CompilationErrors = CompilationErrors.line(errorMessage); "[CSharp_FastCompiler] Compilation Error: {0}".error(errorMessage); } DebugMode.ifError("Compilation failed"); onCompileFail.invoke(); } else { CompiledAssembly = CompilerResults.CompiledAssembly; if (CompiledAssembly.Location.fileExists()) CompileEngine.setCachedCompiledAssembly_toMD5(sourceCode, CompiledAssembly); DebugMode.ifDebug("Compilation was OK"); onCompileOK.invoke(); } return CompiledAssembly; } catch (Exception ex) { ex.log("[compileSourceCode_Sync"); return null; } }
private void WriteProject(SolutionNode solution, ProjectNode project) { string solutionDir = Path.Combine(solution.FullPath, Path.Combine("autotools", solution.Name)); string projectDir = Path.Combine(solutionDir, project.Name); string projectVersion = project.Version; bool hasAssemblyConfig = false; chkMkDir(projectDir); List<string> compiledFiles = new List<string>(), contentFiles = new List<string>(), embeddedFiles = new List<string>(), binaryLibs = new List<string>(), pkgLibs = new List<string>(), systemLibs = new List<string>(), runtimeLibs = new List<string>(), extraDistFiles = new List<string>(), localCopyTargets = new List<string>(); // If there exists a .config file for this assembly, copy // it to the project folder // TODO: Support copying .config.osx files // TODO: support processing the .config file for native library deps string projectAssemblyName = project.Name; if (project.AssemblyName != null) projectAssemblyName = project.AssemblyName; if (File.Exists(Path.Combine(project.FullPath, projectAssemblyName) + ".dll.config")) { hasAssemblyConfig = true; System.IO.File.Copy(Path.Combine(project.FullPath, projectAssemblyName + ".dll.config"), Path.Combine(projectDir, projectAssemblyName + ".dll.config"), true); extraDistFiles.Add(project.AssemblyName + ".dll.config"); } foreach (ConfigurationNode conf in project.Configurations) { if (conf.Options.KeyFile != string.Empty) { // Copy snk file into the project's directory // Use the snk from the project directory directly string source = Path.Combine(project.FullPath, conf.Options.KeyFile); string keyFile = conf.Options.KeyFile; Regex re = new Regex(".*/"); keyFile = re.Replace(keyFile, ""); string dest = Path.Combine(projectDir, keyFile); // Tell the user if there's a problem copying the file try { mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } // Copy compiled, embedded and content files into the project's directory foreach (string filename in project.Files) { string source = Path.Combine(project.FullPath, filename); string dest = Path.Combine(projectDir, filename); if (filename.Contains("AssemblyInfo.cs")) { // If we've got an AssemblyInfo.cs, pull the version number from it string[] sources = { source }; string[] args = { "" }; Microsoft.CSharp.CSharpCodeProvider cscp = new Microsoft.CSharp.CSharpCodeProvider(); string tempAssemblyFile = Path.Combine(Path.GetTempPath(), project.Name + "-temp.dll"); System.CodeDom.Compiler.CompilerParameters cparam = new System.CodeDom.Compiler.CompilerParameters(args, tempAssemblyFile); System.CodeDom.Compiler.CompilerResults cr = cscp.CompileAssemblyFromFile(cparam, sources); foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors) Console.WriteLine("Error! '{0}'", error.ErrorText); try { string projectFullName = cr.CompiledAssembly.FullName; Regex verRegex = new Regex("Version=([\\d\\.]+)"); Match verMatch = verRegex.Match(projectFullName); if (verMatch.Success) projectVersion = verMatch.Groups[1].Value; }catch{ Console.WriteLine("Couldn't compile AssemblyInfo.cs"); } // Clean up the temp file try { if (File.Exists(tempAssemblyFile)) File.Delete(tempAssemblyFile); } catch { Console.WriteLine("Error! '{0}'", e); } } // Tell the user if there's a problem copying the file try { mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } switch (project.Files.GetBuildAction(filename)) { case BuildAction.Compile: compiledFiles.Add(filename); break; case BuildAction.Content: contentFiles.Add(filename); extraDistFiles.Add(filename); break; case BuildAction.EmbeddedResource: embeddedFiles.Add(filename); break; } } // Set up references for (int refNum = 0; refNum < project.References.Count; refNum++) { ReferenceNode refr = project.References[refNum]; Assembly refAssembly = Assembly.LoadWithPartialName(refr.Name); /* Determine which pkg-config (.pc) file refers to this assembly */ SystemPackage package = null; if (packagesHash.ContainsKey(refr.Name)) { package = packagesHash[refr.Name]; } else { string assemblyFullName = string.Empty; if (refAssembly != null) assemblyFullName = refAssembly.FullName; string assemblyFileName = string.Empty; if (assemblyFullName != string.Empty && assemblyFullNameToPath.ContainsKey(assemblyFullName) ) assemblyFileName = assemblyFullNameToPath[assemblyFullName]; if (assemblyFileName != string.Empty && assemblyPathToPackage.ContainsKey(assemblyFileName) ) package = assemblyPathToPackage[assemblyFileName]; } /* If we know the .pc file and it is not "mono" (already in the path), add a -pkg: argument */ if (package != null && package.Name != "mono" && !pkgLibs.Contains(package.Name) ) pkgLibs.Add(package.Name); string fileRef = FindFileReference(refr.Name, (ProjectNode)refr.Parent); if (refr.LocalCopy || solution.ProjectsTable.ContainsKey(refr.Name) || fileRef != null || refr.Path != null ) { /* Attempt to copy the referenced lib to the project's directory */ string filename = refr.Name + ".dll"; string source = filename; if (refr.Path != null) source = Path.Combine(refr.Path, source); source = Path.Combine(project.FullPath, source); string dest = Path.Combine(projectDir, filename); /* Since we depend on this binary dll to build, we * will add a compile- time dependency on the * copied dll, and add the dll to the list of * files distributed with this package */ binaryLibs.Add(refr.Name + ".dll"); extraDistFiles.Add(refr.Name + ".dll"); // TODO: Support copying .config.osx files // TODO: Support for determining native dependencies if (File.Exists(source + ".config")) { System.IO.File.Copy(source + ".config", Path.GetDirectoryName(dest), true); extraDistFiles.Add(refr.Name + ".dll.config"); } try { System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException) { if (solution.ProjectsTable.ContainsKey(refr.Name)){ /* If an assembly is referenced, marked for * local copy, in the list of projects for * this solution, but does not exist, put a * target into the Makefile.am to build the * assembly and copy it to this project's * directory */ ProjectNode sourcePrj = ((solution.ProjectsTable[refr.Name])); string target = String.Format("{0}:\n" + "\t$(MAKE) -C ../{1}\n" + "\tln ../{2}/$@ $@\n", filename, sourcePrj.Name, sourcePrj.Name ); localCopyTargets.Add(target); } } } else if( !pkgLibs.Contains(refr.Name) ) { // Else, let's assume it's in the GAC or the lib path string assemName = string.Empty; int index = refr.Name.IndexOf(","); if (index > 0) assemName = refr.Name.Substring(0, index); else assemName = refr.Name; m_Kernel.Log.Write(String.Format( "Warning: Couldn't find an appropriate assembly " + "for reference:\n'{0}'", refr.Name )); systemLibs.Add(assemName); } } const string lineSep = " \\\n\t"; string compiledFilesString = string.Empty; if (compiledFiles.Count > 0) compiledFilesString = lineSep + string.Join(lineSep, compiledFiles.ToArray()); string embeddedFilesString = ""; if (embeddedFiles.Count > 0) embeddedFilesString = lineSep + string.Join(lineSep, embeddedFiles.ToArray()); string contentFilesString = ""; if (contentFiles.Count > 0) contentFilesString = lineSep + string.Join(lineSep, contentFiles.ToArray()); string extraDistFilesString = ""; if (extraDistFiles.Count > 0) extraDistFilesString = lineSep + string.Join(lineSep, extraDistFiles.ToArray()); string pkgLibsString = ""; if (pkgLibs.Count > 0) pkgLibsString = lineSep + string.Join(lineSep, pkgLibs.ToArray()); string binaryLibsString = ""; if (binaryLibs.Count > 0) binaryLibsString = lineSep + string.Join(lineSep, binaryLibs.ToArray()); string systemLibsString = ""; if (systemLibs.Count > 0) systemLibsString = lineSep + string.Join(lineSep, systemLibs.ToArray()); string localCopyTargetsString = ""; if (localCopyTargets.Count > 0) localCopyTargetsString = string.Join("\n", localCopyTargets.ToArray()); string monoPath = ""; foreach (string runtimeLib in runtimeLibs) { monoPath += ":`pkg-config --variable=libdir " + runtimeLib + "`"; } // Add the project name to the list of transformation // parameters XsltArgumentList argList = new XsltArgumentList(); argList.AddParam("projectName", "", project.Name); argList.AddParam("solutionName", "", solution.Name); argList.AddParam("assemblyName", "", projectAssemblyName); argList.AddParam("compiledFiles", "", compiledFilesString); argList.AddParam("embeddedFiles", "", embeddedFilesString); argList.AddParam("contentFiles", "", contentFilesString); argList.AddParam("extraDistFiles", "", extraDistFilesString); argList.AddParam("pkgLibs", "", pkgLibsString); argList.AddParam("binaryLibs", "", binaryLibsString); argList.AddParam("systemLibs", "", systemLibsString); argList.AddParam("monoPath", "", monoPath); argList.AddParam("localCopyTargets", "", localCopyTargetsString); argList.AddParam("projectVersion", "", projectVersion); argList.AddParam("hasAssemblyConfig", "", hasAssemblyConfig ? "true" : ""); // Transform the templates transformToFile(Path.Combine(projectDir, "configure.ac"), argList, "/Autotools/ProjectConfigureAc"); transformToFile(Path.Combine(projectDir, "Makefile.am"), argList, "/Autotools/ProjectMakefileAm"); transformToFile(Path.Combine(projectDir, "autogen.sh"), argList, "/Autotools/ProjectAutogenSh"); if (project.Type == Core.Nodes.ProjectType.Library) transformToFile(Path.Combine(projectDir, project.Name + ".pc.in"), argList, "/Autotools/ProjectPcIn"); if (project.Type == Core.Nodes.ProjectType.Exe || project.Type == Core.Nodes.ProjectType.WinExe) transformToFile(Path.Combine(projectDir, project.Name.ToLower() + ".in"), argList, "/Autotools/ProjectWrapperScriptIn"); }
private void Scan() { try { BotShell.Output("[Plugins] Starting Plugin Scan..."); if (this.PluginLoaders == null) { this.PluginLoaders = new SortedDictionary <string, PluginLoader>(); } lock (this.PluginLoaders) this.PluginLoaders.Clear(); List <ScannedAssembly> assemblies = new List <ScannedAssembly>(); // Add this Assembly to the list assemblies.Add(new ScannedAssembly(Assembly.LoadFrom("VhaBot.CorePlugins.dll"), AssemblyType.Buildin, "VhaBot.CorePlugins.dll")); // Scan for DLLs string dllPath = this.PluginsPath.Contains(";") ? this.PluginsPath.Substring(0, this.PluginsPath.IndexOf(';')) : this.PluginsPath; string[] dlls = new string[0]; try { dlls = Directory.GetFiles("." + Path.DirectorySeparatorChar + dllPath + Path.DirectorySeparatorChar, "*.dll"); } catch { } foreach (string dll in dlls) { string shortDll = Path.GetFileName(dll); if (shortDll.Length < 1 || shortDll.ToCharArray()[0] == '_') { BotShell.Output("[Plugins] Skipped DLL: " + shortDll, true); continue; } BotShell.Output("[Plugins] Found DLL: " + shortDll, true); try { assemblies.Add(new ScannedAssembly(Assembly.LoadFrom(dll), AssemblyType.Binary, shortDll)); } catch (Exception ex) { BotShell.Output("[Plugins] Failed Loading DLL " + shortDll + ": " + ex.ToString()); } } // Scan for plugin files string[] paths = this.PluginsPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string path in paths) { if (path == null || path == string.Empty) { continue; } if (!Directory.Exists(path)) { continue; } List <string> filesSharp = new List <string>(); foreach (string file in Directory.GetFiles(path + Path.DirectorySeparatorChar, "*.cs")) { filesSharp.Add(file); } List <string> filesBasic = new List <string>(); foreach (string file in Directory.GetFiles(path + Path.DirectorySeparatorChar, "*.vb")) { filesBasic.Add(file); } if (filesSharp.Count > 0 || filesBasic.Count > 0) { CodeDomProvider csCompiler = new Microsoft.CSharp.CSharpCodeProvider(); CodeDomProvider vbCompiler = new Microsoft.VisualBasic.VBCodeProvider(); CompilerParameters options = new CompilerParameters(); options.CompilerOptions = "/target:library /optimize"; options.GenerateExecutable = false; options.GenerateInMemory = true; options.IncludeDebugInformation = false; // .NET related assemblies options.ReferencedAssemblies.Add("mscorlib.dll"); options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); options.ReferencedAssemblies.Add("System.Xml.dll"); options.ReferencedAssemblies.Add("System.Web.dll"); // VhaBot related assemblies options.ReferencedAssemblies.Add("AoLib.dll"); options.ReferencedAssemblies.Add("VhaBot.API.dll"); options.ReferencedAssemblies.Add("VhaBot.Communication.dll"); // Add reference DLL's foreach (ScannedAssembly assembly in assemblies) { if (assembly.Type == AssemblyType.Binary) { options.ReferencedAssemblies.Add(dllPath + Path.DirectorySeparatorChar + assembly.File); } } for (int i = 0; i < 2; i++) { try { CompilerResults results = null; if (i == 0) { if (filesSharp.Count < 1) { continue; } results = csCompiler.CompileAssemblyFromFile(options, filesSharp.ToArray()); } else { if (filesBasic.Count < 1) { continue; } results = csCompiler.CompileAssemblyFromFile(options, filesBasic.ToArray()); } List <string> shortFiles = new List <string>(); if (i == 0) { foreach (string file in filesSharp) { shortFiles.Add(Path.GetFileName(file)); } } else { foreach (string file in filesBasic) { shortFiles.Add(Path.GetFileName(file)); } } string shortFile = string.Join(", ", shortFiles.ToArray()); bool errors = false; if (results.Errors.Count > 0) { foreach (CompilerError error in results.Errors) { if (error.IsWarning) { continue; } BotShell.Output("[Plugins] Compile Error: " + error.ErrorText + " (" + error.FileName + ":" + error.Line + ")"); this.SafeMode = true; errors = true; } } if (!errors) { BotShell.Output("[Plugins] Compiled: " + shortFile); assemblies.Add(new ScannedAssembly(results.CompiledAssembly, AssemblyType.Source, path)); } } catch (Exception ex) { BotShell.Output("[Plugins] Error while compiling: " + ex.ToString()); this.SafeMode = true; } } } } // Scan for plugins foreach (ScannedAssembly assembly in assemblies) { Type[] types = assembly.Assembly.GetExportedTypes(); foreach (Type _type in types) { string type = _type.FullName; try { PluginLoader loader = new PluginLoader(assembly.File, type, assembly.Type, assembly.Assembly); lock (this.PluginLoaders) { if (this.PluginLoaders.ContainsKey(loader.InternalName.ToLower())) { BotShell.Output("[Error] Internal Name (" + loader.InternalName + ") Already in Use!", true); BotShell.Output("[Error] Plugin (" + loader.ToString() + ") Conflicts With Plugin (" + this.PluginLoaders[loader.InternalName.ToLower()].ToString() + ")"); BotShell.Output("[Error] Skipped Object " + loader.Type + " in " + loader.File + "!", true); } else { if (loader.DefaultState != PluginState.Core && this.SafeMode) { continue; // When using SafeMode, load only core plugins } if (loader.Dependencies.Length > 0 && loader.DefaultState == PluginState.Loaded) { BotShell.Output("[Error] Plugins with dependencies can't have DefaultState = Loaded (" + loader.InternalName + ")! Plugin skipped!"); continue; } if (loader.Dependencies.Length > 0 && loader.DefaultState == PluginState.Core) { BotShell.Output("[Error] Core plugins can't have dependencies (" + loader.InternalName + ")! Plugin skipped!"); continue; } if (loader.AssemblyType != AssemblyType.Buildin && loader.DefaultState == PluginState.Core) { BotShell.Output("[Error] Only buildin plugins can have DefaultState = Core (" + loader.InternalName + ")! Plugin skipped!"); continue; } this.PluginLoaders.Add(loader.InternalName.ToLower(), loader); BotShell.Output("[Plugins] Detected Plugin: " + loader.ToString(), true); } } } catch { } } } BotShell.Output("[Plugins] Found " + this.PluginLoaders.Count + " Plugins"); return; } catch (Exception ex) { BotShell.Output("[Plugins] Unknown error during plugin scanning! " + ex.ToString()); return; } }
public Assembly CreateAssembly(IList filenames, IList references) { string fileType = null; foreach (string filename in filenames) { string extension = Path.GetExtension(filename); if (fileType == null) { fileType = extension; } else if (fileType != extension) { throw new ArgumentException("All files in the file list must be of the same type."); } } compilerErrors = null; CodeDomProvider codeProvider = null; switch (fileType) { case ".cs": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; case ".vb": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; default: throw new InvalidOperationException("Script files must have a .cs, .vb, or .js extension, for C#, Visual Basic.NET, or JScript respectively."); } CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); foreach (string reference in references) { if (!compilerParams.ReferencedAssemblies.Contains(reference)) { compilerParams.ReferencedAssemblies.Add(reference); } } CompilerResults results = codeProvider.CompileAssemblyFromFile( compilerParams, (string[])ArrayList.Adapter(filenames).ToArray(typeof(string))); if (results.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (CompilerError item in results.Errors) { sb.AppendFormat("{0} line:{1} {2}\r\n", item.FileName, item.Line, item.ErrorText); } compilerErrors = results.Errors; throw new Exception( "Compiler error(s)\r\n" + sb.ToString()); } Assembly createdAssembly = results.CompiledAssembly; return(createdAssembly); }
private void WriteProject(SolutionNode solution, ProjectNode project) { string solutionDir = Path.Combine(solution.FullPath, Path.Combine("autotools", solution.Name)); string projectDir = Path.Combine(solutionDir, project.Name); string projectVersion = project.Version; bool hasAssemblyConfig = false; chkMkDir(projectDir); List <string> compiledFiles = new List <string>(), contentFiles = new List <string>(), embeddedFiles = new List <string>(), binaryLibs = new List <string>(), pkgLibs = new List <string>(), systemLibs = new List <string>(), runtimeLibs = new List <string>(), extraDistFiles = new List <string>(), localCopyTargets = new List <string>(); // If there exists a .config file for this assembly, copy // it to the project folder // TODO: Support copying .config.osx files // TODO: support processing the .config file for native library deps string projectAssemblyName = project.Name; if (project.AssemblyName != null) { projectAssemblyName = project.AssemblyName; } if (File.Exists(Path.Combine(project.FullPath, projectAssemblyName) + ".dll.config")) { hasAssemblyConfig = true; System.IO.File.Copy(Path.Combine(project.FullPath, projectAssemblyName + ".dll.config"), Path.Combine(projectDir, projectAssemblyName + ".dll.config"), true); extraDistFiles.Add(project.AssemblyName + ".dll.config"); } foreach (ConfigurationNode conf in project.Configurations) { if (conf.Options.KeyFile != string.Empty) { // Copy snk file into the project's directory // Use the snk from the project directory directly string source = Path.Combine(project.FullPath, conf.Options.KeyFile); string keyFile = conf.Options.KeyFile; Regex re = new Regex(".*/"); keyFile = re.Replace(keyFile, ""); string dest = Path.Combine(projectDir, keyFile); // Tell the user if there's a problem copying the file try { mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } // Copy compiled, embedded and content files into the project's directory foreach (string filename in project.Files) { string source = Path.Combine(project.FullPath, filename); string dest = Path.Combine(projectDir, filename); if (filename.Contains("AssemblyInfo.cs")) { // If we've got an AssemblyInfo.cs, pull the version number from it string[] sources = { source }; string[] args = { "" }; Microsoft.CSharp.CSharpCodeProvider cscp = new Microsoft.CSharp.CSharpCodeProvider(); string tempAssemblyFile = Path.Combine(Path.GetTempPath(), project.Name + "-temp.dll"); System.CodeDom.Compiler.CompilerParameters cparam = new System.CodeDom.Compiler.CompilerParameters(args, tempAssemblyFile); System.CodeDom.Compiler.CompilerResults cr = cscp.CompileAssemblyFromFile(cparam, sources); foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors) { Console.WriteLine("Error! '{0}'", error.ErrorText); } try { string projectFullName = cr.CompiledAssembly.FullName; Regex verRegex = new Regex("Version=([\\d\\.]+)"); Match verMatch = verRegex.Match(projectFullName); if (verMatch.Success) { projectVersion = verMatch.Groups[1].Value; } }catch { Console.WriteLine("Couldn't compile AssemblyInfo.cs"); } // Clean up the temp file try { if (File.Exists(tempAssemblyFile)) { File.Delete(tempAssemblyFile); } } catch { Console.WriteLine("Error! '{0}'", e); } } // Tell the user if there's a problem copying the file try { mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } switch (project.Files.GetBuildAction(filename)) { case BuildAction.Compile: compiledFiles.Add(filename); break; case BuildAction.Content: contentFiles.Add(filename); extraDistFiles.Add(filename); break; case BuildAction.EmbeddedResource: embeddedFiles.Add(filename); break; } } // Set up references for (int refNum = 0; refNum < project.References.Count; refNum++) { ReferenceNode refr = project.References[refNum]; Assembly refAssembly = Assembly.LoadWithPartialName(refr.Name); /* Determine which pkg-config (.pc) file refers to * this assembly */ SystemPackage package = null; if (packagesHash.ContainsKey(refr.Name)) { package = packagesHash[refr.Name]; } else { string assemblyFullName = string.Empty; if (refAssembly != null) { assemblyFullName = refAssembly.FullName; } string assemblyFileName = string.Empty; if (assemblyFullName != string.Empty && assemblyFullNameToPath.ContainsKey(assemblyFullName) ) { assemblyFileName = assemblyFullNameToPath[assemblyFullName]; } if (assemblyFileName != string.Empty && assemblyPathToPackage.ContainsKey(assemblyFileName) ) { package = assemblyPathToPackage[assemblyFileName]; } } /* If we know the .pc file and it is not "mono" * (already in the path), add a -pkg: argument */ if (package != null && package.Name != "mono" && !pkgLibs.Contains(package.Name) ) { pkgLibs.Add(package.Name); } string fileRef = FindFileReference(refr.Name, (ProjectNode)refr.Parent); if (refr.LocalCopy || solution.ProjectsTable.ContainsKey(refr.Name) || fileRef != null || refr.Path != null ) { /* Attempt to copy the referenced lib to the * project's directory */ string filename = refr.Name + ".dll"; string source = filename; if (refr.Path != null) { source = Path.Combine(refr.Path, source); } source = Path.Combine(project.FullPath, source); string dest = Path.Combine(projectDir, filename); /* Since we depend on this binary dll to build, we * will add a compile- time dependency on the * copied dll, and add the dll to the list of * files distributed with this package */ binaryLibs.Add(refr.Name + ".dll"); extraDistFiles.Add(refr.Name + ".dll"); // TODO: Support copying .config.osx files // TODO: Support for determining native dependencies if (File.Exists(source + ".config")) { System.IO.File.Copy(source + ".config", Path.GetDirectoryName(dest), true); extraDistFiles.Add(refr.Name + ".dll.config"); } try { System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException) { if (solution.ProjectsTable.ContainsKey(refr.Name)) { /* If an assembly is referenced, marked for * local copy, in the list of projects for * this solution, but does not exist, put a * target into the Makefile.am to build the * assembly and copy it to this project's * directory */ ProjectNode sourcePrj = ((solution.ProjectsTable[refr.Name])); string target = String.Format("{0}:\n" + "\t$(MAKE) -C ../{1}\n" + "\tln ../{2}/$@ $@\n", filename, sourcePrj.Name, sourcePrj.Name); localCopyTargets.Add(target); } } } else if (!pkgLibs.Contains(refr.Name)) { // Else, let's assume it's in the GAC or the lib path string assemName = string.Empty; int index = refr.Name.IndexOf(","); if (index > 0) { assemName = refr.Name.Substring(0, index); } else { assemName = refr.Name; } m_Kernel.Log.Write(String.Format( "Warning: Couldn't find an appropriate assembly " + "for reference:\n'{0}'", refr.Name )); systemLibs.Add(assemName); } } const string lineSep = " \\\n\t"; string compiledFilesString = string.Empty; if (compiledFiles.Count > 0) { compiledFilesString = lineSep + string.Join(lineSep, compiledFiles.ToArray()); } string embeddedFilesString = ""; if (embeddedFiles.Count > 0) { embeddedFilesString = lineSep + string.Join(lineSep, embeddedFiles.ToArray()); } string contentFilesString = ""; if (contentFiles.Count > 0) { contentFilesString = lineSep + string.Join(lineSep, contentFiles.ToArray()); } string extraDistFilesString = ""; if (extraDistFiles.Count > 0) { extraDistFilesString = lineSep + string.Join(lineSep, extraDistFiles.ToArray()); } string pkgLibsString = ""; if (pkgLibs.Count > 0) { pkgLibsString = lineSep + string.Join(lineSep, pkgLibs.ToArray()); } string binaryLibsString = ""; if (binaryLibs.Count > 0) { binaryLibsString = lineSep + string.Join(lineSep, binaryLibs.ToArray()); } string systemLibsString = ""; if (systemLibs.Count > 0) { systemLibsString = lineSep + string.Join(lineSep, systemLibs.ToArray()); } string localCopyTargetsString = ""; if (localCopyTargets.Count > 0) { localCopyTargetsString = string.Join("\n", localCopyTargets.ToArray()); } string monoPath = ""; foreach (string runtimeLib in runtimeLibs) { monoPath += ":`pkg-config --variable=libdir " + runtimeLib + "`"; } // Add the project name to the list of transformation // parameters XsltArgumentList argList = new XsltArgumentList(); argList.AddParam("projectName", "", project.Name); argList.AddParam("solutionName", "", solution.Name); argList.AddParam("assemblyName", "", projectAssemblyName); argList.AddParam("compiledFiles", "", compiledFilesString); argList.AddParam("embeddedFiles", "", embeddedFilesString); argList.AddParam("contentFiles", "", contentFilesString); argList.AddParam("extraDistFiles", "", extraDistFilesString); argList.AddParam("pkgLibs", "", pkgLibsString); argList.AddParam("binaryLibs", "", binaryLibsString); argList.AddParam("systemLibs", "", systemLibsString); argList.AddParam("monoPath", "", monoPath); argList.AddParam("localCopyTargets", "", localCopyTargetsString); argList.AddParam("projectVersion", "", projectVersion); argList.AddParam("hasAssemblyConfig", "", hasAssemblyConfig ? "true" : ""); // Transform the templates transformToFile(Path.Combine(projectDir, "configure.ac"), argList, "/Autotools/ProjectConfigureAc"); transformToFile(Path.Combine(projectDir, "Makefile.am"), argList, "/Autotools/ProjectMakefileAm"); transformToFile(Path.Combine(projectDir, "autogen.sh"), argList, "/Autotools/ProjectAutogenSh"); if (project.Type == Core.Nodes.ProjectType.Library) { transformToFile(Path.Combine(projectDir, project.Name + ".pc.in"), argList, "/Autotools/ProjectPcIn"); } if (project.Type == Core.Nodes.ProjectType.Exe || project.Type == Core.Nodes.ProjectType.WinExe) { transformToFile(Path.Combine(projectDir, project.Name.ToLower() + ".in"), argList, "/Autotools/ProjectWrapperScriptIn"); } }
/// <summary> /// Build code bằng Microsoft.CSharp.CSharpCodeProvider /// </summary> /// <returns></returns> public bool CompileAssembly() { bool compileOk = false; if (this.SourceFiles.Any() == false) { return(compileOk); } this.CompilerResults = null; var pathDirTemp = this.CreateSourceFilesBuildTemp(DateTime.Now, v_KindBuildAssembly.ByCodeProvider); try { Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); if (provider != null) { System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters(); // Save the assembly as a physical file. compilerParameters.GenerateInMemory = false; // Set whether to treat all warnings as errors. compilerParameters.TreatWarningsAsErrors = false; // Specify the assembly file name to generate. if (this.OutputAssembly + "" != "") { compilerParameters.OutputAssembly = this.OutputAssembly; } else { var sourceFirst = new System.IO.FileInfo(this.SourceFiles.First()); compilerParameters.OutputAssembly = String.Format(@"{0}\{1}.exe", System.Environment.CurrentDirectory, sourceFirst.Name.Replace(".", "_")); } compilerParameters.CompilerOptions = string.Format("/optimize {0}", this.CreateOptionWin32Icon()); // Generate an executable instead of // a class library. if (this.OutputAssembly.ToUpper().EndsWith("EXE")) { compilerParameters.GenerateExecutable = true; } else { compilerParameters.GenerateExecutable = false; } // Set reference dll if (this.ReferencedAssemblies != null && this.ReferencedAssemblies.Any()) { foreach (string itemValue in this.ReferencedAssemblies) { var item = itemValue + ""; if (item.ToUpper().EndsWith(".dll".ToUpper()) == false && item.ToUpper().EndsWith(".exe".ToUpper()) == false) { item = item + ".dll"; } if (System.IO.File.Exists(item)) { compilerParameters.ReferencedAssemblies.Add(item); } else if (this.ReferencedAssemblyNoPaths.Where(x => x.ToUpper().Contains(item.ToUpper())).Any()) { compilerParameters.ReferencedAssemblies.Add(item); } else { foreach (var pathDir in this.ReferencedAssemblyDirs) { var pathFile = System.IO.Path.Combine(pathDir, item); if (System.IO.File.Exists(pathFile)) { compilerParameters.ReferencedAssemblies.Add(pathFile); break; } } } } } this.ReferencedAssemblyNoPaths.ForEach(x => { if (compilerParameters.ReferencedAssemblies.Contains(x) == false) { compilerParameters.ReferencedAssemblies.Add(x); } }); // Invoke compilation of the source file. this.CompilerResults = provider.CompileAssemblyFromFile(compilerParameters, this.SourceFilesBuildTemp.ToArray()); compileOk = !(this.CompilerResults.Errors.Count > 0); if (compileOk && System.IO.File.Exists(this.OutputAssembly)) { if (this.AssemblyFileVersionCode == "") { compileOk = true; } else { compileOk = Compiler.CompareStringVersion(this.AssemblyFileVersionCode, Compiler.GetVersionStringFile(this.OutputAssembly)); } } else { compileOk = false; } } return(compileOk); } catch { return(compileOk); } finally { try { Compiler.DirectoryDeleteForce(System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(pathDirTemp))); } catch { } } }
/// <summary> /// Creates an assembly by dynamically compiling TestVersionTableMetaData.cs /// </summary> /// <returns></returns> private Assembly GetAssemblyWithCustomVersionTableMetaData() { CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parms = new CompilerParameters(); // Configure parameters parms.GenerateExecutable = false; parms.GenerateInMemory = true; parms.IncludeDebugInformation = false; parms.ReferencedAssemblies.Add("System.dll"); parms.ReferencedAssemblies.Add("FluentMigrator.dll"); CompilerResults results = provider.CompileAssemblyFromFile(parms, "..\\..\\Unit\\TestVersionTableMetaData.cs"); Assert.AreEqual(0, results.Errors.Count); return results.CompiledAssembly; }
public Assembly CreateAssembly(IList filenames, IList references) { string fileType = null; foreach (string filename in filenames) { string extension = Path.GetExtension(filename); if (fileType == null) { fileType = extension; } else if (fileType != extension) { throw new ArgumentException("All files in the file list must be of the same type."); } } compilerErrors = null; CodeDomProvider codeProvider = null; switch (fileType) { case ".cs": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; case ".vb": codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; default: throw new InvalidOperationException("Script files must have a .cs, .vb, or .js extension, for C#, Visual Basic.NET, or JScript respectively."); } CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); foreach (string reference in references) { if (!compilerParams.ReferencedAssemblies.Contains(reference)) { compilerParams.ReferencedAssemblies.Add(reference); } } CompilerResults results = codeProvider.CompileAssemblyFromFile( compilerParams, (string[])ArrayList.Adapter(filenames).ToArray(typeof(string))); if (results.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (CompilerError item in results.Errors) { sb.AppendFormat("{0} line:{1} {2}\r\n", item.FileName, item.Line, item.ErrorText); } compilerErrors = results.Errors; throw new Exception( "Compiler error(s)\r\n" + sb.ToString()); } Assembly createdAssembly = results.CompiledAssembly; return createdAssembly; }
CompilePackageAssembly( bool enforceBamAssemblyVersions = true, bool enableClean = true) { // validate build root if (null == Graph.Instance.BuildRoot) { throw new Exception("Build root has not been specified"); } var gatherSourceProfile = new TimeProfile(ETimingProfiles.GatherSource); gatherSourceProfile.StartProfile(); IdentifyAllPackages(enforceBamAssemblyVersions: enforceBamAssemblyVersions); var cleanFirst = CommandLineProcessor.Evaluate(new Options.CleanFirst()); if (enableClean && cleanFirst && System.IO.Directory.Exists(Graph.Instance.BuildRoot)) { Log.Info("Deleting build root '{0}'", Graph.Instance.BuildRoot); try { System.IO.Directory.Delete(Graph.Instance.BuildRoot, true); } catch (System.IO.IOException ex) { Log.Info("Failed to delete build root, because {0}. Continuing", ex.Message); } } if (!System.IO.Directory.Exists(Graph.Instance.BuildRoot)) { System.IO.Directory.CreateDirectory(Graph.Instance.BuildRoot); } BuildModeUtilities.ValidateBuildModePackage(); var definitions = new StringArray(); // gather source files var sourceCode = new StringArray(); int packageIndex = 0; foreach (var package in Graph.Instance.Packages) { Log.DebugMessage("{0}: '{1}' @ '{2}'", packageIndex, package.Version, (package.PackageRepositories.Count > 0) ? package.PackageRepositories[0] : "Not in a repository"); // to compile with debug information, you must compile the files // to compile without, we need to file contents to hash the source if (Graph.Instance.CompileWithDebugSymbols) { var scripts = package.GetScriptFiles(); sourceCode.AddRange(scripts); Log.DebugMessage(scripts.ToString("\n\t")); } else { foreach (var scriptFile in package.GetScriptFiles()) { using (var reader = new System.IO.StreamReader(scriptFile)) { sourceCode.Add(reader.ReadToEnd()); } Log.DebugMessage("\t'{0}'", scriptFile); } } foreach (var define in package.Definitions) { if (!definitions.Contains(define)) { definitions.Add(define); } } ++packageIndex; } // add/remove other definitions definitions.Add(VersionDefineForCompiler); definitions.Add(HostPlatformDefineForCompiler); definitions.Sort(); gatherSourceProfile.StopProfile(); var assemblyCompileProfile = new TimeProfile(ETimingProfiles.AssemblyCompilation); assemblyCompileProfile.StartProfile(); // assembly is written to the build root var cachedAssemblyPathname = System.IO.Path.Combine(Graph.Instance.BuildRoot, "CachedPackageAssembly"); cachedAssemblyPathname = System.IO.Path.Combine(cachedAssemblyPathname, Graph.Instance.MasterPackage.Name) + ".dll"; var hashPathName = System.IO.Path.ChangeExtension(cachedAssemblyPathname, "hash"); string thisHashCode = null; var cacheAssembly = !CommandLineProcessor.Evaluate(new Options.DisableCacheAssembly()); string compileReason = null; if (Graph.Instance.CompileWithDebugSymbols) { compileReason = "debug symbols were enabled"; } else { // can an existing assembly be reused? thisHashCode = GetPackageHash(sourceCode, definitions, Graph.Instance.MasterPackage.BamAssemblies); if (cacheAssembly) { if (System.IO.File.Exists(hashPathName)) { using (var reader = new System.IO.StreamReader(hashPathName)) { var diskHashCode = reader.ReadLine(); if (diskHashCode.Equals(thisHashCode)) { Log.DebugMessage("Cached assembly used '{0}', with hash {1}", cachedAssemblyPathname, diskHashCode); Log.Detail("Re-using existing package assembly"); Graph.Instance.ScriptAssemblyPathname = cachedAssemblyPathname; assemblyCompileProfile.StopProfile(); return true; } else { compileReason = "package source has changed since the last compile"; } } } else { compileReason = "no previously compiled package assembly exists"; } } else { compileReason = "user has disabled package assembly caching"; } } // use the compiler in the current runtime version to build the assembly of packages var clrVersion = System.Environment.Version; var compilerVersion = System.String.Format("v{0}.{1}", clrVersion.Major, clrVersion.Minor); Log.Detail("Compiling package assembly (C# compiler {0}{1}), because {2}.", compilerVersion, Graph.Instance.ProcessState.TargetFrameworkVersion != null ? (", targetting " + Graph.Instance.ProcessState.TargetFrameworkVersion) : string.Empty, compileReason); var providerOptions = new System.Collections.Generic.Dictionary<string, string>(); providerOptions.Add("CompilerVersion", compilerVersion); if (Graph.Instance.ProcessState.RunningMono) { Log.DebugMessage("Compiling assembly for Mono"); } using (var provider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions)) { var compilerParameters = new System.CodeDom.Compiler.CompilerParameters(); compilerParameters.TreatWarningsAsErrors = true; compilerParameters.WarningLevel = 4; compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = false; if (Graph.Instance.CompileWithDebugSymbols) { compilerParameters.OutputAssembly = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Graph.Instance.MasterPackage.Name) + ".dll"; } else { compilerParameters.OutputAssembly = cachedAssemblyPathname; } var compilerOptions = "/checked+ /unsafe-"; if (Graph.Instance.CompileWithDebugSymbols) { compilerParameters.IncludeDebugInformation = true; compilerOptions += " /optimize-"; } else { compilerOptions += " /optimize+"; } compilerOptions += " /platform:anycpu"; // define strings compilerOptions += " /define:" + definitions.ToString(';'); compilerParameters.CompilerOptions = compilerOptions; if (provider.Supports(System.CodeDom.Compiler.GeneratorSupport.Resources)) { // Bam assembly // TODO: Q: why is it only for the master package? Why not all of them, which may have additional dependencies? foreach (var assembly in Graph.Instance.MasterPackage.BamAssemblies) { var assemblyFileName = System.String.Format("{0}.dll", assembly.Name); var assemblyPathName = System.IO.Path.Combine(Graph.Instance.ProcessState.ExecutableDirectory, assemblyFileName); compilerParameters.ReferencedAssemblies.Add(assemblyPathName); } // DotNet assembly foreach (var desc in Graph.Instance.MasterPackage.DotNetAssemblies) { var assemblyFileName = System.String.Format("{0}.dll", desc.Name); compilerParameters.ReferencedAssemblies.Add(assemblyFileName); } if (Graph.Instance.ProcessState.RunningMono) { compilerParameters.ReferencedAssemblies.Add("Mono.Posix.dll"); } } else { throw new Exception("C# compiler does not support Resources"); } System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(compilerParameters.OutputAssembly)); var results = Graph.Instance.CompileWithDebugSymbols ? provider.CompileAssemblyFromFile(compilerParameters, sourceCode.ToArray()) : provider.CompileAssemblyFromSource(compilerParameters, sourceCode.ToArray()); if (results.Errors.HasErrors || results.Errors.HasWarnings) { Log.ErrorMessage("Failed to compile package '{0}'. There are {1} errors.", Graph.Instance.MasterPackage.FullName, results.Errors.Count); foreach (System.CodeDom.Compiler.CompilerError error in results.Errors) { Log.ErrorMessage("\t{0}({1}): {2} {3}", error.FileName, error.Line, error.ErrorNumber, error.ErrorText); } return false; } if (!Graph.Instance.CompileWithDebugSymbols) { if (cacheAssembly) { using (var writer = new System.IO.StreamWriter(hashPathName)) { writer.WriteLine(thisHashCode); } } else { // will not throw if the file doesn't exist System.IO.File.Delete(hashPathName); } } Log.DebugMessage("Written assembly to '{0}'", compilerParameters.OutputAssembly); Graph.Instance.ScriptAssemblyPathname = compilerParameters.OutputAssembly; } assemblyCompileProfile.StopProfile(); return true; }