CompileAssemblyFromFile() public method

public CompileAssemblyFromFile ( CompilerParameters options ) : CompilerResults
options CompilerParameters
return CompilerResults
Example #1
0
        internal static bool CompileCode(CodeDomProvider provider, Assembly userAssembly, string[] generatedSrcFiles)
        {
            // Parameters for compilation
            String[] referenceAssemblies = {
                "System.dll",
                "System.ServiceModel.dll",
                "System.Configuration.dll",
                userAssembly.Location
                                            };
            string compiledFile = "temp.dll";

            CompilerParameters cp = new CompilerParameters(referenceAssemblies, compiledFile, false);
            cp.GenerateExecutable = false;

            Console.WriteLine("Compiling files: ");
            foreach (string fileName in generatedSrcFiles)
            {
                Console.WriteLine(fileName);
            }
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, generatedSrcFiles);

            if (cr.Errors.Count > 0)
            {
                Console.WriteLine("Please investigate. The tool encountered errors during compilation");
                foreach (CompilerError ce in cr.Errors)
                    Console.WriteLine(ce.ToString());
                return false;
            }
            else
            {
                Console.WriteLine("No errors encountered during compilation");
                File.Delete(compiledFile);
            }
            return true;
        }
Example #2
0
 /// <summary>
 /// Compile a set of source files with a specific provider
 /// </summary>
 /// <param name="files">Array of source files</param>
 /// <param name="referencedAssemblies">Array of referenced assemblies</param>
 /// <param name="outputFilePath">Output assembly file path</param>
 /// <param name="provider">Code dom provider</param>
 /// <returns>Compiler results</returns>
 public static CompilerResults Compile(List<string> files, List<string> referencedAssemblies, List<string> embeddedResourcesFiles, string outputFilePath, CodeDomProvider provider)
 {
     // Configure parameters
     CompilerParameters parms = new CompilerParameters();
     parms.GenerateExecutable = false;
     parms.GenerateInMemory = false;
     parms.OutputAssembly = outputFilePath;
     parms.IncludeDebugInformation = false;
     if (provider.Supports(GeneratorSupport.Resources))
         parms.EmbeddedResources.AddRange(embeddedResourcesFiles.ToArray());
     parms.ReferencedAssemblies.AddRange(referencedAssemblies.ToArray());
     // Compile
     return provider.CompileAssemblyFromFile(parms, files.ToArray());
 }
Example #3
0
        private static Type CreateCodeGeneratorType(System.CodeDom.Compiler.CodeDomProvider compilerProvider, string resourceName, string typeName)
        {
            string sourceCode = null;

            using (Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(sourceStream))
                {
                    sourceCode = reader.ReadToEnd();
                }

            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.CompilerOptions    = "/d:PREPROCESSED_TEMPLATE";
            compilerParams.GenerateInMemory   = true;
            compilerParams.GenerateExecutable = false;
            // grab the assemblies by location so that we don't compile against one that we didn't reference
            compilerParams.ReferencedAssemblies.AddRange(new string[] {
                typeof(System.CodeDom.Compiler.CodeDomProvider).Assembly.Location,                      // System.dll
                typeof(System.Linq.Enumerable).Assembly.Location,                                       // System.Core.dll
                typeof(System.Data.Objects.ObjectContext).Assembly.Location,                            // System.Data.Entity.dll
                typeof(System.Data.Entity.Design.EntityCodeGenerator).Assembly.Location,                // System.Data.Entity.Design.dll
                typeof(System.Data.DbType).Assembly.Location,                                           // System.Data.dll
                typeof(System.Xml.XmlAttribute).Assembly.Location,                                      // System.Xml.dll
                typeof(System.Xml.Linq.XElement).Assembly.Location,                                     // System.Xml.Linq.dll
            });

#if !ENABLE_TEMPLATE_DEBUGGING
            CompilerResults results = compilerProvider.CompileAssemblyFromSource(compilerParams, sourceCode);
#else
            // enables debugging
            compilerParams.GenerateInMemory        = false;
            compilerParams.IncludeDebugInformation = true;
            string baseName = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".";
            compilerParams.OutputAssembly = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Assembly.dll");
            string sourceFileName = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Source." + compilerProvider.FileExtension);
            File.WriteAllText(sourceFileName, sourceCode);
            CompilerResults results = compilerProvider.CompileAssemblyFromFile(compilerParams, sourceFileName);
#warning DO NOT CHECK IN LIKE THIS, Dynamic Assembly Debugging is enabled
#endif


            if (results.Errors.HasErrors)
            {
                string message = results.Errors.OfType <CompilerError>().Aggregate(string.Empty, (accumulated, input) => accumulated == string.Empty ? input.ToString() : accumulated + Environment.NewLine + input.ToString());
                throw EDesignUtil.InvalidOperation(message);
            }

            return(results.CompiledAssembly.GetType(typeName));
        }
        private CompilerResults CompileAll(CodeDomProvider provider, List<string> sourceFile)
        {
            String lib = System.Configuration.ConfigurationManager.AppSettings["CSFolder"] + @"/CS4BBLib.dll";
            if (!File.Exists(lib))
                throw new ArgumentException("Unable to find '" + lib + "' Please make sure that the library exists. ");

            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add(lib);

            cp.TreatWarningsAsErrors = true;

            CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile.ToArray());
            return cr;
        }
Example #5
0
        Assembly CompileFromSource(CodeDomProvider provider, string searchPattern)
        {
            var compilerParameters = new CompilerParameters();

            compilerParameters.GenerateExecutable = false;

            // Necessary for stack trace line numbers etc
            compilerParameters.IncludeDebugInformation = true;
            compilerParameters.GenerateInMemory = false;

            #if RELEASE
            if(!compilationParameters.ForceDebugInformation)
            {
                compilerParameters.GenerateInMemory = true;
                compilerParameters.IncludeDebugInformation = false;
            }
            #endif

            if(!compilerParameters.GenerateInMemory)
            {
                var assemblyPath = Path.Combine(PathUtils.TempFolder, string.Format("CompiledScripts_{0}.dll", searchPattern.Replace("*.", "")));

                if(File.Exists(assemblyPath))
                {
                    try
                    {
                        File.Delete(assemblyPath);
                    }
                    catch(Exception ex)
                    {
                        if(ex is UnauthorizedAccessException || ex is IOException)
                            assemblyPath = Path.ChangeExtension(assemblyPath, "_" + Path.GetExtension(assemblyPath));
                        else
                            throw;
                    }
                }

                compilerParameters.OutputAssembly = assemblyPath;
            }

            var scripts = new List<string>();
            var scriptsDirectory = PathUtils.ScriptsFolder;

            if(Directory.Exists(scriptsDirectory))
            {
                foreach (var script in Directory.GetFiles(scriptsDirectory, searchPattern, SearchOption.AllDirectories))
                    scripts.Add(script);
            }
            else
                Debug.LogAlways("Scripts directory could not be located");

            CompilerResults results;
            using(provider)
            {
                var referenceHandler = new AssemblyReferenceHandler();
                compilerParameters.ReferencedAssemblies.AddRange(referenceHandler.GetRequiredAssembliesFromFiles(scripts));

                results = provider.CompileAssemblyFromFile(compilerParameters, scripts.ToArray());
            }

            return ScriptCompiler.ValidateCompilation(results);
        }
Example #6
0
        private static CompilerResults CompileLanguage(string[] sourceFiles, CodeDomProvider provider, CompilerParameters options)
        {
            options.EmbeddedResources.Clear();
            options.LinkedResources.Clear();

            int codeFileCount = 0;
            List<String> files = new List<String>();

            foreach (string file in sourceFiles) {
                string ext = Path.GetExtension(file);
                if (String.Compare(ext, "." + provider.FileExtension, StringComparison.InvariantCultureIgnoreCase) == 0) {
                    files.Add(file);
                    codeFileCount++;
                }
                else if (ext.ToLowerInvariant() == ".resx") {
                    options.EmbeddedResources.Add(file);
                }
            }

            if (codeFileCount > 0) {
                try {
                    return provider.CompileAssemblyFromFile(options, files.ToArray());
                }
                catch (Exception ex) {
                    Trace.WriteLine("Unexpected error during compilation:\n" + ex.ToString(), "Runtime");
                }
            }

            return null;
        }
Example #7
0
        /// <summary>
        /// Function to compile .Net C#/VB source codes at runtime 
        /// Adapted from:
        /// (http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Compile-C-or-VB-source-code-run-time.html)
        /// </summary>
        /// <param name="codeProvider">Base class for compiler provider</param>
        /// <param name="sourceCode">C# or VB source code as a string</param>
        /// <param name="sourceFile">External file containing C# or VB source code</param>
        /// <param name="exeFile">File path to create external executable file</param>
        /// <param name="assemblyName">File path to create external assembly file</param>
        /// <param name="resourceFiles">Required resource files to compile the code</param>
        /// 
        /// <param name="errors">String variable to store any errors occurred during the process</param>
        /// <returns>Return TRUE if successfully compiled the code, else return FALSE</returns>
        public static bool CompileCode(CodeDomProvider codeProvider, string sourceCode, string sourceFile, 
                           string exeFile, string assemblyName, string[] resourceFiles, string[] referencedAssemblies,
                           out string errors, out CompilerResults compilerResults)
        {
            // Define parameters to invoke a compiler
            CompilerParameters compilerParameters = new CompilerParameters();

            if (exeFile != null)
            {
                // Set the assembly file name to generate.
                compilerParameters.OutputAssembly = exeFile;
                // Generate an executable instead of a class library.
                compilerParameters.GenerateExecutable = true;
                compilerParameters.GenerateInMemory = false;
            }
            else if (assemblyName != null)
            {
                // Set the assembly file name to generate.
                compilerParameters.OutputAssembly = assemblyName;
                // Generate a class library instead of an executable.
                compilerParameters.GenerateExecutable = false;
                compilerParameters.GenerateInMemory = false;
            }
            else
            {
                // Generate an in-memory class library instead of an executable.
                compilerParameters.GenerateExecutable = false;
                compilerParameters.GenerateInMemory = true;
            }
            // Generate debug information.
            compilerParameters.IncludeDebugInformation = true;
            // Should start displaying warnings.
            compilerParameters.WarningLevel = 2;
            // Set whether to treat all warnings as errors.
            compilerParameters.TreatWarningsAsErrors = false;
            // Set compiler argument to optimize output.
            compilerParameters.CompilerOptions = "/optimize";
            // Add referenced assemblies
            if (referencedAssemblies != null)
                compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies);
            // Set a temporary files collection.
            // The TempFileCollection stores the temporary files
            // generated during a build in the current directory,
            // and does not delete them after compilation.
            //compilerParameters.TempFiles = new TempFileCollection(".", true);
            compilerParameters.TempFiles = new TempFileCollection(".", false);

            if (resourceFiles != null && resourceFiles.Length > 0)
            {
                foreach (string _ResourceFile in resourceFiles)
                {
                    // Set the embedded resource file of the assembly.
                    compilerParameters.EmbeddedResources.Add(_ResourceFile);
                }
            }
            try
            {
                // Invoke compilation
                if (sourceFile != null && System.IO.File.Exists(sourceFile))
                    // source code in external file
                    compilerResults = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFile);
                else
                    // source code pass as a string
                    compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);

                if (compilerResults.Errors.Count > 0)
                {
                    // Return compilation errors
                    errors = "";
                    foreach (CompilerError compErr in compilerResults.Errors)
                    {
                        errors += "Line number " + compErr.Line +
                                  ", Column number " + compErr.Column +
                                    ", Error Number: " + compErr.ErrorNumber +
                                    ", '" + compErr.ErrorText + ";\r\n\r\n";
                    }
                    // Return the results of compilation - Failed
                    return false;
                }
                else
                {
                    // no compile errors
                    errors = null;
                }
            }
            catch (Exception exception)
            {
                // Error occurred when trying to compile the code
                errors = exception.Message;
                compilerResults = null;
                return false;
            }
            // Return the results of compilation - Success
            return true;
        }
        public static bool CompileCode(CodeDomProvider provider, String[] sourceFile, String exeFile)
        {

            CompilerParameters cp = new CompilerParameters();

            // Generate an executable instead of 
            // a class library.
            cp.GenerateExecutable = true;

            // Set the assembly file name to generate.
            cp.OutputAssembly = exeFile;

            // Generate debug information.
            cp.IncludeDebugInformation = true;

            // Add an assembly reference.
            cp.ReferencedAssemblies.Add("Onyx.JS.api.dll");

            // Save the assembly as a physical file.
            cp.GenerateInMemory = false;

            // Set the level at which the compiler 
            // should start displaying warnings.
            cp.WarningLevel = 3;

            // Set whether to treat all warnings as errors.
            cp.TreatWarningsAsErrors = false;

            // Set compiler argument to optimize output.
            //cp.CompilerOptions = "/optimize";

            // Set a temporary files collection.
            // The TempFileCollection stores the temporary files
            // generated during a build in the current directory,
            // and does not delete them after compilation.
            cp.TempFiles = new TempFileCollection(".", true);

            //if (provider.Supports(GeneratorSupport.EntryPointMethod))
            //{
            //    // Specify the class that contains 
            //    // the main method of the executable.
            //    cp.MainClass = "Samples.Class1";
            //}

            if (Directory.Exists("Resources"))
            {
                if (provider.Supports(GeneratorSupport.Resources))
                {
                    // Set the embedded resource file of the assembly.
                    // This is useful for culture-neutral resources,
                    // or default (fallback) resources.
                    cp.EmbeddedResources.Add("Resources\\Default.resources");

                    // Set the linked resource reference files of the assembly.
                    // These resources are included in separate assembly files,
                    // typically localized for a specific language and culture.
                    cp.LinkedResources.Add("Resources\\nb-no.resources");
                }
            }

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);

            if (cr.Errors.Count > 0)
            {
                // Display compilation errors.
                Console.WriteLine("Errors building {0} into {1}",
                    sourceFile, cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    Console.WriteLine("  {0}", ce.ToString());
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("Source {0} built into {1} successfully.",
                    sourceFile, cr.PathToAssembly);
                Console.WriteLine("{0} temporary files created during the compilation.",
                    cp.TempFiles.Count.ToString());

            }

            // Return the results of compilation.
            if (cr.Errors.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        protected Assembly CompileScript(string[] Source, CodeDomProvider Provider, IEnumerable<string> ReferencedAssemblies)
        {
            if (Source.Length == 0)
            {
                WriteInformation("ScriptCompiler", "No scripts to compile");
                return null;
            }

            CompilerResults results;
            CompilerParameters parms = getCompilerParameters(ReferencedAssemblies);
            results = Provider.CompileAssemblyFromFile(parms, Source);
            int tempCount = 0;
            if (results.Errors.Count > 0)
            {
                foreach (CompilerError error in results.Errors)
                {
                    if (error.IsWarning == false)
                    {
                        //throw new CompileException(string.Format("Error {0} on file {1} on line {2}", error.ErrorText, error.FileName, error.Line))
                        WriteError("ScriptCompiler", "Error {0} on file {1} on line {2}", error.ErrorText, error.FileName, error.Line);
                        tempCount++;
                    }
                    else
                    {
                        WriteWarning("ScriptCompiler", "Error {0} on file {1} on line {2}", error.ErrorText, error.FileName, error.Line);
                    }
                }

                if (tempCount > 0)
                    return null;
            }
            else
            {
                WriteInformation("ScriptCompiler", "Scripts compiled no errors");
            }

            return results.CompiledAssembly;
        }
Example #10
0
        private void Compile(bool file)
        {
            System.CodeDom.Compiler.CodeDomProvider CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");

            System.CodeDom.Compiler.CompilerParameters CompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
            CompilerParameters.ReferencedAssemblies.Add("System.dll");
            CompilerParameters.ReferencedAssemblies.Add("System.Data.dll");
            CompilerParameters.ReferencedAssemblies.Add("System.Xml.dll");
            CompilerParameters.ReferencedAssemblies.Add("System.Linq.dll");
            CompilerParameters.ReferencedAssemblies.Add("RakNetSwig.dll");
            CompilerParameters.ReferencedAssemblies.Add("GMP_Server.exe");


            foreach (String str in Program.serverOptions.AdditionalLibs)
            {
                CompilerParameters.ReferencedAssemblies.Add(str);
            }



            CompilerParameters.CompilerOptions = "/t:library";///debug:full
            for (int i = 0; i < Program.serverOptions.AdditionalSymbols.Count; i++)
            {
                String str = Program.serverOptions.AdditionalSymbols[i];
                if (i == 0)
                {
                    CompilerParameters.CompilerOptions += "/define: ";
                }
                CompilerParameters.CompilerOptions += str;
                if (i != Program.serverOptions.AdditionalLibs.Count - 1)
                {
                    CompilerParameters.CompilerOptions += ";";
                }
            }

            CompilerParameters.IncludeDebugInformation = true;

            if (!file)
            {
                CompilerParameters.GenerateInMemory = true;
            }
            else
            {
                CompilerParameters.GenerateInMemory = false;
                CompilerParameters.OutputAssembly   = "scripts/_compiled/ServerScripts.dll";
            }

            List <String> fileList = new List <string>();

            GetFileList(fileList, "scripts/server");
            //getFileList(fileList, "scripts/both");

            System.CodeDom.Compiler.CompilerResults CompilerResults = CodeDomProvider.CompileAssemblyFromFile(CompilerParameters, fileList.ToArray());
            if (CompilerResults.Errors.Count > 0)
            {
                foreach (CompilerError col in CompilerResults.Errors)
                {
                    Log.Logger.log(Log.Logger.LOG_ERROR, col.FileName + ":" + col.Line + " \t" + col.ErrorText);
                }
                return;
            }


            m_Assembly = CompilerResults.CompiledAssembly;
        }
Example #11
0
        private static Assembly CompileInternal(String outputAssembly, IEnumerable<String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp)
        {
            var options = new CompilerParameters();
            foreach (var str in references)
            {
                options.ReferencedAssemblies.Add(str);
            }
            options.WarningLevel = 4;

            CompilerResults results = null;
            if (Debug)
            {
                #region 调试状态,把生成的类文件和最终dll输出到XTemp目录下
                var tempPath = XTrace.TempPath;
                //if (!String.IsNullOrEmpty(outputAssembly)) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.Equals(".dll")) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));

                if (!String.IsNullOrEmpty(tempPath) && !Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);

                var files = new List<String>();
                foreach (var item in tmp.Templates)
                {
                    if (item.Included) continue;

                    String name = item.Name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ? item.Name : item.ClassName;
                    // 猜测后缀
                    Int32 p = name.LastIndexOf("_");
                    if (p > 0 && name.Length - p <= 5)
                        name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1);
                    else if (!name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                        name += ".cs";

                    name = Path.Combine(tempPath, name);
                    File.WriteAllText(name, item.Source, Encoding.UTF8);

                    files.Add(name);
                }
                #endregion
                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.Equals(".dll"))
                {
                    options.TempFiles = new TempFileCollection(tempPath, false);
                    options.OutputAssembly = Path.Combine(tempPath, outputAssembly);
                    options.GenerateInMemory = true;
                    options.IncludeDebugInformation = true;
                }

                results = provider.CompileAssemblyFromFile(options, files.ToArray());
            }
            else
            {
                List<String> sources = new List<String>();
                foreach (var item in tmp.Templates)
                {
                    sources.Add(item.Source);
                }

                options.GenerateInMemory = true;

                results = provider.CompileAssemblyFromSource(options, sources.ToArray());
            }

            #region 编译错误处理
            if (results.Errors.Count > 0)
            {
                Errors.AddRange(results.Errors);

                var sb = new StringBuilder();
                CompilerError err = null;
                foreach (CompilerError error in results.Errors)
                {
                    error.ErrorText = error.ErrorText;
                    //if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile;

                    if (!error.IsWarning)
                    {
                        String msg = error.ToString();
                        if (sb.Length < 1)
                        {
                            String code = null;
                            // 屏蔽因为计算错误行而导致的二次错误
                            try
                            {
                                code = tmp.FindBlockCode(error.FileName, error.Line);
                            }
                            catch { }
                            if (code != null)
                            {
                                msg += Environment.NewLine;
                                msg += code;
                            }
                            err = error;
                        }
                        else
                            sb.AppendLine();

                        sb.Append(msg);
                    }
                }
                if (sb.Length > 0)
                {
                    TemplateException ex = new TemplateException(sb.ToString());
                    ex.Error = err;
                    throw ex;
                }
            }
            else
            {
                try
                {
                    options.TempFiles.Delete();
                }
                catch { }
            }
            #endregion

            if (!results.Errors.HasErrors)
            {
                try
                {
                    return results.CompiledAssembly;
                }
                catch { }
            }
            return null;
        }
Example #12
0
		/// <summary>
		/// Compiles a file to an assembly using specified compiler.
		/// </summary>
		Assembly Compile( PluginInfo pi, CodeDomProvider cdp )
		{
			// Compile
			//ICodeCompiler compiler = cdp.CreateCompiler();

			if(cdp is Microsoft.JScript.JScriptCodeProvider)
				// JSCript doesn't support unsafe code
				cp.CompilerOptions = "";
			else
				cp.CompilerOptions = "/unsafe";

			// Add references
			cp.ReferencedAssemblies.Clear();
			foreach( string reference in m_worldWindReferencesList)
				cp.ReferencedAssemblies.Add(reference);

			// Add reference to core functions for VB.Net users 
			if(cdp is Microsoft.VisualBasic.VBCodeProvider)
				cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");

			// Add references specified in the plugin
			foreach( string reference in pi.References.Split(','))
				AddCompilerReference( pi.FullPath, reference.Trim() );

			CompilerResults cr = cdp.CompileAssemblyFromFile( cp, pi.FullPath );
			if(cr.Errors.HasErrors || cr.Errors.HasWarnings)
			{
				// Handle compiler errors
				StringBuilder error = new StringBuilder();
				foreach (CompilerError err in cr.Errors)
				{
					string type = (err.IsWarning ? "Warning" : "Error");
					if(error.Length>0)
						error.Append(Environment.NewLine);
					error.AppendFormat("{0} {1}: Line {2} Column {3}: {4}", type, err.ErrorNumber, err.Line, err.Column, err.ErrorText );
				}
                Log.Write(Log.Levels.Error, LogCategory, error.ToString());
                if(cr.Errors.HasErrors)
				    throw new Exception( error.ToString() );
			}

			// Success, return our new assembly
			return cr.CompiledAssembly;
		}
Example #13
0
        Assembly CompileFromSource(CodeDomProvider provider, string searchPattern)
        {
            var compilerParameters = new CompilerParameters();

            compilerParameters.GenerateExecutable = false;

            // Necessary for stack trace line numbers etc
            compilerParameters.IncludeDebugInformation = true;
            compilerParameters.GenerateInMemory = false;

            #if RELEASE
            if(!compilationParameters.ForceDebugInformation)
            {
                compilerParameters.GenerateInMemory = true;
                compilerParameters.IncludeDebugInformation = false;
            }
            #endif

            if (!compilerParameters.GenerateInMemory)
            {
                var assemblyPath = Path.Combine(ProjectSettings.TempDirectory, string.Format("CompiledScripts_{0}.dll", searchPattern.Replace("*.", "")));

                if (File.Exists(assemblyPath))
                {
                    try
                    {
                        File.Delete(assemblyPath);
                    }
                    catch (Exception ex)
                    {
                        if (ex is UnauthorizedAccessException || ex is IOException)
                        {
                            int num = 1;
                            var split = assemblyPath.Split(new string[] { ".dll" }, StringSplitOptions.None);

                            while (File.Exists(assemblyPath))
                            {
                                assemblyPath = split.First() + num.ToString() + ".dll";
                                num++;
                            }
                        }
                        else
                            throw;
                    }
                }

                compilerParameters.OutputAssembly = assemblyPath;
            }

            var scripts = new List<string>();
            var scriptsDirectory = CryPak.ScriptsFolder;

            CVar cvar;
            if (CVar.TryGet("mono_scriptDirectory", out cvar))
            {
                var alternateScriptsDir = cvar.String;
                if (!string.IsNullOrEmpty(alternateScriptsDir))
                    scriptsDirectory = alternateScriptsDir;
            }

            if (Directory.Exists(scriptsDirectory))
            {
                foreach (var script in Directory.GetFiles(scriptsDirectory, searchPattern, SearchOption.AllDirectories))
                    scripts.Add(script);
            }
            else
                Debug.LogAlways("Scripts directory could not be located");

            if (scripts.Count == 0)
                return null;

            CompilerResults results;
            using (provider)
            {
                var referenceHandler = new AssemblyReferenceHandler();
                compilerParameters.ReferencedAssemblies.AddRange(referenceHandler.GetRequiredAssembliesFromFiles(scripts));

                results = provider.CompileAssemblyFromFile(compilerParameters, scripts.ToArray());
            }

            return ValidateCompilation(results);
        }
Example #14
0
		private string CompileModule(
			CodeDomProvider codeProvider, string targetDirectory, List<AspViewFile> files,
			ReferencedAssembly[] references, bool createAssembly, string[] modulesToAdd)
		{
			string prefix = string.IsNullOrEmpty(options.GeneratedAssemblyNamePrefix) ? null : options.GeneratedAssemblyNamePrefix + ".";

			if (!createAssembly)
			{
				parameters.CompilerOptions = "/t:module";
				parameters.OutputAssembly = Path.Combine(targetDirectory,
					string.Format("{0}CompiledViews.{1}.netmodule", prefix, codeProvider.FileExtension));
			}
			else
				parameters.OutputAssembly = Path.Combine(targetDirectory, prefix + "CompiledViews.dll");

			List<ReferencedAssembly> actualReferences = new List<ReferencedAssembly>();
			if (options.References != null)
				actualReferences.AddRange(options.References);
			if (references != null)
				actualReferences.AddRange(references);

			foreach (ReferencedAssembly reference in actualReferences)
			{
				string assemblyName = reference.Name;
				if (reference.Source == ReferencedAssembly.AssemblySource.BinDirectory)
					assemblyName = Path.Combine(targetDirectory, assemblyName);
				parameters.CompilerOptions += " /r:\"" + assemblyName + "\"";
			}

			if (modulesToAdd != null && modulesToAdd.Length > 0)
			{
				StringBuilder sb = new StringBuilder();
				sb.Append(" /addmodule: ");
				foreach (string moduleToAdd in modulesToAdd)
					sb.Append(Path.Combine(targetDirectory, moduleToAdd));
				parameters.CompilerOptions += "\"" + sb.ToString() + "\"";
			}

			CompilerResults results;
			if (options.KeepTemporarySourceFiles)
			{
				string targetTemporarySourceFilesDirectory = Path.Combine(targetDirectory, options.TemporarySourceFilesDirectory);
				List<string> fileNames = new List<string>(files.Count);
				foreach (AspViewFile file in files)
					fileNames.Add(Path.Combine(targetTemporarySourceFilesDirectory, file.FileName));
				results = codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());
			}
			else
			{
				List<string> sources = new List<string>(files.Count);
				foreach (AspViewFile file in files)
					sources.Add(file.ConcreteClass);
				results = codeProvider.CompileAssemblyFromSource(parameters, sources.ToArray());
			}
			if (results.Errors.Count > 0)
			{
				StringBuilder message = new StringBuilder();
				foreach (CompilerError err in results.Errors)
					message.AppendLine(err.ToString());
				throw new Exception(string.Format(
					"Error while compiling'':\r\n{0}",
					message.ToString()));
			}
			return results.PathToAssembly;
		}
Example #15
0
        ///<remarks>Brendan Ingram has greatly improved this method.</remarks>		
        private static object LoadClass(CodeDomProvider codeProvider, string targetClassName, string source, bool sourceIsString)
        {
            CompilerParameters compilerParameters = new CompilerParameters();
            compilerParameters.GenerateExecutable = false;
            compilerParameters.GenerateInMemory = Compilation.GenerateInMemoryAssembly;
            compilerParameters.IncludeDebugInformation = true;
            compilerParameters.TreatWarningsAsErrors = false;
            compilerParameters.CompilerOptions = compilerOptions;

            // Chuck Cross has vastly improved the loading of NxBRE DLL reference mechanism
            bool nxbreAssemblyLoaded = false;

            // Add all implicitly referenced assemblies
            if ((ReferenceLinkMode == ReferenceLinkModes.CurrentDomain) || (ReferenceLinkMode == ReferenceLinkModes.Full)) {
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
                    // do not add AssemblyBuilders (bug 1482753), thanks to Bob Brumfield
                    // handle .NET4 dynamic assemblies correctly, thanks to Nich
                     if (!(assembly is AssemblyBuilder) && (assembly.ManifestModule.GetType().Namespace != "System.Reflection.Emit")) {
                        AddReferencedAssembly(compilerParameters, assembly.Location);
                        if(assembly.ManifestModule.ScopeName.Equals(NXBRE_DLL)) nxbreAssemblyLoaded = true;
                    }
                }
            }

            // Add NxBRE DLL reference only if not already added through implicit references.
            if (!nxbreAssemblyLoaded &&
                ((ReferenceLinkMode == ReferenceLinkModes.NxBRE) || (ReferenceLinkMode == ReferenceLinkModes.Full))) {

                AddReferencedAssembly(compilerParameters, NxBREAssemblyLocation);
            }

            // Add any extra DLL listed in the application configuration
            String extraReferences = Parameter.GetString("extraReferences");
            if (extraReferences != null) {
                foreach(String dllToReference in extraReferences.Split(';')) {
                    AddReferencedAssembly(compilerParameters, dllToReference);
                }
            }

            CompilerResults cr;

            if (sourceIsString) {
                cr = codeProvider.CompileAssemblyFromSource(compilerParameters, source);
            }
            else {
                cr = codeProvider.CompileAssemblyFromFile(compilerParameters, source);
            }

            if (cr.Errors.Count != 0) {
                throw new BREException(GetCompilerErrors(cr));
            }

            // Marcin Kielar - zorba128
            // Under some (strange?) conditions, compilation finishes without errors,
            // but assembly cannot be loaded:
            //  - any of Assembly's methods (here - GetTypes) throws exception
            //  - CreateInstance returns null
            try {
                cr.CompiledAssembly.GetTypes();
            }
            catch(Exception e)
            {
                throw new BREException("Unable to create evaluator class instance - assembly loading problem", e);
            }

            object evaluatorInstance = cr.CompiledAssembly.CreateInstance(targetClassName);

            if(evaluatorInstance == null) {
                throw new BREException("Unable to create evaluator class instance");
            }

            return evaluatorInstance;
        }
Example #16
0
        public static bool CompileCode(CodeDomProvider provider,    String sourceFile,List<string> filesToEmbed,    String exeFile)
        {
            CompilerParameters cp = new CompilerParameters();

            // Generate an executable instead of
            // a class library.
            cp.GenerateExecutable = true;

            // Set the assembly file name to generate.
            cp.OutputAssembly = exeFile;

            // Generate debug information.
            cp.IncludeDebugInformation = true;

            // Add an assembly reference.
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add("mscorlib.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");

            // Save the assembly as a physical file.
            cp.GenerateInMemory = false;

            // Set the level at which the compiler
            // should start displaying warnings.
            cp.WarningLevel = 3;

            // Set whether to treat all warnings as errors.
            cp.TreatWarningsAsErrors = false;

            // Set compiler argument to optimize output.
            cp.CompilerOptions = "/debug-  /optimize+ /target:winexe";// "/optimize";

            // Set a temporary files collection.
            // The TempFileCollection stores the temporary files
            // generated during a build in the current directory,
            // and does not delete them after compilation.
            cp.TempFiles = new TempFileCollection(".", true);

            if (provider.Supports(GeneratorSupport.EntryPointMethod))
            {
                // Specify the class that contains
                // the main method of the executable.
                cp.MainClass = "skeleton.Program";
            }

            //if (Directory.Exists("Resources"))
            //{
                if (provider.Supports(GeneratorSupport.Resources))
                {
                    // Set the embedded resource file of the assembly.
                    // This is useful for culture-neutral resources,
                    // or default (fallback) resources.

                   // cp.EmbeddedResources.Add(@"D:\PROJECTS\Tests\R_N_D\CompileCode\CompileCode\Extractor\CCD.resource");

                    cp.EmbeddedResources.AddRange(filesToEmbed.ToArray());
                  //  cp.EmbeddedResources.Add("enc_1097421_JOHN_30-01-12_05-50-13.xml");
                    // Set the linked resource reference files of the assembly.
                    // These resources are included in separate assembly files,
                    // typically localized for a specific language and culture.
                   // cp.LinkedResources.Add("Resources\\nb-no.resources");
                }
               // }

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);

            if (cr.Errors.Count > 0)
            {
                // Display compilation errors.
                //Console.WriteLine("Errors building {0} into {1}",
                //    sourceFile, cr.PathToAssembly);
                //foreach (CompilerError ce in cr.Errors)
                //{
                //    Console.WriteLine("  {0}", ce.ToString());
                //    Console.WriteLine();
                //}
            }
            else
            {
                //Console.WriteLine("Source {0} built into {1} successfully.",
                //    sourceFile, cr.PathToAssembly);
                //Console.WriteLine("{0} temporary files created during the compilation.",
                //    cp.TempFiles.Count.ToString());

            }

            // Return the results of compilation.
            if (cr.Errors.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
Example #17
0
        /// <summary>
        /// Compiles the given source code file into an exe assembly or class library and saves it to the given file name.
        /// </summary>
        /// <param name="srcFile">A string value indicating the source file to compile from.</param>
        /// <param name="exeFile">A string value indicating the assembly to to create.</param>
        /// <param name="Provider">An object of type CodeDomProvider that can be used to compile the code.</param>
        /// <param name="createExe">A bool value indicating whether the CodeProvider should compile an exe file or class library.</param>
        /// <param name="includeDebugInfo">A bool value indicating whether or not to include debug information.</param>
        /// <returns>A CompilerResults object indicating the results of the compile operation.</returns>
        public static CompilerResults CompileCode(string[] srcFile, string exeFile, CodeDomProvider Provider, bool createExe, bool includeDebugInfo)
        {
            foreach (string file in srcFile)
            {
                if (!File.Exists(file))
                    throw new Exception("One or more source files could not be found.");
            }

            // Link the 'system.dll' file to the executable
            string[] refAsm ={ "System.dll" };
            CompilerParameters cp = new CompilerParameters(refAsm, exeFile, false);

            // Tell the Compiler whether or not we're building an exe or class library.
            cp.GenerateExecutable = createExe;

            // Start the compiler.
            CompilerResults cr = Provider.CompileAssemblyFromFile(cp, srcFile);

            // Return the results of the compilation.
            return cr;
        }