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


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

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


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

示例1: service_info_methods

        public static void service_info_methods()
        {
            uri = new Uri("http://localhost:60377/Service1.asmx?wsdl"); 
            WebRequest webRequest = WebRequest.Create(uri);
            System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
            // Get a WSDL file describing a service
            ServiceDescription sd = ServiceDescription.Read(requestStream);
            string sdName = sd.Services[0].Name;

            // Initialize a service description servImport
            ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
            servImport.AddServiceDescription(sd, String.Empty, String.Empty);
            servImport.ProtocolName = "Soap";
            servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

            CodeNamespace nameSpace = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            codeCompileUnit.Namespaces.Add(nameSpace);
            // Set Warnings
            ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable = false;
                param.GenerateInMemory = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel = 4;

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly assembly = results.CompiledAssembly;
                service = assembly.GetType(sdName);

                methodInfo = service.GetMethods();

                int c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                        break;
                    c++;
                }
                listurl = new string[c]; c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                        break;
                    listurl[c++] = t.Name;
                }

            }

        }
开发者ID:MinaYounan-CS,项目名称:WoT-Testbed-Environment,代码行数:59,代码来源:Service+Info.cs

示例2: CreateRazorTemplateInstance

        // Returns an instance of the razor template, compiled from the file stored as an embedded resource.
        // The first time this method is executed, the Razor template is compiled and stored.
        // This method will throw an InvalidDataException if the template contains syntax errors.
        public TemplateBase CreateRazorTemplateInstance()
        {
            if (templateType == null)
            {
                var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
                host.DefaultBaseClass = typeof(TemplateBase).FullName;
                host.DefaultNamespace = "RazorOutput";
                host.DefaultClassName = "Template";
                host.NamespaceImports.Add("System");

                GeneratorResults razorResult = null;

                var templateStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Curtsy.Resources.curtsy.cshtml");

                if (templateStream == null)
                    throw new FileNotFoundException("Could not find embedded resource 'Curtsy.Resources.curtsy.cshtml'");

                using (var reader = new StreamReader(templateStream))
                {
                    razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
                }

                var compilerParams = new CompilerParameters
                {
                    GenerateInMemory = true,
                    GenerateExecutable = false,
                    IncludeDebugInformation = false,
                    CompilerOptions = "/target:library /optimize"
                };
                compilerParams.ReferencedAssemblies.Add(typeof(Program).Assembly.CodeBase.Replace("file:///", "").Replace('/', Path.DirectorySeparatorChar));

                var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                var results = codeProvider.CompileAssemblyFromDom(compilerParams, razorResult.GeneratedCode);

                if (results.Errors.HasErrors)
                {
                    StringBuilder errors = new StringBuilder();
                    foreach (var err in results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning))
                        errors.AppendFormat("Error compiling template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText);

                    throw new InvalidDataException(errors.ToString());
                }

                templateType = results.CompiledAssembly.GetType("RazorOutput.Template");
            }

            return (TemplateBase)Activator.CreateInstance(templateType);
        }
开发者ID:brandonc,项目名称:curtsy,代码行数:51,代码来源:EmbeddedResources.cs

示例3: GenerateAssembly

		public static byte[] GenerateAssembly(string namespaceName, string className, params CodeMemberMethod[] methods)
		{
			CodeCompileUnit unit = new CodeCompileUnit();
			CodeNamespace space = new CodeNamespace(namespaceName);
			CodeTypeDeclaration type = new CodeTypeDeclaration(className);

			type.Attributes = MemberAttributes.Static | MemberAttributes.Public;
			type.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed;

			type.Members.AddRange(methods);
			space.Types.Add(type);
			unit.Namespaces.Add(space);

			Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

			System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
			options.IncludeDebugInformation = false;
			options.GenerateExecutable = false;

			options.ReferencedAssemblies.Add(typeof(int).Assembly.Location);
			options.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);

			System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromDom(options,unit);

			System.CodeDom.Compiler.CodeGeneratorOptions ops = new System.CodeDom.Compiler.CodeGeneratorOptions();
			ops.IndentString = "\t";
			ops.VerbatimOrder = true;
			ops.BracingStyle = "C";

			StringWriter text = new StringWriter();
			provider.GenerateCodeFromCompileUnit(unit, text, ops);
			string code = text.ToString();

			if (results.Errors.HasErrors)
			{
				string errors = "";
				foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
				{
					errors += error.ToString() + Environment.NewLine;
				}
				throw new InvalidOperationException(errors);
			}
			
			byte[] data = File.ReadAllBytes(results.PathToAssembly);
			File.Delete(results.PathToAssembly);
			return data;
		}
开发者ID:shadarath,项目名称:Wirtualna-rzeczywistosc,代码行数:47,代码来源:CpuParticlesCodeBuilder.cs

示例4: Invoke

        /// < summary> 
        /// 动态调用web服务 
        /// < /summary> 
        /// < param name="url">WSDL服务地址< /param> 
        /// < param name="classname">类名< /param> 
        /// < param name="methodname">方法名< /param> 
        /// < param name="args">参数< /param> 
        /// < returns>< /returns> 
        public static object Invoke(string url, string classname, string methodname, object[] args)
        {
            string ns = "EnterpriseServerBase.WebService.DynamicWebCalling";
            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceInvoker.GetWsClassName(url);
            }
            System.Net.WebClient wc = new System.Net.WebClient();
            System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
            System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
            System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
            sdi.AddServiceDescription(sd, "", "");
            System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(ns);
            System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);

            Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
            // System.CodeDom.Compiler.ICodeCompiler csc = .CreateCompiler();

            System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");

            System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new NHExt.Runtime.Exceptions.RuntimeException("调用WebService开始编译发生错误:" + sb.ToString());
            }
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            Type t = assembly.GetType(ns + "." + classname, true, true);
            object obj = Activator.CreateInstance(t);
            System.Reflection.MethodInfo mi = t.GetMethod(methodname);
            return mi.Invoke(obj, args);
        }
开发者ID:zhouweigang01,项目名称:NHExt.Runtime,代码行数:53,代码来源:WebServiceInvoker.cs

示例5: CompileCode

        private static Type CompileCode(CodeCompileUnit compileUnit)
        {
            Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            string currentBinLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.Entity.Interfaces.dll"));
            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.Platform.dll"));
            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.SData.Client.dll"));
            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.SalesLogix.Client.dll"));

            CompilerResults result = codeProvider.CompileAssemblyFromDom(compilerParameters, compileUnit);

            if (result.Errors.Count > 0)
                throw new InvalidOperationException(result.Errors[0].ErrorText);

            //The only type within the Assembly is the type requested here.
            return result.CompiledAssembly.GetTypes()[0];
        }
开发者ID:slukert,项目名称:SData-Client-for-SalesLogix,代码行数:21,代码来源:WrapperFactory.cs

示例6: SetupRazorTemplate

        //### Helpers & Setup
        // Setup the Razor templating engine so that we can quickly pass the data in
        // and generate HTML.
        //
        // The file `Resources\Nocco.cshtml` is read and compiled into a new dll
        // with a type that extends the `TemplateBase` class. This new assembly is
        // loaded so that we can create an instance and pass data into it
        // and generate the HTML.
        private static Type SetupRazorTemplate()
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            host.DefaultBaseClass = typeof(TemplateBase).FullName;
            host.DefaultNamespace = "RazorOutput";
            host.DefaultClassName = "Template";
            host.NamespaceImports.Add("System");

            GeneratorResults razorResult = null;
            using (var reader = new StreamReader(Path.Combine(_executingDirectory, "Resources", "Nocco.cshtml"))) {
                razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
            }

            var compilerParams = new CompilerParameters {
                GenerateInMemory = true,
                GenerateExecutable = false,
                IncludeDebugInformation = false,
                CompilerOptions = "/target:library /optimize"
            };
            compilerParams.ReferencedAssemblies.Add(typeof(Nocco).Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\"));

            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults results = codeProvider.CompileAssemblyFromDom(compilerParams, razorResult.GeneratedCode);

            // Check for errors that may have occurred during template generation
            if (results.Errors.HasErrors) {
                foreach (var err in results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning))
                    Console.WriteLine("Error Compiling Template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText);
            }

            return results.CompiledAssembly.GetType("RazorOutput.Template");
        }
开发者ID:marcusoftnet,项目名称:nocco,代码行数:40,代码来源:Nocco.cs

示例7: GetProxyTypeForStateInterface


//.........这里部分代码省略.........
                            }
                            else
                            {
                                throw new InvalidOperationException("Can't have fields with more than 2 dimensions");
                            }
                        }

                        foreach (StateFieldDimensionStructure sfds in field.Dimensions)
                        {
                            tt.TypeArguments.Add(sfds.Type);

                            if (!typesRequired.Contains(sfds.Type))
                            {
                                typesRequired.Add(sfds.Type);
                            }
                        }
                        tt.TypeArguments.Add(field.Type);

                        string fieldName = String.Format("_{0}Field", field.Name);
                        CodeMemberField newField = new CodeMemberField(tt, fieldName);
                        ctd.Members.Add(newField);

                        CodeMemberProperty p = new CodeMemberProperty();
                        p.Name = String.Format("{0}.{1}", _interfaceType, field.Name);
                        p.Type = tt;
                        p.Attributes -= MemberAttributes.Private;
                        CodeStatementCollection statements = p.GetStatements;

                        statements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    new CodeFieldReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                            fieldName),
                                        CodeBinaryOperatorType.IdentityInequality,
                                        new CodePrimitiveExpression(null)),
                                    new CodeStatement[] { new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName)) },
                                    new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));
                        ctd.Members.Add(p);
                    }

                }

                GenerateCodeForIStateObjectConnection(ctd);

                CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                CompilerParameters cp = new CompilerParameters();
                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add(typeof(IParameter1Dimensional<,>).Module.FullyQualifiedName);

                List<string> modules = new List<string>();
                foreach (Type t in typesRequired)
                {
                    if (!modules.Contains(t.Module.FullyQualifiedName))
                    {
                        modules.Add(t.Module.FullyQualifiedName);
                    }
                }

                foreach (string s in modules)
                {
                    cp.ReferencedAssemblies.Add(s);
                }

                cp.GenerateInMemory = true;
                string assemblyDirectory = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Temp");
                if (!Directory.Exists(assemblyDirectory))
                {
                    Directory.CreateDirectory(assemblyDirectory);
                }
                cp.OutputAssembly = Path.Combine(assemblyDirectory, string.Format("AutoGenerated{0}.dll", Guid.NewGuid()));
                CompilerResults results = provider.CompileAssemblyFromDom(cp, ccu);
                if (results.Errors.HasErrors)
                {
                    foreach (CompilerError err in results.Errors)
                    {
                        Console.WriteLine();
                        Console.WriteLine(err);
                    }
                }

                //CodeDomProvider provider2 = new Microsoft.CSharp.CSharpCodeProvider();
                //using (System.IO.TextWriter output = System.IO.File.CreateText(@"C:\Users\davidanthoff\Documents\Visual Studio 2005\Projects\test.cs"))
                //{
                //    provider2.GenerateCodeFromCompileUnit(ccu, output, new CodeGeneratorOptions());
                //}

                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

                _proxyTypeCache = results.CompiledAssembly.GetType("Esmf.StateTypes." + implementationTypeName);

                AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);

                return _proxyTypeCache;
            }
            else
            {
                return _proxyTypeCache;
            }
        }
开发者ID:fund-model,项目名称:fund,代码行数:101,代码来源:ComponentStateStructure.cs

示例8: CompileInMemory

        public static Assembly CompileInMemory(CodeCompileUnit[] codeCompileUnits, string[] assemblyNames)
        {
            // TODO: better way?
            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            var compileOptions = new CompilerParameters();
            compileOptions.GenerateInMemory = true;

            compileOptions.ReferencedAssemblies.AddRange(assemblyNames);
            CompilerResults results = codeProvider.CompileAssemblyFromDom(compileOptions, codeCompileUnits);
            if (results.Errors.Count > 0)
            {
                List<string> errors = new List<string>();
                foreach (CompilerError error in results.Errors)
                {
                    errors.Add(string.Format("{0} Line {1} Column {2}", error.ErrorText, error.Line, error.Column));
                }

                StringBuilder sb = new StringBuilder();
                foreach (string error in errors)
                {
                    sb.AppendFormat("\n\n{0}", error);
                }
                string errorText = sb.ToString();

                throw CodeCompilerException.NewFormat(
                    results.Errors,
                    codeCompileUnits,
                    codeProvider,
                    "Errors in compiling CodeCompileUnits: {0}",
                    errorText
                    );
            }

            return results.CompiledAssembly;
        }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:35,代码来源:CodeDomHelper.cs

示例9: InvokeWebservice

        /// <summary> 
        /// 根据指定的信息,调用远程WebService方法 
        /// </summary> 
        /// <param name="url">WebService的http形式的地址</param> 
        /// <param name="namespace">欲调用的WebService的命名空间</param> 
        /// <param name="classname">欲调用的WebService的类名(不包括命名空间前缀)</param> 
        /// <param name="methodname">欲调用的WebService的方法名</param> 
        /// <param name="args">参数列表</param> 
        /// <returns>WebService的执行结果</returns> 
        /// <remarks> 
        /// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。 
        /// 异常信息可能会发生在两个地方: 
        /// 1、动态构造WebService的时候,CompileAssembly失败。 
        /// 2、WebService本身执行失败。 
        /// </remarks> 
        /// <example> 
        /// <code> 
        /// object obj = InvokeWebservice("http://localhost/GSP_WorkflowWebservice/common.asmx","Genersoft.Platform.Service.Workflow","Common","GetToolType",new object[]{"1"}); 
        /// </code> 
        /// </example> 
        public static object InvokeWebservice(string url, string @namespace, string classname, string methodname, params object[] args)
        {
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
                System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
                System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace);
                System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
开发者ID:rajayaseelan,项目名称:mysoftsolution,代码行数:65,代码来源:ServiceClient.cs


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