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


C# CSharpCodeProvider.CompileAssemblyFromSource方法代码示例

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


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

示例1: UpdateSource

        public void UpdateSource()
        {
            _codeType = null;
            _codeInstance = null;
            if (Source == null)
                return;

            var provider = new CSharpCodeProvider();
            var options = new CompilerParameters { GenerateInMemory = true };
            string qn = typeof(Point3D).Assembly.Location;
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add(qn);
            string src = template.Replace("#code#", Source);
            CompilerResults compilerResults = provider.CompileAssemblyFromSource(options, src);
            if (!compilerResults.Errors.HasErrors)
            {
                Errors = null;
                var assembly = compilerResults.CompiledAssembly;
                _codeInstance = assembly.CreateInstance("MyNamespace.MyEvaluator");
                _codeType = _codeInstance.GetType();
            }
            else
            {
                // correct line numbers
                Errors = compilerResults.Errors;
                for (int i = 0; i < Errors.Count; i++)
                    Errors[i].Line -= 17;
            }

            _w = ParameterW;
            UpdateModel();
        }
开发者ID:dermeister0,项目名称:helix-toolkit,代码行数:32,代码来源:DynamicSurface3D.cs

示例2: CompileFile

        public static CompilerResults CompileFile(string input, string output, params string[] references)
        {
            CreateOutput(output);

            List<string> referencedAssemblies = new List<string>(references.Length + 3);

            referencedAssemblies.AddRange(references);
            referencedAssemblies.Add("System.dll");
            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);

            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
            {
                if (stream == null)
                {
                    throw new ArgumentException("input");
                }

                StreamReader reader = new StreamReader(stream);
                string source = reader.ReadToEnd();
                CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
                ThrowIfCompilerError(results);
                return results;
            }
        }
开发者ID:eslahi,项目名称:prism,代码行数:28,代码来源:CompilerHelper.Desktop.cs

示例3: OutputAssembly

        public static void OutputAssembly(Dictionary<string, string> generated, IEnumerable<string> assemblies, string assemblyPath)
        {
            var providerOptions = new Dictionary<string, string> {{"CompilerVersion", "v4.0"}};

            using (var codeProvider = new CSharpCodeProvider(providerOptions))
            {
                string[] sources = (from p in generated.Keys select generated[p]).ToArray();

                List<string> assemblyPaths = new List<string>(assemblies);
                assemblyPaths.Add(typeof (ManifestEventAttribute).Assembly.Location);

                var compilerParameters = new CompilerParameters(
                    assemblyPaths.ToArray(),
                    assemblyPath, 
                    false);

                CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, sources);

                if (results.Errors.Count == 0)
                    return;

                var sb = new StringBuilder();
                foreach (object o in results.Errors)
                {
                    sb.AppendLine(o.ToString());
                }

                string errors = sb.ToString();
                throw new Exception(errors);
            }
        }
开发者ID:modulexcite,项目名称:Tx,代码行数:31,代码来源:AssemblyBuilder.cs

示例4: Compile

        public bool Compile(string src)
        {
            var param = new CompilerParameters(new string[]
            {
                "System.dll",
                "mscorlib.dll",
                "System.Data.dll",
                "System.Xml.dll",
                "System.Xml.Linq.dll",
                "lib.dll",
                "compiler.dll",
            });
            param.GenerateInMemory = true;
            param.GenerateExecutable = false;
            param.IncludeDebugInformation = false;

            _provider = new CSharpCodeProvider(
                new Dictionary<string, string>()
                {
                    { "CompilerVersion", "v4.0" },
                });
            _results = _provider.CompileAssemblyFromSource(param, src);
            if (_results.Errors.Count > 0)
            {
                foreach (CompilerError err in _results.Errors)
                {
                    if (err.IsWarning) Console.WriteLine("[Warning] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
                    else Console.WriteLine("[Error] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
                }
                return false;
            }

            return true;
        }
开发者ID:hal1932,项目名称:cstest,代码行数:34,代码来源:Compiler.cs

示例5: ExecuteScript

        private static object ExecuteScript(string script, ScriptExecutionOptions options)
        {
            object result = null;

            CompilerParameters cpar = new CompilerParameters();
            cpar.GenerateInMemory = true;
            cpar.ReferencedAssemblies.Add("mscorlib.dll");
            cpar.ReferencedAssemblies.Add("System.dll");
            cpar.ReferencedAssemblies.Add("System.Core.dll");
            cpar.ReferencedAssemblies.Add("System.Data.dll");
            cpar.ReferencedAssemblies.Add("System.Xml.dll");
            cpar.ReferencedAssemblies.Add(typeof(CSharpScriptingProvider).Assembly.Location);

            string code = Properties.Resources.ScriptProviderCSharpTemplate;
            code = code.Replace("{Source}", script);

            CSharpCodeProvider csp = new CSharpCodeProvider();
            CompilerResults res = csp.CompileAssemblyFromSource(cpar, code);

            if (!res.Errors.HasErrors)
            {
                MethodInfo func = res.CompiledAssembly.ExportedTypes.First().GetMethods().First();
                result = func.Invoke(null, new object[] { options });
            }

            return result;
        }
开发者ID:chrishensel,项目名称:ezNReporting,代码行数:27,代码来源:CSharpScriptingProvider.cs

示例6: Compile

        public CompilerResults Compile(string generatedCodeFileName = null)
        {
            var options = new Dictionary<string, string>
                          {
                          	{"CompilerVersion", "v3.5"}
                          };
            var codeProvider = new CSharpCodeProvider(options);

            var scanner = new Scanner(this.fileName);
            var parser = new Parser(scanner);

            parser.Parse();

            var generatator = new Generator();
            var generatedCode = generatator.Generate(null, parser.ruleClassStatement, "");

            if (generatedCodeFileName != null)
            {
                using (var stream = new StreamWriter(generatedCodeFileName, false, Encoding.UTF8))
                {
                    stream.Write(generatedCode);
                }
            }

            return codeProvider.CompileAssemblyFromSource(this._compilerParams, generatedCode.ToString());
        }
开发者ID:werwolfby,项目名称:wolfgenerator,代码行数:26,代码来源:Compiler.cs

示例7: Run

        private static void Run(string csFilename, IEnumerable<string> args)
        {
            var compilerParameters = new CompilerParameters
                {
                    GenerateExecutable = false,
                    GenerateInMemory = true
                };
            var referencedAssemblies = new[] {"System.dll", "System.Core.dll", "System.Data.dll"};
            foreach (var assembly in referencedAssemblies)
            {
                compilerParameters.ReferencedAssemblies.Add(assembly);
            }
            compilerParameters.IncludeDebugInformation = true;

            var cSharpCodeProvider = new CSharpCodeProvider();

            var code = File.ReadAllText(csFilename);

            foreach(Match m in RxRef.Matches(code))
            {
                compilerParameters.ReferencedAssemblies.Add(m.Groups[1].Value);
            }

            var result = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code);
            if (result.Errors.Count != 0)
            {
                foreach (var error in result.Errors)
                {
                    Console.WriteLine(error);
                }
                return;
            }
            result.CompiledAssembly.GetType("CsRun.Program").GetMethod("Main").Invoke(null, new object[] {args.ToArray()});
        }
开发者ID:tanglebones,项目名称:ch-csrun,代码行数:34,代码来源:Program.cs

示例8: CreateEvaluator

        private void CreateEvaluator()
        {
            string Code = "using System; public class Evaluator { public static double Evaluate (double x) { return " + this.Expression + "; } }";

            CompilerParameters Parameters = new CompilerParameters();

            Parameters.GenerateExecutable = false;
            Parameters.TreatWarningsAsErrors = true;
            Parameters.TempFiles.KeepFiles = false;
            Parameters.GenerateInMemory = true;
            Parameters.ReferencedAssemblies.Add("System.dll");

            CSharpCodeProvider Provider = new CSharpCodeProvider();
            CompilerResults CompResults = Provider.CompileAssemblyFromSource(Parameters, Code);

            if (CompResults.Errors.Count > 0)
            {
                throw new FormatException("Espressione non valida!");
            }
            else
            {
                System.Reflection.Assembly Asm = CompResults.CompiledAssembly;
                this.EvaluateFunction = Asm.GetType("Evaluator").GetMethod("Evaluate");
            }
        }
开发者ID:tomaluca95,项目名称:TheNerdMathFunction,代码行数:25,代码来源:Function.cs

示例9: Compile

        /// <summary>
        /// Compiles the srcipt and returns an evaluator (a delegate) 
        /// which takes in time and returns audioFrame values
        /// </summary>
        /// <returns>A delegate of type Func&lt;double,double&gt;</returns>
        public Func<double, double> Compile()
        {
            var codeProvider = new CSharpCodeProvider();
            var compilerResults =
                codeProvider.CompileAssemblyFromSource(
                    new CompilerParameters(new[] {"TuneItDynamicBase.dll"}) {GenerateInMemory = true},
                    @"
            using System;
            using TuneItDynamicBase;

            public class DynamicCompiledScript : DynamicCompiledScriptBase
            {
            public override Func<double, double> Evaluator
            {
            get
            {
            return delegate(double time)
                   {"
                        + script + @"
                   };
            }
            }
            }
            ");
            if (compilerResults.Errors.HasErrors)
            {
                return null;
            }
            var dynamicScriptInstance = (IDynamicScript) compilerResults.CompiledAssembly.CreateInstance("DynamicCompiledScript");
            if (dynamicScriptInstance == null)
            {
                return null;
            }
            return dynamicScriptInstance.Evaluator;
        }
开发者ID:ashokgowtham,项目名称:tune-it,代码行数:40,代码来源:ScriptCompiler.cs

示例10: Compile

		static AssemblyDefinition Compile(string code)
		{
			CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });
			CompilerParameters options = new CompilerParameters();
			options.ReferencedAssemblies.Add("System.Core.dll");
			CompilerResults results = provider.CompileAssemblyFromSource(options, code);
			try
			{
				if (results.Errors.Count > 0)
				{
					StringBuilder b = new StringBuilder("Compiler error:");
					foreach (var error in results.Errors)
					{
						b.AppendLine(error.ToString());
					}
					throw new Exception(b.ToString());
				}
				return AssemblyDefinition.ReadAssembly(results.PathToAssembly);
			}
			finally
			{
				File.Delete(results.PathToAssembly);
				results.TempFiles.Delete();
			}
		}
开发者ID:stgwilli,项目名称:ILSpy,代码行数:25,代码来源:DecompilerTestBase.cs

示例11: CompileWithReferences

        private static Assembly CompileWithReferences(string sourcecode,CompileLanguage language, string[] references)
        {
            CodeDomProvider comp =null;
            switch (language ){
                case CompileLanguage.VisualBasic:
                    comp = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case CompileLanguage.CSharp:
                default:
                    comp = new CSharpCodeProvider();
                    break;
            }
            CompilerParameters cp = new CompilerParameters();
            foreach (string reference in references)
            {
                cp.ReferencedAssemblies.Add(reference);
            }
            cp.GenerateInMemory = true;

            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sourcecode);
            if (cr.Errors.HasErrors)
            {
                string error = string.Empty;
                foreach (CompilerError err in cr.Errors)
                {
                    error += err.ErrorText + System.Environment.NewLine;
                }
                System.Diagnostics.Trace.WriteLine(error);
                return null;
            }

            return cr.CompiledAssembly;
        }
开发者ID:WrongDog,项目名称:CardServer,代码行数:33,代码来源:Compiler.cs

示例12: MakeFrom

        public static IPlayer MakeFrom( string text )
        {
            CSharpCodeProvider csc = new CSharpCodeProvider();
            string[] refs = new[] { "mscorlib.dll", "System.Drawing.dll", "ModelPreviewer.exe", "OpenTK.dll" };

            CompilerParameters prms = new CompilerParameters( refs, "model.dll", true );
            prms.GenerateInMemory = true;
            CompilerResults results = csc.CompileAssemblyFromSource( prms, text );

            using( StreamWriter writer = new StreamWriter( "error.txt", false ) ) {
                StringBuilder builder = new StringBuilder();
                foreach( CompilerError error in results.Errors ) {
                    writer.WriteLine( "=== errror" );
                    writer.WriteLine( "line {0}: {1} ({2})", error.Line,
                                     error.ErrorText, error.ErrorNumber );
                    builder.AppendFormat( "line {0}: {1} ({2})", error.Line,
                                     error.ErrorText, error.ErrorNumber );
                }
                if( results.Errors.Count > 0 ) {
                    MessageBox.Show( builder.ToString(), "Model error" );
                    return null;
                }
            }

            foreach( var type in results.CompiledAssembly.GetTypes() ) {
                if( type.IsSubclassOf( typeof( IPlayer ) ) ) {
                    try {
                        return (IPlayer)Activator.CreateInstance( type );
                    } catch( Exception ex ) {
                        MessageBox.Show( ex.ToString(), "Model error" );
                    }
                }
            }
            return null;
        }
开发者ID:UnknownShadow200,项目名称:CSModelPreviewer,代码行数:35,代码来源:CSharpParser.cs

示例13: CompileCSharpScript

        /// <summary>
        /// Compiles a C# script as if it were a file in your project.
        /// </summary>
        /// <param name="scriptText">The text of the script.</param>
        /// <param name="errors">The compiler errors and warnings from compilation.</param>
        /// <param name="assemblyIfSucceeded">The compiled assembly if compilation succeeded.</param>
        /// <returns>True if compilation was a success, false otherwise.</returns>
        public static bool CompileCSharpScript(string scriptText, out CompilerErrorCollection errors, out Assembly assemblyIfSucceeded)
        {
            var codeProvider = new CSharpCodeProvider();
            var compilerOptions = new CompilerParameters();

            // We want a DLL and we want it in memory
            compilerOptions.GenerateExecutable = false;
            compilerOptions.GenerateInMemory = true;

            // Add references for UnityEngine and UnityEditor DLLs
            compilerOptions.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);
            compilerOptions.ReferencedAssemblies.Add(typeof(EditorApplication).Assembly.Location);

            // Default to null output parameters
            errors = null;
            assemblyIfSucceeded = null;

            // Compile the assembly from the source script text
            CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerOptions, scriptText);

            // Store the errors for the caller. even on successful compilation, we may have warnings.
            errors = result.Errors;

            // See if any errors are actually errors. if so return false
            foreach (CompilerError e in errors) {
                if (!e.IsWarning) {
                    return false;
                }
            }

            // Otherwise we pass back the compiled assembly and return true
            assemblyIfSucceeded = result.CompiledAssembly;
            return true;
        }
开发者ID:rubeninmark,项目名称:UnityToolbag,代码行数:41,代码来源:CodeCompiler.cs

示例14: RunCode

 /// <summary>
 /// 执行一段 C# 代码并返回结果。
 /// </summary>
 /// <param name="codeBody">方法体。</param>
 /// <param name="parameters">参数(名称,值)。</param>
 /// <returns>方法的返回值。</returns>
 public static object RunCode(string codeBody, Dictionary<string, object> parameters)
 {
     using (CSharpCodeProvider provider = new CSharpCodeProvider())
     {
         CompilerParameters parameter = new CompilerParameters();
         parameter.GenerateExecutable = false;
         parameter.GenerateInMemory = true;
         StringBuilder sb = new StringBuilder(); // 生成方法参数代码。
         List<object> methodParameters = new List<object>(); // 调用方法时的参数对象列表。
         for (int i = 0; i < parameters.Count; i++)
         {
             var temp = parameters.ElementAt(i);
             sb.Append(temp.Value.GetType().FullName + " " + temp.Key);
             methodParameters.Add(temp.Value);
             if (i != parameters.Count - 1)
             {
                 sb.Append(",");
             }
         }
         string source = @"using System;namespace NameSpace{public class Class{public static object Method(" +
                         sb.ToString() + @"){" + codeBody + @"}}}"; // 最终代码段。
         CompilerResults result = provider.CompileAssemblyFromSource(parameter, source); // 编译代码。
         if (result.Errors.Count > 0)
         {
             throw new Exception("代码错误");
         }
         else
         {
             Assembly assembly = result.CompiledAssembly; // 获得编译成功的程序集。
             Type type = assembly.GetType("NameSpace.Class");
             return type.GetMethod("Method").Invoke(null, methodParameters.ToArray()); // 执行方法。
         }
     }
 }
开发者ID:h82258652,项目名称:Common,代码行数:40,代码来源:ReflectionHelper.DynamicCompile.cs

示例15: Compile

        public static Type Compile(string name, string queryText)
        {
            var provider = new CSharpCodeProvider(new Dictionary<string, string> {{"CompilerVersion", "v4.0"}});
            var results = provider.CompileAssemblyFromSource(new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory = false,
                IncludeDebugInformation = true,
                ReferencedAssemblies =
                    {
                        typeof (AbstractViewGenerator).Assembly.Location,
                        typeof (NameValueCollection).Assembly.Location,
                        typeof (Enumerable).Assembly.Location,
                        typeof (Binder).Assembly.Location,
                    },
            }, queryText);

            if (results.Errors.HasErrors)
            {
                var sb = new StringBuilder()
                    .AppendLine("Source code:")
                    .AppendLine(queryText)
                    .AppendLine();
                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(error.ToString());
                }
                throw new InvalidOperationException(sb.ToString());
            }
            return results.CompiledAssembly.GetType(name);
        }
开发者ID:kenegozi,项目名称:ravendb,代码行数:31,代码来源:QueryParsingUtils.cs


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