static Assembly CompileAssembly(string OutputAssemblyPath, List <string> SourceFileNames, List <string> ReferencedAssembies = null, List <string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false)
        {
            CompilerParameters CompileParams = new CompilerParameters();

            CompileParams.OutputAssembly = OutputAssemblyPath;

            Assembly UnrealBuildToolAssembly = Assembly.GetExecutingAssembly();

            CompileParams.ReferencedAssemblies.Add(UnrealBuildToolAssembly.Location);
            CompilerResults CompileResults;

            try
            {
                // Enable .NET 4.0 as we want modern language features like 'var'
                Dictionary <string, string> ProviderOptions = new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                };
                CSharpCodeProvider Compiler = new CSharpCodeProvider(ProviderOptions);
                CompileResults = Compiler.CompileAssemblyFromFile(CompileParams, SourceFileNames.ToArray());
            }
            catch (Exception Ex)
            {
                throw new Exception("Failed to launch compiler to compile assembly from source files '{0}' (Exception: {1})", Ex);
            }
            if (CompileResults.Errors.Count > 0)
            {
                foreach (CompilerError CurError in CompileResults.Errors)
                {
                    Console.WriteLine(CurError.ToString());
                }
                throw new Exception();
            }
            Console.WriteLine("Compile Successful");

            return(CompileResults.CompiledAssembly);
        }
示例#2
0
        private static Assembly CompileAssembly(FileReference OutputAssemblyPath, HashSet <FileReference> SourceFileNames, List <string> ReferencedAssembies, List <string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false)
        {
            TempFileCollection TemporaryFiles = new TempFileCollection();

            // Setup compile parameters
            CompilerParameters CompileParams = new CompilerParameters();
            {
                // Always compile the assembly to a file on disk, so that we can load a cached version later if we have one
                CompileParams.GenerateInMemory = false;

                // This is the full path to the assembly file we're generating
                CompileParams.OutputAssembly = OutputAssemblyPath.FullName;

                // We always want to generate a class library, not an executable
                CompileParams.GenerateExecutable = false;

                // Never fail compiles for warnings
                CompileParams.TreatWarningsAsErrors = false;

                // Set the warning level so that we will actually receive warnings -
                // doesn't abort compilation as stated in documentation!
                CompileParams.WarningLevel = 4;

                // Always generate debug information as it takes minimal time
                CompileParams.IncludeDebugInformation = true;
#if !DEBUG
                // Optimise the managed code in Development
                CompileParams.CompilerOptions += " /optimize";
#endif
                Log.TraceVerbose("Compiling " + OutputAssemblyPath);

                // Keep track of temporary files emitted by the compiler so we can clean them up later
                CompileParams.TempFiles = TemporaryFiles;

                // Warnings as errors if desired
                CompileParams.TreatWarningsAsErrors = TreatWarningsAsErrors;

                // Add assembly references
                {
                    if (ReferencedAssembies == null)
                    {
                        // Always depend on the CLR System assembly
                        CompileParams.ReferencedAssemblies.Add("System.dll");
                        CompileParams.ReferencedAssemblies.Add("System.Core.dll");
                    }
                    else
                    {
                        // Add in the set of passed in referenced assemblies
                        CompileParams.ReferencedAssemblies.AddRange(ReferencedAssembies.ToArray());
                    }

                    // The assembly will depend on this application
                    Assembly UnrealBuildToolAssembly = Assembly.GetExecutingAssembly();
                    CompileParams.ReferencedAssemblies.Add(UnrealBuildToolAssembly.Location);

                    // The assembly will depend on the utilities assembly. Find that assembly
                    // by looking for the one that contains a common utility class
                    Assembly UtilitiesAssembly = Assembly.GetAssembly(typeof(FileReference));
                    CompileParams.ReferencedAssemblies.Add(UtilitiesAssembly.Location);
                }

                // Add preprocessor definitions
                if (PreprocessorDefines != null && PreprocessorDefines.Count > 0)
                {
                    CompileParams.CompilerOptions += " /define:";
                    for (int DefinitionIndex = 0; DefinitionIndex < PreprocessorDefines.Count; ++DefinitionIndex)
                    {
                        if (DefinitionIndex > 0)
                        {
                            CompileParams.CompilerOptions += ";";
                        }
                        CompileParams.CompilerOptions += PreprocessorDefines[DefinitionIndex];
                    }
                }

                // @todo: Consider embedding resources in generated assembly file (version/copyright/signing)
            }

            // Create the output directory if it doesn't exist already
            DirectoryInfo DirInfo = new DirectoryInfo(OutputAssemblyPath.Directory.FullName);
            if (!DirInfo.Exists)
            {
                try
                {
                    DirInfo.Create();
                }
                catch (Exception Ex)
                {
                    throw new BuildException(Ex, "Unable to create directory '{0}' for intermediate assemblies (Exception: {1})", OutputAssemblyPath, Ex.Message);
                }
            }

            // Compile the code
            CompilerResults CompileResults;
            try
            {
                Dictionary <string, string> ProviderOptions = new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                };
                CSharpCodeProvider Compiler = new CSharpCodeProvider(ProviderOptions);
                CompileResults = Compiler.CompileAssemblyFromFile(CompileParams, SourceFileNames.Select(x => x.FullName).ToArray());
            }
            catch (Exception Ex)
            {
                throw new BuildException(Ex, "Failed to launch compiler to compile assembly from source files:\n  {0}\n(Exception: {1})", String.Join("\n  ", SourceFileNames), Ex.ToString());
            }

            // Display compilation warnings and errors
            if (CompileResults.Errors.Count > 0)
            {
                Log.TraceInformation("While compiling {0}:", OutputAssemblyPath);
                foreach (CompilerError CurError in CompileResults.Errors)
                {
                    Log.WriteLine(0, CurError.IsWarning? LogEventType.Warning : LogEventType.Error, LogFormatOptions.NoSeverityPrefix, "{0}", CurError.ToString());
                }
                if (CompileResults.Errors.HasErrors || TreatWarningsAsErrors)
                {
                    throw new BuildException("Unable to compile source files.");
                }
            }

            // Grab the generated assembly
            Assembly CompiledAssembly = CompileResults.CompiledAssembly;
            if (CompiledAssembly == null)
            {
                throw new BuildException("UnrealBuildTool was unable to compile an assembly for '{0}'", SourceFileNames.ToString());
            }

            // Clean up temporary files that the compiler saved
            TemporaryFiles.Delete();

            return(CompiledAssembly);
        }
        /*
         * Compiles an assembly from source files
         */
        private static Assembly CompileAssembly(string OutputAssemblyPath, List <string> SourceFileNames, List <string> ReferencedAssembies, List <string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false)
        {
            var TemporaryFiles = new TempFileCollection();

            // Setup compile parameters
            var CompileParams = new CompilerParameters();
            {
                // Always compile the assembly to a file on disk, so that we can load a cached version later if we have one
                CompileParams.GenerateInMemory = false;

                // This is the full path to the assembly file we're generating
                CompileParams.OutputAssembly = OutputAssemblyPath;

                // We always want to generate a class library, not an executable
                CompileParams.GenerateExecutable = false;

                // Always fail compiles for warnings
                CompileParams.TreatWarningsAsErrors = true;

                // Always generate debug information as it takes minimal time
                CompileParams.IncludeDebugInformation = true;
#if !DEBUG
                // Optimise the managed code in Development
                CompileParams.CompilerOptions += " /optimize";
#endif
                Log.TraceVerbose("Compiling " + OutputAssemblyPath);

                // Keep track of temporary files emitted by the compiler so we can clean them up later
                CompileParams.TempFiles = TemporaryFiles;

                // Warnings as errors if desired
                CompileParams.TreatWarningsAsErrors = TreatWarningsAsErrors;

                // Add assembly references
                {
                    if (ReferencedAssembies == null)
                    {
                        // Always depend on the CLR System assembly
                        CompileParams.ReferencedAssemblies.Add("System.dll");
                    }
                    else
                    {
                        // Add in the set of passed in referenced assemblies
                        CompileParams.ReferencedAssemblies.AddRange(ReferencedAssembies.ToArray());
                    }

                    // The assembly will depend on this application
                    var UnrealBuildToolAssembly = Assembly.GetExecutingAssembly();
                    CompileParams.ReferencedAssemblies.Add(UnrealBuildToolAssembly.Location);
                }

                // Add preprocessor definitions
                if (PreprocessorDefines != null && PreprocessorDefines.Count > 0)
                {
                    CompileParams.CompilerOptions += " /define:";
                    for (int DefinitionIndex = 0; DefinitionIndex < PreprocessorDefines.Count; ++DefinitionIndex)
                    {
                        if (DefinitionIndex > 0)
                        {
                            CompileParams.CompilerOptions += ";";
                        }
                        CompileParams.CompilerOptions += PreprocessorDefines[DefinitionIndex];
                    }
                }

                // @todo: Consider embedding resources in generated assembly file (version/copyright/signing)
            }

            // Create the output directory if it doesn't exist already
            DirectoryInfo DirInfo = new DirectoryInfo(Path.GetDirectoryName(OutputAssemblyPath));
            if (!DirInfo.Exists)
            {
                try
                {
                    DirInfo.Create();
                }
                catch (Exception Ex)
                {
                    throw new BuildException(Ex, "Unable to create directory '{0}' for intermediate assemblies (Exception: {1})", OutputAssemblyPath, Ex.Message);
                }
            }

            // Compile the code
            CompilerResults CompileResults;
            try
            {
                // Enable .NET 4.0 as we want modern language features like 'var'
                var ProviderOptions = new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                };
                var Compiler = new CSharpCodeProvider(ProviderOptions);
                CompileResults = Compiler.CompileAssemblyFromFile(CompileParams, SourceFileNames.ToArray());
            }
            catch (Exception Ex)
            {
                throw new BuildException(Ex, "Failed to launch compiler to compile assembly from source files '{0}' (Exception: {1})", SourceFileNames.ToString(), Ex.Message);
            }

            // Display compilation errors
            if (CompileResults.Errors.Count > 0)
            {
                Log.TraceInformation("Errors detected while compiling {0}:", OutputAssemblyPath);
                foreach (var CurError in CompileResults.Errors)
                {
                    Log.TraceInformation(CurError.ToString());
                }
                throw new BuildException("UnrealBuildTool encountered an error while compiling source files");
            }

            // Grab the generated assembly
            Assembly CompiledAssembly = CompileResults.CompiledAssembly;
            if (CompiledAssembly == null)
            {
                throw new BuildException("UnrealBuildTool was unable to compile an assembly for '{0}'", SourceFileNames.ToString());
            }

            // Clean up temporary files that the compiler saved
            TemporaryFiles.Delete();

            return(CompiledAssembly);
        }