CompileAssemblyFromDom() public method

public CompileAssemblyFromDom ( CompilerParameters options ) : CompilerResults
options CompilerParameters
return CompilerResults
Example #1
0
        /// <summary> 根据参数执行WebService </summary>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            try
            {
                string _namespace = "WebService";
                if (string.IsNullOrEmpty(classname))
                {
                    classname = GetClassName(url);
                }
                //获取服务描述语言(WSDL)
                Net.WebClient wc     = new Net.WebClient();
                Stream        stream = wc.OpenRead(url + "?WSDL");                                                                   //【1】
                Web.Services.Description.ServiceDescription         sd  = Web.Services.Description.ServiceDescription.Read(stream);  //【2】
                Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】
                sdi.AddServiceDescription(sd, "", "");
                CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace);                                                    //【4】
                //生成客户端代理类代码
                CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit();                                                         //【5】
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】
                CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
                //ICodeCompiler icc = csc.CreateCompiler();//【7】

                //设定编译器的参数
                CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】
                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");
                //编译代理类
                CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (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 bj = Activator.CreateInstance(t);                   //【10】
                System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】
                return(mi.Invoke(bj, args));
            }
            catch (System.Exception ex)
            {
                Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace);
                //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test");
                return(null);
            }
        }
Example #2
0
        private RazorViewBase GenerateRazorView(CodeDomProvider codeProvider, GeneratorResults razorResult)
        {
            // Compile the generated code into an assembly
            string outputAssemblyName = String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N"));

            CompilerResults results = codeProvider.CompileAssemblyFromDom(

                new CompilerParameters(new string[] {
                    GetAssemblyPath(typeof(Microsoft.CSharp.RuntimeBinder.Binder)),
                    GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
                    GetAssemblyPath(Assembly.GetExecutingAssembly()) }, outputAssemblyName),
                razorResult.GeneratedCode);

            if (results.Errors.HasErrors) {
                CompilerError err = results.Errors
                                           .OfType<CompilerError>()
                                           .Where(ce => !ce.IsWarning)
                                           .First();
                var error = String.Format("Error Compiling Template: ({0}, {1}) {2})",
                                              err.Line, err.Column, err.ErrorText);

                return new ErrorView(error);
            }
            else {
                // Load the assembly
                Assembly assembly = Assembly.LoadFrom(outputAssemblyName);
                if (assembly == null) {
                    string error = "Error loading template assembly";

                    return new ErrorView(error);
                }
                else {
                    // Get the template type
                    Type type = assembly.GetType("RazorOutput.RazorView");
                    if (type == null) {
                        string error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                        return new ErrorView(error);
                    }
                    else {
                        RazorViewBase view = Activator.CreateInstance(type) as RazorViewBase;
                        if (view == null) {
                            string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase";
                            return new ErrorView(error);
                        }
                        else {
                            return view;
                        }
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// 动态 WebService 构造函数
        /// </summary>
        /// <param name="pUrl">WebService 地址</param>
        /// <param name="pClassname">类名,可省略,可空</param>
        public SoapHelper(string pUrl, string pClassname = null)
        {
            if (String.IsNullOrEmpty(pClassname))
                WebServiceClassname = GetWsClassName(pUrl);
            else
                WebServiceClassname = pClassname;
            WebServiceNamespace = "LiveAzure.Utility";

            try
            {
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(pUrl + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                sdi.ProtocolName = "Soap";
                sdi.Style = ServiceDescriptionImportStyle.Client;
                sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                CodeNamespace cn = new CodeNamespace(this.WebServiceNamespace);
                SoapCompileUnit = new CodeCompileUnit();
                SoapCompileUnit.Namespaces.Add(cn);
                sdi.Import(cn, SoapCompileUnit);

                CSharpCodeProvider csc = new CSharpCodeProvider();
                SoapCodeProvider = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters cparam = new CompilerParameters();
                cparam.GenerateExecutable = false;
                cparam.GenerateInMemory = true;
                cparam.ReferencedAssemblies.Add("System.dll");
                cparam.ReferencedAssemblies.Add("System.XML.dll");
                cparam.ReferencedAssemblies.Add("System.Web.Services.dll");
                cparam.ReferencedAssemblies.Add("System.Data.dll");

                SoapCompilerResults = SoapCodeProvider.CompileAssemblyFromDom(cparam, SoapCompileUnit);
                if (SoapCompilerResults.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in SoapCompilerResults.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
        public void SaveAsAssembly(CodeDomProvider provider, GLSLAssembly assembly)
        {
            // Build the parameters for source compilation.
            var cp = new CompilerParameters();

            // Add an assembly reference.
            cp.ReferencedAssemblies.Add( "System.dll" );
            cp.ReferencedAssemblies.Add ("System.Runtime.InteropServices.dll");

            if (assembly.ReferencedAssemblies != null)
            {
                foreach (var assemblyName in assembly.ReferencedAssemblies)
                {
                    cp.ReferencedAssemblies.Add( assemblyName );
                }
            }

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

            // Set the assembly file name to generate.
            cp.OutputAssembly = System.IO.Path.Combine(assembly.Path,assembly.OutputAssembly);

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

            var contentUnit = InitialiseCompileUnit (assembly);

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromDom(cp, contentUnit);

            if (cr.Errors.Count > 0)
            {
                Debug.WriteLine(string.Format("Source built into {0} unsuccessfully.", cr.PathToAssembly));
                // Display compilation errors.
                foreach (CompilerError ce in cr.Errors)
                {
                    Debug.WriteLine("  {0}", ce.ToString());
                }
            }
            else
            {
                Debug.WriteLine(string.Format("Source built into {0} successfully.", cr.PathToAssembly));
            }
        }
Example #5
0
        private Func<INancyRazorView> GenerateRazorViewFactory(CodeDomProvider codeProvider, GeneratorResults razorResult, Assembly referencingAssembly, IEnumerable<string> rendererSpecificAssemblies, Type passedModelType, ViewLocationResult viewLocationResult)
        {
            var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));

            var modelType = FindModelType(razorResult.Document, passedModelType);

            var assemblies = new List<string>
            {
                GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
                GetAssemblyPath(typeof(IHtmlString)),
                GetAssemblyPath(Assembly.GetExecutingAssembly()),
                GetAssemblyPath(modelType)
            };

            if (referencingAssembly != null)
            {
                assemblies.Add(GetAssemblyPath(referencingAssembly));
            }

            assemblies = assemblies
                .Union(rendererSpecificAssemblies)
                .ToList();

            if (this.razorConfiguration != null)
            {
                var assemblyNames = this.razorConfiguration.GetAssemblyNames();
                if (assemblyNames != null)
                {
                    assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
                }

                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(razorResult, modelType);
                }
            }

            var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName);

            CompilerResults results;
            lock (this.compileLock)
            {
                results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
            }

            if (results.Errors.HasErrors)
            {
                var output = new string[results.Output.Count];
                results.Output.CopyTo(output, 0);
                var outputString = string.Join("\n", output);

                var fullTemplateName = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
                var templateLines = GetViewBodyLines(viewLocationResult);
                var errors = results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).ToArray();
                var errorMessages = BuildErrorMessages(errors);

                MarkErrorLines(errors, templateLines);

                var errorDetails = string.Format(
                                        "Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}",
                                        fullTemplateName,
                                        errorMessages,
                                        templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2));

                return () => new NancyRazorErrorView(errorDetails);
            }

            var assembly = Assembly.LoadFrom(outputAssemblyName);
            if (assembly == null)
            {
                const string error = "Error loading template assembly";
                return () => new NancyRazorErrorView(error);
            }

            var type = assembly.GetType("RazorOutput.RazorView");
            if (type == null)
            {
                var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                return () => new NancyRazorErrorView(error);
            }

            if (Activator.CreateInstance(type) as INancyRazorView == null)
            {
                const string error = "Could not construct RazorOutput.Template or it does not inherit from INancyRazorView";
                return () => new NancyRazorErrorView(error);
            }

            return () => (INancyRazorView)Activator.CreateInstance(type);
        }
        /// <summary>
        /// This overrides the CodeDomTest Run method that does verification
        /// on the tree provided in the BuildTree method you provide.
        /// </summary>
        /// <param name="provider">Provider to test.</param>
        /// <returns>True if the tree builds, compiles, searches and passes
        /// assembly verification.  False if any of these fails.</returns>
        public override bool Run (CodeDomProvider provider) {
            bool fail = false;

            // build the tree
            LogMessageIndent ();
            LogMessage ("- Generating tree.");
            CodeCompileUnit cu = new CodeCompileUnit ();
            LogMessageIndent ();
            BuildTree (provider, cu);
            LogMessageUnindent ();

            // validate tree using 'experimental' subset tester
            // but only if the test believes its in the subset
            if ((TestType & TestTypes.Subset) != 0) {
                SubsetConformance subsConf = new SubsetConformance ();
                LogMessage ("- Checking tree subset conformance.");
                if (!subsConf.ValidateCodeCompileUnit (cu))
                    LogMessage ("Failed subset tester: {0}",
                            subsConf.ToString ());
            }

            // realize source
            StringWriter sw = new StringWriter (CultureInfo.InvariantCulture);
#if WHIDBEY
            provider.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#else
            ICodeGenerator generator = provider.CreateGenerator ();
            generator.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#endif

            // only continue if the source could be realized into a string.
            if (!fail) {
                string source = sw.ToString ();

                if (saveSourceFileName.Length > 0) {
                    LogMessage ("- Saving source into '" + saveSourceFileName + "'");

                    // save this source to a file
                    DumpStringToFile (source, saveSourceFileName);
                }

                // log the source code
                //LogMessage (source);

                // search the source if the test case asks us to
                if (ShouldSearch) {
                    LogMessageIndent ();
                    Search (provider, source);
                    LogMessageUnindent ();
                }
                
                // continue only if the test case wants to compile or verify
                if (ShouldCompile || ShouldVerify) {

                    // ask the test case which compiler parameters it would like to use
                    CompilerParameters parms = GetCompilerParameters (provider);

#if FSHARP
                    // If the generated code has entrypoint, then F# requires us to generate EXE
                    bool hasEntryPoint = false;
                    foreach(CodeNamespace ns in cu.Namespaces)
                        foreach (CodeTypeDeclaration ty in ns.Types)
                            foreach(CodeTypeMember mem in ty.Members)
                                if (mem is CodeEntryPointMethod) { hasEntryPoint = true; }

                    // If the output file name is specified then it should be EXE
                    if (hasEntryPoint && parms.GenerateExecutable == false)
                    {
                        parms.GenerateExecutable = true;
                        if (saveAssemblyFileName.ToLower().EndsWith(".dll"))
                            saveAssemblyFileName = saveAssemblyFileName.Substring(0, saveAssemblyFileName.Length - 4) + ".exe";
                    }
#endif
                    
                    // add the appropriate compiler parameters if the user asked us
                    // to save assemblies to file
                    if (saveAssemblyFileName.Length > 0) {
                        parms.OutputAssembly = saveAssemblyFileName;
                        LogMessage ("- Compiling to '" + saveAssemblyFileName + "'.");
                    }

                    // always generate in memory for verification purposes
                    parms.GenerateInMemory = true;

                    // compile!
#if WHIDBEY
                    CompilerResults results = provider.CompileAssemblyFromDom (parms, cu);
#else
                    ICodeCompiler compiler = provider.CreateCompiler ();
                    CompilerResults results = compiler.CompileAssemblyFromDom (parms, cu);
#endif

                    if (results.NativeCompilerReturnValue != 0) {
                        // compilation failed
                        fail = true;
                        LogMessage ("- Compilation failed.");
                        
                        // log the compilation failed output
                        foreach (string msg in results.Output)
                            LogMessage (msg);

                    } else if (ShouldVerify) {
                        // compilation suceeded and we are asked to verify the
                        // compiled assembly
                        LogMessage ("- Verifying assembly.");

                        // verify the compiled assembly if it's there
                        if (results.CompiledAssembly != null) {
                            LogMessageIndent ();
                            VerifyAssembly (provider, results.CompiledAssembly);
                            LogMessageUnindent ();
                        }
                    }
                }
            }

            if (fail || !AreAllValidated ()) {
                // one of the steps above failed or a scenario was not
                // verified within the test case
                fail = true;
                LogMessage ("! Test '" + Name + "' failed.");

                // output failing scenarios
                if (!AreAllValidated()) {
                    LogMessage ("! Failing scenarios:");
                    foreach (Scenario s in GetNotValidated())
                    {
                        LogMessage ("-  " + s.ToString());
                    }
                }
            } else {
                // test passed
                LogMessage ("* Test '" + Name + "' passed.");
            }
            LogMessageUnindent ();

            // return true on success, false on failure
            return !fail;
        }
        private Func<NancyRazorViewBase> GenerateRazorViewFactory(CodeDomProvider codeProvider, GeneratorResults razorResult, Assembly referencingAssembly, IEnumerable<string> rendererSpecificAssemblies, Type passedModelType)
        {
            var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));

            var modelType = FindModelType(razorResult.Document, passedModelType);

            var assemblies = new List<string>
            {
                GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
                GetAssemblyPath(typeof(IHtmlString)),
                GetAssemblyPath(Assembly.GetExecutingAssembly()),
                GetAssemblyPath(modelType)
            };

            if (referencingAssembly != null)
                assemblies.Add(GetAssemblyPath(referencingAssembly));

            assemblies = assemblies
                .Union(rendererSpecificAssemblies)
                .ToList();

            if (this.razorConfiguration != null)
            {
                var assemblyNames = this.razorConfiguration.GetAssemblyNames();
                if (assemblyNames != null)
                {
                    assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
                }

                if (this.razorConfiguration.AutoIncludeModelNamespace)
                {
                    AddModelNamespace(razorResult, modelType);
                }
            }

            var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName);

            var results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);

            if (results.Errors.HasErrors)
            {
                var err = results.Errors
                    .OfType<CompilerError>()
                    .Where(ce => !ce.IsWarning)
                    .Select(error => String.Format("Error Compiling Template: ({0}, {1}) {2})", error.Line, error.Column, error.ErrorText))
                    .Aggregate((s1, s2) => s1 + "<br/>" + s2);

                return () => new NancyRazorErrorView(err);
            }

            var assembly = Assembly.LoadFrom(outputAssemblyName);
            if (assembly == null)
            {
                const string error = "Error loading template assembly";
                return () => new NancyRazorErrorView(error);
            }

            var type = assembly.GetType("RazorOutput.RazorView");
            if (type == null)
            {
                var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                return () => new NancyRazorErrorView(error);
            }

            if (Activator.CreateInstance(type) as NancyRazorViewBase == null)
            {
                const string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase";
                return () => new NancyRazorErrorView(error);
            }

            return () => (NancyRazorViewBase)Activator.CreateInstance(type);
        }
        private static void ImportSchemasAsClasses(CodeDomProvider codeProvider, System.IO.Stream xsdStream, string ns, string uri, CodeGenerationOptions options, IList elements, StringCollection schemaImporterExtensions)
        {
            XmlSchemas userSchemas = new XmlSchemas();

            Hashtable uris = new Hashtable();
            XmlSchema schema = ReadSchema(xsdStream);

            Uri uri2 = new Uri("http://www.w3.org/2001/XMLSchema/temp");
            uris.Add(schema, uri2);
            userSchemas.Add(schema, uri2);

            Hashtable includeSchemas = new Hashtable();
            Compile(userSchemas, uris, includeSchemas);
            try
            {
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                CodeNamespace namespace2 = new CodeNamespace(ns);
                codeCompileUnit.Namespaces.Add(namespace2);
                GenerateVersionComment(namespace2);
                XmlCodeExporter codeExporter = new XmlCodeExporter(namespace2, codeCompileUnit, codeProvider, options, null);
                XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas, options, codeProvider, new ImportContext(new CodeIdentifiers(), false));
                schemaImporter.Extensions.Add(new System.Data.DataSetSchemaImporterExtension());

                {
                    StringEnumerator enumerator2 = schemaImporterExtensions.GetEnumerator();
                    {
                        while (enumerator2.MoveNext())
                        {
                            Type type = Type.GetType(enumerator2.Current.Trim(), true, false);
                            schemaImporter.Extensions.Add(type.FullName, type);
                        }
                    }
                }
                AddImports(namespace2, GetNamespacesForTypes(new Type[] { typeof(XmlAttributeAttribute) }));
                for (int i = 0; i < userSchemas.Count; i++)
                {
                    ImportSchemaAsClasses(userSchemas[i], uri, elements, schemaImporter, codeExporter);
                }
                foreach (XmlSchema schema2 in includeSchemas.Values)
                {
                    ImportSchemaAsClasses(schema2, uri, elements, schemaImporter, codeExporter);
                }

                CompilerParameters compilePrams = new CompilerParameters();
                CompilerResults compileResults = codeProvider.CompileAssemblyFromDom(compilePrams, codeCompileUnit);

                if (compileResults.Errors.Count > 0)
                {
                    throw new ArgumentException("Compile Error of " + compileResults.Errors[0].ToString());
                }
                // Feng.Windows.Utils.ReflectionHelper.CreateInstanceFromType(compileResults.CompiledAssembly.GetTypes()[0])

                //CodeTypeDeclarationCollection types = namespace2.Types;
                //CodeGenerator.ValidateIdentifiers(namespace2);
                //TextWriter writer = this.CreateOutputWriter(outputdir, fileName, fileExtension);
                //codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null);
                //writer.Close();
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Compile Xsd Error!", ex);
            }
        }
Example #9
0
    public static int GetWebServiceDataWSDL(string url, string funcName, string className, Object[] parameters, ref Object retItem)
    {
        try
        {
            string @namespace = "KFBIO.Webservice.WSDL";

            System.Net.WebClient client = new System.Net.WebClient();
            //String classname;


            //String url = System.Configuration.ConfigurationManager.ConnectionStrings["serviceAddress"].ConnectionString;//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL
            //String url = "http://192.168.4.4:8090/yfy-client/services/Msg_Service";

            //String param = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><NOTICEMSG><MSGCONTENT><APPLICATION><INP_ID></INP_ID><INP_VISIT_TYPE_CD>1</INP_VISIT_TYPE_CD><NAME></NAME><GENDER_CD>2</GENDER_CD><BIRTHDATE> </BIRTHDATE><ID_NO></ID_NO><PATI_PHONE> </PATI_PHONE><PROVINCE_NAME> </PROVINCE_NAME><CITY_NAME> </CITY_NAME><AREA_NAME> </AREA_NAME><STREET_ID> </STREET_ID><VILLAGE_NAME> </VILLAGE_NAME><HOUSE_NO> </HOUSE_NO><APPLY_REASON>2</APPLY_REASON><CONSULT_AIM>远程诊断</CONSULT_AIM><ILLNESS_DIAG> </ILLNESS_DIAG><CONSULT_ORG_CODE> </CONSULT_ORG_CODE><CONSULT_ORG_NAME> </CONSULT_ORG_NAME></APPLICATION><EXAMSET><REPORT_NO> </REPORT_NO><REPORT_DATE> </REPORT_DATE><TEST_DEPT_NAME>病理科</TEST_DEPT_NAME><REPORT_DOC_NAME>牛爱芳</REPORT_DOC_NAME><ITEM_CD>00213564</ITEM_CD><ITEM_NAME>病理诊断</ITEM_NAME><CLINICDESC>送检目的</CLINICDESC><EXAMFINDING>检查所见</EXAMFINDING><EXAMCONCLUSION>检查结论</EXAMCONCLUSION><FTP_USER>FTP</FTP_USER><FTP_PASSWORD>1234</FTP_PASSWORD><FTP_FILEPATH> FTP文件完整路径</FTP_FILEPATH></EXAMSET></MSGCONTENT><CREATETIME>产生日期时间</CREATETIME></NOTICEMSG>";



            //classname = "Msg_Service";

            url = url + "?wsdl";

            Stream stream = client.OpenRead(url);

            ServiceDescription description = ServiceDescription.Read(stream);

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类。

            importer.ProtocolName          = "Soap";                                //指定访问协议。
            importer.Style                 = ServiceDescriptionImportStyle.Client;  //生成客户端代理。
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

            importer.AddServiceDescription(description, null, null); //添加WSDL文档。

            CodeNamespace nmspace = new CodeNamespace();             //命名空间
            nmspace.Name = @namespace;
            System.CodeDom.CodeCompileUnit unit = new System.CodeDom.CodeCompileUnit();
            unit.Namespaces.Add(nmspace);

            System.Web.Services.Description.ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            System.CodeDom.Compiler.CodeDomProvider provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");

            System.CodeDom.Compiler.CompilerParameters parameter = new System.CodeDom.Compiler.CompilerParameters();
            parameter.GenerateExecutable = false;
            if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("Temp")))
            {
                Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("Temp"));
            }
            parameter.OutputAssembly = System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll"; //"D:/TempClass.dll";//输出程序集的名称
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.ReferencedAssemblies.Add("System.XML.dll");
            parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
            parameter.ReferencedAssemblies.Add("System.Data.dll");



            System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
            if (result.Errors.HasErrors)
            {
                // 显示编译错误信息
                //临时模板编译错误,内部错误
                string a = System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll";
                if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll"))
                {
                    return(-5);
                }
            }

            System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll");//加载前面生成的程序集
            //Type t = asm.GetType(nameSpace + "." + className);
            Type t = asm.GetType(@namespace + "." + className);

            object o = Activator.CreateInstance(t);
            System.Reflection.MethodInfo method = t.GetMethod(funcName);//CONSULTAPPLYNOTICE_PATHOLOGY是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下


            retItem = method.Invoke(o, parameters);
        }
        catch (WebException ex)
        {
            //网络异常异常
            return(-1);
        }
        catch (Exception ex)
        {
            //未知错误
            return(-99);
        }

        return(0);
    }
        private CompilerResults CompileCode(CodeDomProvider provider, CodeCompileUnit unit,  string outputAssemblyPath = null)
        {
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.AddRange(GetReferenceAssemblyPaths(this._serviceInterface).ToArray());
            cp.ReferencedAssemblies.AddRange(GetReferenceAssemblyPaths(typeof(HttpRestClient<>)).ToArray());
            cp.GenerateInMemory = outputAssemblyPath == null;
            if (!string.IsNullOrEmpty(outputAssemblyPath))
            {
                cp.OutputAssembly = outputAssemblyPath;
            }

            CompilerResults results = provider.CompileAssemblyFromDom(cp, unit);
            if (results.Errors.Count > 0)
            {
                throw new CompileException("Compilation failed: Please look at the CompilerErrors property for more details!", results);
            }
            return results;
        }
 public void ToAssemblyFile(CodeCompileUnit compileunit, CodeDomProvider provider, string fileName)
 {
     #if NET2
     CompilerParameters cp = new CompilerParameters();
     cp.ReferencedAssemblies.Add("System.dll");
     cp.GenerateInMemory = false;
     cp.OutputAssembly = fileName;
     CompilerResults cr = provider.CompileAssemblyFromDom(cp, compileunit);
     #else
     ICodeCompiler compiler = provider.CreateCompiler();
     CompilerParameters cp = new CompilerParameters();
     cp.ReferencedAssemblies.Add( "System.dll" );
     cp.GenerateInMemory = false;
     cp.OutputAssembly = fileName;
      			CompilerResults cr = compiler.CompileAssemblyFromDom(cp, compileunit);
     #endif
 }