当前位置: 首页>>代码示例>>C#>>正文


C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile方法代码示例

本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile方法的典型用法代码示例。如果您正苦于以下问题:C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile方法的具体用法?C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile怎么用?C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CSharp.CSharpCodeProvider的用法示例。


在下文中一共展示了Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: execScript

		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;
		}
开发者ID:2asoft,项目名称:NoxMapEditor,代码行数:35,代码来源:Template.cs

示例2: CreateAssembly

        /// <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;
        }
开发者ID:hdxhan,项目名称:IKendeLib,代码行数:63,代码来源:AssemblyFactory.cs

示例3: CreateAssembly

        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;
        }
开发者ID:hdxhan,项目名称:IKendeLib,代码行数:55,代码来源:FileCompiler.cs

示例4: ObfuscationAttributeTests

		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");
		}
开发者ID:modulexcite,项目名称:obfuscar,代码行数:23,代码来源:ObfuscationAttributeTests.cs

示例5: BuildAssembly

        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);
            }
        }
开发者ID:gencer,项目名称:obfuscar,代码行数:20,代码来源:TestHelper.cs

示例6: WriteProject

        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))
//.........这里部分代码省略.........
开发者ID:CassieEllen,项目名称:opensim,代码行数:101,代码来源:AutotoolsTarget.cs

示例7: _CompileSource

        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());
                            }
                        }
//.........这里部分代码省略.........
开发者ID:erisonliang,项目名称:qizmt,代码行数:101,代码来源:Compiler.cs

示例8: WriteProject

        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:
//.........这里部分代码省略.........
开发者ID:TheProjecter,项目名称:zaspe-sharp,代码行数:101,代码来源:AutotoolsTarget.cs

示例9: Compile_Clicked

        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);
                }
            }
        }
开发者ID:scnerd,项目名称:Visual_Coder,代码行数:28,代码来源:Form1.cs

示例10: CompileScript

        /// <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());
                }
            }
        }
开发者ID:sawickiap,项目名称:NoConsole,代码行数:65,代码来源:Form1.cs

示例11: CompilePluginsDirectory

        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;
                    }
                }
            }
        }
开发者ID:Unchated,项目名称:pogee-3d-editor,代码行数:37,代码来源:MainWindowViewModel.cs

示例12: CompileScripts

        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;
        }
开发者ID:HaKDMoDz,项目名称:Lunar-Development-Kit,代码行数:64,代码来源:MainWindow.cs

示例13: compilePlugin

            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;
            }
开发者ID:KARAS-LightweightMarkupLanguage,项目名称:KARAS_CSharp,代码行数:23,代码来源:KARAS.cs

示例14: compileSourceCode_Sync

        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;
            }
        }
开发者ID:sempf,项目名称:FluentSharp,代码行数:64,代码来源:Charp_FastCompiler.cs

示例15: GetAssemblyWithCustomVersionTableMetaData

        /// <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;
        }
开发者ID:nats,项目名称:fluentmigrator,代码行数:21,代码来源:MigrationLoaderTests.cs


注:本文中的Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。