Example #1
0
        /// <summary>
        /// Compiles an assembly from the proxy class provided by the ServiceDescriptionImporter.
        /// </summary>
        /// <param name="descriptionImporter"></param>
        /// <returns>An assembly that can be used to execute the web service methods.</returns>
        private Assembly CompileAssembly(ServiceContractGenerator serviceContractGenerator)
        {
            // a namespace and compile unit are needed by importer
            CodeNamespace   codeNamespace = new CodeNamespace();
            CodeCompileUnit codeUnit      = new CodeCompileUnit();

            codeUnit.Namespaces.Add(codeNamespace);

            // create a c# compiler
            CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");

            // include the assembly references needed to compile
            string[] references = new string[5] {
                "System.Web.Services.dll", "System.Xml.dll", "System.ServiceModel.dll", "System.configuration.dll", "System.Runtime.Serialization.dll"
            };
            string             progFiles  = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            CompilerParameters parameters = new CompilerParameters(references);

            parameters.CompilerOptions = string.Format(@" /lib:{0}", string.Format("\"{0}\\Reference Assemblies\\Microsoft\\Framework\\v3.0\"", progFiles));

            // compile into assembly
            CompilerResults results = compiler.CompileAssemblyFromDom(parameters, serviceContractGenerator.TargetCompileUnit);

            foreach (CompilerError oops in results.Errors)
            {
                // trap these errors and make them available to exception object
                throw new Exception("Compilation Error Creating Assembly");
            }

            // all done....
            return(results.CompiledAssembly);
        }
Example #2
0
    private static Assembly CompileAssembly(ServiceDescriptionImporter descriptionImporter)
    {
        CodeNamespace   codeNamespace = new CodeNamespace();
        CodeCompileUnit codeUnit      = new CodeCompileUnit();

        codeUnit.Namespaces.Add(codeNamespace);

        ServiceDescriptionImportWarnings importWarnings = descriptionImporter.Import(codeNamespace, codeUnit);

        if (importWarnings == 0)
        {
            CodeDomProvider    compiler   = CodeDomProvider.CreateProvider("CSharp");
            string[]           references = { "System.Web.Services.dll", "System.Xml.dll" };
            CompilerParameters parameters = new CompilerParameters(references);
            CompilerResults    results    = compiler.CompileAssemblyFromDom(parameters, codeUnit);

            if (results.Errors.Count > 0)
            {
                throw new Exception("Compilation Error Creating Assembly");
            }

            return(results.CompiledAssembly);
        }
        else
        {
            throw new Exception("Invalid WSDL");
        }
    }
Example #3
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 #4
0
        /// <summary>
        /// Builds the proxy class for specified interface and source types.
        /// </summary>
        /// <param name="interfaceType">Type of the interface.</param>
        /// <param name="sourceType">Type of the source.</param>
        /// <returns>Type definition for proxy class.</returns>
        private static Type BuildProxyClass(Type interfaceType, Type sourceType)
        {
            CodeCompileUnit compileUnit = GenProxyClass(interfaceType, sourceType);
            CodeDomProvider provider    = CodeDomProvider.CreateProvider("CSharp");

            // Generate the code
            using (StringWriter wr = new StringWriter())
            {
                provider.GenerateCodeFromCompileUnit(compileUnit, wr, new CodeGeneratorOptions());
                string code = wr.ToString();
            }

            // Compile the code
            var res = provider.CompileAssemblyFromDom(new CompilerParameters(), compileUnit);

            if (res.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in res.Errors)
                {
                    sb.AppendLine(error.Line + "\t" + error.ErrorNumber + "\t" + error.ErrorText);
                }

                throw new Exception("Error compiling proxy class:\n" + sb.ToString());
            }

            return(res.CompiledAssembly.GetTypes()[0]);
        }
Example #5
0
        private bool CompileMode(CodeCompileUnit unit, out IUtilityComponentMode optimizedMode, ref string error)
        {
            var options = new CompilerParameters();

            options.IncludeDebugInformation = false;
            options.GenerateInMemory        = true;
            options.CompilerOptions         = "/optimize";
            CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
            var             results  = compiler.CompileAssemblyFromDom(options, unit);

            if (this.IncludeCode)
            {
                using (StreamWriter writer = new StreamWriter(String.Format("TMG.Modes.Generated.OptimizedMode{0}.cs", this.ModeName)))
                {
                    //var results = compiler.CompileAssemblyFromDom( options, writer, unit );
                    compiler.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
                }
            }
            if (results.Errors.Count != 0)
            {
                error         = results.Errors[0].ToString();
                optimizedMode = null;
                return(false);
            }
            var assembly    = results.CompiledAssembly;
            var theClass    = assembly.GetType(String.Format("TMG.Modes.Generated.OptimizedMode{0}", this.ModeName));
            var constructor = theClass.GetConstructor(new Type[0]);

            optimizedMode = constructor.Invoke(new object[0]) as IUtilityComponentMode;
            return(true);
        }
Example #6
0
        private Assembly Compile(CodeCompileUnit unit, CodeDomProvider provider)
        {
            CompilerParameters compile_params = new CompilerParameters();
            TempFileCollection temp_files     = new TempFileCollection(Path.GetTempPath());

            bool enable_debugging = HasFlag(RpcClientBuilderFlags.EnableDebugging);

            compile_params.GenerateExecutable      = false;
            compile_params.GenerateInMemory        = true;
            compile_params.IncludeDebugInformation = enable_debugging;
            compile_params.TempFiles = temp_files;
            temp_files.KeepFiles     = enable_debugging;
            compile_params.ReferencedAssemblies.Add(typeof(RpcClientBuilder).Assembly.Location);
            CompilerResults results = provider.CompileAssemblyFromDom(compile_params, unit);

            if (results.Errors.HasErrors)
            {
                foreach (CompilerError e in results.Errors)
                {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }
                throw new InvalidOperationException("Internal error compiling RPC source code");
            }
            return(results.CompiledAssembly);
        }
Example #7
0
        /// <summary>
        /// 创建指定路径的模板解析后的模板类型。
        /// </summary>
        /// <param name="templateReader">用于获取模板内容的 <see cref="TextReader"/> 对象。</param>
        /// <param name="className">模板编译后的类名。默认为根据 <paramref name="sourceFileName"/> 动态生成。</param>
        /// <param name="rootNamespace">模板编译后的名字空间。默认为 RazorCompiledTemplates 。</param>
        /// <param name="sourceFileName">模板的文件名或模板的别名,用于在模板互相引用时使用。模板的名字作为模板的唯一标识符,应该保证其唯一性。默认为模板文件的路径或模板字符串本身的哈希值。</param>
        /// <param name="baseClassName">模板编译后的默认基类。如果值为 null,则使用 <see cref="TemplateBase&lt;T&gt;"/> 作为模板基类。在模板中可以通过 @inherits 关键字来覆盖这里的设置。</param>
        /// <param name="modelType">模板编译后的模型类型。如果值为 null,则表示不使用模板对象。未来版本中,在模板中可以通过 @model 关键字来覆盖这里的设置。</param>
        public Type AddTemplateType(TextReader templateReader, string className, string rootNamespace, string sourceFileName, string baseClassName, Type modelType)
        {
            // 1. 编译为 DOM 语法树。
            GeneratorResults generatorResult = GenerateCode(templateReader, className, rootNamespace, sourceFileName, baseClassName, modelType);

            if (!generatorResult.Success)
            {
                throw new RazorParseException(generatorResult.ParserErrors);
            }

            // 2. 编译为动态的类型。
            CompilerResults compilerResults = CodeDomProvider.CompileAssemblyFromDom(CompilerParameters, generatorResult.GeneratedCode);

#if PARSER_DEBUG
            StringBuilder sb     = new StringBuilder();
            TextWriter    writer = new StringWriter(sb);
            CodeDomProvider.GenerateCodeFromCompileUnit(generatorResult.GeneratedCode, writer, new CodeGeneratorOptions());
            Console.Write(sb.ToString());
            File.WriteAllText("D:\\aa.cs", sb.ToString());
#endif

            if (compilerResults.Errors.Count > 0)
            {
                throw new RazorComplieException(compilerResults.Errors);
            }

            // 3. 获取刚创建的类型。
            Type type = compilerResults.CompiledAssembly.GetType(String.IsNullOrEmpty(rootNamespace) ? className : String.Concat(rootNamespace, ".", className));

            // 4. 加入缓存列表。
            _templateTypeCache[sourceFileName] = new Tuple <Type, Type>(type, modelType);

            return(type);
        }
Example #8
0
        public Assembly Compile(string assemblyPath)
        {
            CompilerParameters options = new CompilerParameters();
            options.IncludeDebugInformation = false;
            options.GenerateExecutable = false;
            options.GenerateInMemory = (assemblyPath == null);
            foreach (string refAsm in listReferencedAssemblies)
                options.ReferencedAssemblies.Add(refAsm);
            if (assemblyPath != null)
                options.OutputAssembly = assemblyPath.Replace('\\', '/');

            CodeDomProvider codeProvider = Provider(_language);

            CompilerResults results =
               codeProvider.CompileAssemblyFromDom(options, CompileUnit);
            codeProvider.Dispose();

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

            // Process compilation errors
            System.Diagnostics.Trace.WriteLine("Compilation Errors:");
            foreach (string outpt in results.Output)
                System.Diagnostics.Trace.WriteLine(outpt);
            foreach (CompilerError err in results.Errors)
                System.Diagnostics.Trace.WriteLine(err.ToString());

            return null;
        }
Example #9
0
        /// <summary>
        /// 创建一个调用webservice的本地代理DLL
        /// </summary>
        /// <param name="url"></param>
        public static void CreateWebServiceDLL()
        {
            string smsfile = HttpContext.Current.Server.MapPath("~") + "dll" + "\\SMSWebservice.dll";

            if (!File.Exists(smsfile))
            {
                return;
            }
            try
            {
                string url = smsWSDL;
                url = url.ToUpper().Contains("?WSDL") ? url : (url + "?WSDL");
                // 1. 使用 WebClient 下载 WSDL 信息。
                WebClient web    = new WebClient();
                Stream    stream = web.OpenRead(url);
                // 2. 创建和格式化 WSDL 文档。
                ServiceDescription description = ServiceDescription.Read(stream);
                // 3. 创建客户端代理代理类。
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                importer.ProtocolName          = "Soap";                               // 指定访问协议。
                importer.Style                 = ServiceDescriptionImportStyle.Client; // 生成客户端代理。
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                importer.AddServiceDescription(description, null, null);               // 添加 WSDL 文档。
                // 4. 使用 CodeDom 编译客户端代理类。
                CodeNamespace   nmspace = new CodeNamespace();                         // 为代理类添加命名空间,缺省为全局空间。
                CodeCompileUnit unit    = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                string file = HttpContext.Current.Server.MapPath("~") + "dll";
                if (!Directory.Exists(file))
                {
                    Directory.CreateDirectory(file);
                }
                parameter.OutputAssembly = file + "\\SMSWebservice.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");
                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
                if (result.Errors.HasErrors)
                {
                    // 显示编译错误信息
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in result.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #10
0
        ///	<summary>
        ///	得到WSDL信息,生成本地代理类并编译为DLL
        ///	</summary>
        private void CreateServiceAssembly()
        {
            if (this.checkCache())
            {
                this.initTypeName();
                return;
            }
            if (string.IsNullOrEmpty(this._wsdlUrl))
            {
                return;
            }
            try
            {
                //使用WebClient下载WSDL信息
                WebClient          web         = new WebClient();
                Stream             stream      = web.OpenRead(this._wsdlUrl);
                ServiceDescription description = ServiceDescription.Read(stream);//创建和格式化WSDL文档
                stream.Close();
                web.Dispose();

                ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类
                importer.ProtocolName          = "Soap";
                importer.Style                 = ServiceDescriptionImportStyle.Client;  //生成客户端代理
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                importer.AddServiceDescription(description, null, null);                //添加WSDL文档
                //使用CodeDom编译客户端代理类
                CodeNamespace   nmspace = new CodeNamespace(_assName);                  //为代理类添加命名空间
                CodeCompileUnit unit    = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);
                this.checkForImports(this._wsdlUrl, importer);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters parameter = new CompilerParameters();
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");
                parameter.GenerateExecutable      = false;
                parameter.GenerateInMemory        = false;
                parameter.IncludeDebugInformation = false;
                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
                provider.Dispose();
                if (result.Errors.HasErrors)
                {
                    string errors = string.Format(@"编译错误:{0}错误!", result.Errors.Count);
                    foreach (CompilerError error in result.Errors)
                    {
                        errors += error.ErrorText;
                    }
                    throw new Exception(errors);
                }
                this.copyTempAssembly(result.PathToAssembly);
                this.initTypeName();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Example #11
0
        /// <summary>
        /// This function will create a new IDataLink for the given Types and associations
        /// </summary>
        /// <typeparam name="T">The type that we will be saving into</typeparam>
        /// <param name="originTypes">The types that we will be loading from</param>
        /// <param name="Links"></param>
        /// <returns>A new IDataLink object that will automate the copying of data</returns>
        public static IDataLink <T> CreateDataLink <T>(Type[] originTypes, KeyValuePair <string, KeyValuePair <int, string> >[] Links)
        {
            Type            destinationType = typeof(T);
            CodeCompileUnit unit            = new CodeCompileUnit();

            unit.ReferencedAssemblies.Add(Assembly.GetCallingAssembly().Location);
            CodeNamespace namespaceXTMF = new CodeNamespace("XTMF.DataUtilities.Generated");

            namespaceXTMF.Imports.Add(new CodeNamespaceImport("System"));
            namespaceXTMF.Imports.Add(new CodeNamespaceImport("XTMF.DataUtilities"));
            unit.Namespaces.Add(namespaceXTMF);
            long uniqueID = DateTime.Now.Ticks;
            CodeTypeDeclaration transitionClass = new CodeTypeDeclaration(String.Format("TransitionClass{0}", uniqueID));

            transitionClass.BaseTypes.Add(new CodeTypeReference(String.Format("IDataLink<{0}>", destinationType.FullName)));
            CodeMemberMethod CopyMethod = new CodeMemberMethod();

            CopyMethod.Name       = "Copy";
            CopyMethod.Attributes = MemberAttributes.Public;
            var destintation = new CodeParameterDeclarationExpression(destinationType, "destination");
            var origin       = new CodeParameterDeclarationExpression(typeof(object[]), "origin");

            CopyMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { destintation, origin });
            foreach (KeyValuePair <string, KeyValuePair <int, string> > link in Links)
            {
                //destination."link.Key" = origin[link.Value.Key]."link.Value.Value";
                Type originField, destinationField;
                if (!CheckTypes(destinationType, link.Key, originTypes[link.Value.Key], link.Value.Value, out destinationField, out originField))
                {
                    throw new XTMFRuntimeException(String.Format("Type miss-match error between {0}:{2} to {1}:{3}!",
                                                                 originField.Name, destinationField.Name, link.Value.Value, link.Key));
                }
                CodeAssignStatement assign = new CodeAssignStatement(
                    new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("destination"), link.Key),
                    new CodeFieldReferenceExpression(new CodeCastExpression(originTypes[link.Value.Key],
                                                                            new CodeIndexerExpression(new CodeVariableReferenceExpression("origin"), new CodePrimitiveExpression(link.Value.Key))), link.Value.Value)
                    );
                CopyMethod.Statements.Add(assign);
            }
            transitionClass.Members.Add(CopyMethod);
            namespaceXTMF.Types.Add(transitionClass);
            CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
            var             options  = new CompilerParameters();

            options.IncludeDebugInformation = false;
            options.GenerateInMemory        = true;
            var results = compiler.CompileAssemblyFromDom(options, unit);

            if (results.Errors.Count != 0)
            {
                throw new XTMFRuntimeException(results.Errors[0].ToString());
            }
            var assembly    = results.CompiledAssembly;
            var theClass    = assembly.GetType(String.Format("XTMF.DataUtilities.Generated.TransitionClass{0}", uniqueID));
            var constructor = theClass.GetConstructor(new Type[0]);
            var output      = constructor.Invoke(new object[0]);

            return(output as IDataLink <T>);
        }
Example #12
0
        /// <summary>
        /// 动态调用WebService
        /// </summary>
        /// <param name="url">WebService地址</param>
        /// <param name="classname">类名</param>
        /// <param name="methodname">方法名(模块名)</param>
        /// <param name="args">参数列表</param>
        /// <returns>object</returns>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "fangqm.Netbank.WebService.webservice";

            if (classname == null || classname == "")
            {
                classname = WebServiceHelper.GetClassName(url);
            }

            //获取服务描述语言(WSDL)
            WebClient                  wc     = new WebClient();
            Stream                     stream = wc.OpenRead(url + "?WSDL");       //【1】
            ServiceDescription         sd     = ServiceDescription.Read(stream);  //【2】
            ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter(); //【3】

            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace(@namespace);//【4】

            //生成客户端代理类代码
            CodeCompileUnit ccu = new CodeCompileUnit();//【5】

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider csc = new CSharpCodeProvider();                 //【6】
            CodeDomProvider    icc = CodeDomProvider.CreateProvider("CSharp"); //【7】

            //设定编译器的参数
            CompilerParameters cplist = new 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");

            //编译代理类
            CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);//【9】

            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new StringBuilder();
                foreach (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);                  //【10】

            System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】
            return(mi.Invoke(obj, args));
        }
        public override Type Generate(IInterceptor interceptor, Type baseType, Type handlerType, params Type[] additionalInterfaceTypes)
        {
            var properties   = this.GetProperties(baseType, additionalInterfaceTypes);
            var methods      = this.GetMethods(baseType, additionalInterfaceTypes);
            var constructors = this.GetConstructors(baseType);

            var targetClass = new CodeTypeDeclaration(string.Concat(baseType.Name, "_Dynamic"));

            targetClass.IsClass        = baseType.IsClass;
            targetClass.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.Serializable;
            targetClass.BaseTypes.Add((baseType.IsInterface == false) ? baseType : typeof(object));
            targetClass.BaseTypes.Add(proxyTypeReference.BaseType);

            foreach (var additionalInterfaceType in additionalInterfaceTypes)
            {
                targetClass.BaseTypes.Add(additionalInterfaceType);
            }

            var samples = new CodeNamespace(baseType.Namespace);

            samples.Imports.Add(new CodeNamespaceImport(typeof(string).Namespace));
            samples.Types.Add(targetClass);

            var targetUnit = new CodeCompileUnit();

            targetUnit.Namespaces.Add(samples);

            this.GenerateFields(targetClass, baseType, handlerType, (interceptor != null) ? interceptor.GetType() : null);

            this.GenerateConstructors(targetClass, baseType, constructors);

            this.GenerateMethods(targetClass, baseType, methods);

            this.GenerateProperties(targetClass, baseType, properties);

            var builder = new StringBuilder();

            using (var sourceWriter = new StringWriter(builder))
            {
                provider.GenerateCodeFromCompileUnit(targetUnit, sourceWriter, options);
            }

            var parameters = new CompilerParameters()
            {
                GenerateInMemory = true
            };

            this.AddReferences(parameters, baseType, handlerType, (interceptor != null) ? interceptor.GetType() : null, additionalInterfaceTypes);

            var results = provider.CompileAssemblyFromDom(parameters, targetUnit);

            if (results.Errors.HasErrors == true)
            {
                throw new InvalidOperationException(string.Join(Environment.NewLine, results.Errors.OfType <object>()));
            }

            return(results.CompiledAssembly.GetTypes().First());
        }
Example #14
0
        public bool SetWebServiceInstance(string webServiceAsmxUrl, string serviceName)
        {
            bool   success  = false;
            string lastStep = "";

            try
            {
                LastError = "";
                lastStep  = "Getting web service description/specification";
                WebClient                  client      = new WebClient();
                Stream                     stream      = client.OpenRead(webServiceAsmxUrl + "?wsdl");
                ServiceDescription         description = ServiceDescription.Read(stream);
                ServiceDescriptionImporter importer    = new ServiceDescriptionImporter();
                //ServiceContractGenerator
                importer.ProtocolName = "Soap12";
                importer.AddServiceDescription(description, null, null);
                importer.Style = ServiceDescriptionImportStyle.Client;
                importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
                CodeNamespace   nmspace = new CodeNamespace();
                CodeCompileUnit unit1   = new CodeCompileUnit();
                unit1.Namespaces.Add(nmspace);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

                if (warning == 0)
                {
                    CodeDomProvider provider1          = CodeDomProvider.CreateProvider("CSharp");
                    string[]        assemblyReferences = new string[] { "System.dll",
                                                                        "System.Web.Services.dll", "System.Web.dll",
                                                                        "System.Xml.dll", "System.Data.dll" };
                    CompilerParameters parms = new CompilerParameters(assemblyReferences);
                    parms.GenerateInMemory = true;
                    CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

                    if (results.Errors.Count > 0)
                    {
                        foreach (CompilerError oops in results.Errors)
                        {
                            System.Diagnostics.Debug.WriteLine("========Compiler error============");
                            System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                        }
                        throw new System.Exception("Compile Error Occurred calling webservice.");
                    }

                    lastStep           = "Creating instance of web service client";
                    WebServiceInstance = results.CompiledAssembly.CreateInstance(serviceName);
                    success            = true;
                }
                else
                {
                    LastError = string.Format("ServiceDescriptionImporter returned {0}", warning);
                }
            }
            catch (Exception ex)
            {
                LastError = string.Format("Last step: {0}\r\n{1}", lastStep, ex.ToString());
            }
            return(success);
        }
Example #15
0
        private void AddMemberDefinition()
        {
            CodeCompileUnit compileUnit = GenerateMemberDefinitionCodeDom();
            CompilerResults results     = CodeDomProvider.CompileAssemblyFromDom(GetCompilerParameters(), compileUnit);

            ReportResults(results);

            WriteTypesAdded(results);
        }
Example #16
0
        private CompilerResults Compile(CodeDomProvider provider, CompilerParameters cp)
        {
            if (sourceFiles != null)
            {
                return(provider.CompileAssemblyFromFile(cp, sourceFiles.ToArray()));
            }

            return(provider.CompileAssemblyFromDom(cp, compileUnits.ToArray()));
        }
Example #17
0
        private static IRead <D, S> CreateReader <S>(Type instanceType, string[] variableNameParts, Type[] sourceType, bool[] property)
        {
            var             destinationType = typeof(D);
            CodeCompileUnit unit            = new CodeCompileUnit();

            AddReferences(unit);
            CodeNamespace       namespaceXTMF  = AddNamespaces(unit);
            long                uniqueID       = DateTime.Now.Ticks;
            CodeTypeDeclaration realTimeReader = new CodeTypeDeclaration(String.Format("RealtimeCompiledReader{0}", uniqueID));

            realTimeReader.BaseTypes.Add(new CodeTypeReference(String.Format("IRead<{0},{1}>", destinationType.FullName, typeof(S))));
            CodeMemberMethod CopyMethod = new CodeMemberMethod();

            CopyMethod.Name       = "Read";
            CopyMethod.Attributes = MemberAttributes.Public;
            CopyMethod.ReturnType = new CodeTypeReference(typeof(bool));
            var readFrom = new CodeParameterDeclarationExpression(typeof(S), "readFrom")
            {
                Direction = FieldDirection.In
            };
            var storeIn = new CodeParameterDeclarationExpression(typeof(D), "result")
            {
                Direction = FieldDirection.Out
            };

            CopyMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { readFrom, storeIn });
            CopyMethod.Statements.Add(CreateAssingmentStatement(storeIn, readFrom, instanceType, variableNameParts, sourceType, property));
            CopyMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
            realTimeReader.Members.Add(CopyMethod);
            namespaceXTMF.Types.Add(realTimeReader);
            CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
            var             options  = new CompilerParameters();

            options.IncludeDebugInformation = false;
            options.GenerateInMemory        = true;
            options.CompilerOptions         = "/optimize";

            /*using ( StreamWriter writer = new StreamWriter( "code.cs" ) )
             * {
             *  compiler.GenerateCodeFromCompileUnit( unit, writer, new CodeGeneratorOptions() );
             *  return null;
             * }*/
            var results = compiler.CompileAssemblyFromDom(options, unit);

            if (results.Errors.Count != 0)
            {
                throw new XTMFRuntimeException(results.Errors[0].ToString());
            }

            var assembly    = results.CompiledAssembly;
            var theClass    = assembly.GetType(String.Format("XTMF.DataUtilities.Generated.RealtimeCompiledReader{0}", uniqueID));
            var constructor = theClass.GetConstructor(new Type[0]);
            var output      = constructor.Invoke(new object[0]);

            return(output as IRead <D, S>);
        }
Example #18
0
        int DoCompilePass(Dictionary <string, CodeCompileUnit> units)
        {
            CompilerParameters parms = new CompilerParameters();

            // Params

            parms.GenerateExecutable      = false;
            parms.OutputAssembly          = outfile;
            parms.TempFiles.KeepFiles     = debug_preserve;
            parms.IncludeDebugInformation = gen_debug_info;

            foreach (string assy in refs)
            {
                parms.ReferencedAssemblies.Add(assy);
            }

            foreach (string id in resources.Keys)
            {
                string file = (string)resources[id];

                parms.CompilerOptions += String.Format("{0}{1},{2} ", resource_arg,
                                                       file, id);
            }

            // Do it

            CodeCompileUnit[] array = new CodeCompileUnit[units.Count];
            units.Values.CopyTo(array, 0);

            CompilerResults res = prov.CompileAssemblyFromDom(parms, array);

            if (debug_preserve)
            {
                Console.Error.WriteLine("Source files not being deleted:");
                foreach (string s in parms.TempFiles)
                {
                    Console.Error.WriteLine("        {0}", s);
                }
                Console.Error.WriteLine();
            }

            if (res.Errors.Count > 0)
            {
                foreach (string s in res.Output)
                {
                    Console.Error.WriteLine("{0}", s);
                }

                foreach (CompilerError err in res.Errors)
                {
                    Console.Error.WriteLine("{0}", err);
                }
            }

            return(res.NativeCompilerReturnValue);
        }
Example #19
0
        public ICompilerResult FromUnit(CodeCompileUnit unit, string assemblyFile)
        {
            Ensure.NotNull(unit, "unit");
            Ensure.NotNullOrEmpty(assemblyFile, "assemblyFile");

            if (Configuration.IsDebugMode())
            {
                using (StringWriter writer = new StringWriter())
                {
                    provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
                    File.WriteAllText(Path.ChangeExtension(assemblyFile, ".cs"), writer.ToString());
                }
            }

            CompilerParameters compilerParameters = PrepareCompilerParameters(assemblyFile);
            CompilerResults    compilerResults    = provider.CompileAssemblyFromDom(compilerParameters, unit);

            return(ProcessCompilerResults(compilerResults));
        }
        public static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            // Connect To the web service
            System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
            // Now read the WSDL file describing a service.
            ServiceDescription description = ServiceDescription.Read(stream);
            ///// LOAD THE DOM /////////
            // Initialize a service description importer.
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName = "Soap12";                     // Use SOAP 1.2.
            importer.AddServiceDescription(description, null, null);
            // Generate a proxy client.
            importer.Style = ServiceDescriptionImportStyle.Client;
            // Generate properties to represent primitive values.
            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            // Initialize a Code-DOM tree into which we will import the service.
            CodeNamespace   nmspace = new CodeNamespace();
            CodeCompileUnit unit1   = new CodeCompileUnit();

            unit1.Namespaces.Add(nmspace);
            // Import the service into the Code-DOM tree. This creates proxy code that uses the service.
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

            if (warning == 0)                     // If zero then we are good to go
            {
                // Generate the proxy code
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
                // Compile the assembly proxy with the appropriate references
                string[] assemblyReferences = new string[5] {
                    "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll"
                };
                CompilerParameters parms   = new CompilerParameters(assemblyReferences);
                CompilerResults    results = provider1.CompileAssemblyFromDom(parms, unit1);
                // Check For Errors
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError oops in results.Errors)
                    {
                        System.Diagnostics.Debug.WriteLine("========Compiler error============");
                        System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                    }
                    throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
                }
                // Finally, Invoke the web service method
                object     wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
                MethodInfo mi        = wsvcClass.GetType().GetMethod(methodName);
                return(mi.Invoke(wsvcClass, args));
            }
            else
            {
                return(null);
            }
        }
Example #21
0
        private static bool CreateWebServiceAssembly(ServiceDescription description, DBandMES dbandMES, ref string error)
        {
            // 创建客户端代理类。
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter {
                ProtocolName          = "Soap",
                Style                 = ServiceDescriptionImportStyle.Client,
                CodeGenerationOptions =
                    CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync
            };

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

            //使用 CodeDom 编译客户端代理类。
            CodeNamespace   nmspace = new CodeNamespace();
            CodeCompileUnit unit    = new CodeCompileUnit();

            unit.Namespaces.Add(nmspace);

            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);

            error += "ServiceDescriptionImportWarnings\"" + GetWarningMeaning(warning) + "\", ";

            using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp")) {
                CompilerParameters parameter = new CompilerParameters {
                    GenerateExecutable = false,
                    // 指定输出dll文件名。
                    OutputAssembly = m_OutputDllFilename
                };

                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");

                // 编译输出程序集
                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

                // 使用 Reflection 调用 WebService。
                if (!result.Errors.HasErrors)
                {
                    BuildMethods(dbandMES.GetMethodArray());
                    if (error.Length > 0)
                    {
                        error = error.Substring(0, error.Length - 3);
                    }
                    return(true);
                }
                else
                {
                    error += "反射生成dll文件时异常";
                }
            }
            return(false);
        }
        private Tuple <CompilerResults, string> Compile(TypeContext context, string name)
        {
            var    key          = Common.StrToMD5(name);
            string className    = "C" + key;
            var    assemblyPath = CatchPath + className + ".dll";

            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces,
                                                 context.TemplateType, context.ModelType);

            var @params = new CompilerParameters
            {
                GenerateInMemory        = true,
                OutputAssembly          = @assemblyPath,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/target:library /optimize"
            };

            var assemblies = CompilerServicesUtility
                             .GetLoadedAssemblies()
                             .Where(a => !a.IsDynamic)
                             .Select(a => a.Location);

            var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty <string>());

            assemblies = assemblies.Concat(includeAssemblies)
                         .Select(a => a.ToUpperInvariant())
                         .Where(a => !string.IsNullOrWhiteSpace(a))
                         .Distinct();

            @params.ReferencedAssemblies.AddRange(assemblies.ToArray());

            string sourceCode = null;
            // if (Debug)
            //  {
            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
                sourceCode = builder.ToString();
            }

            //  CompileType(context.ClassName, sourceCode);
            //  }
            CompilerResults r = _codeDomProvider.CompileAssemblyFromDom(@params, compileUnit);

            return(Tuple.Create(r, sourceCode));
        }
Example #23
0
        //data loader
        object GetObjectManagerService(string WebServer, string WebServerU, string WebServerP)
        {
            if (string.IsNullOrEmpty(WebServer))
            {
                throw new Exception("Invalid web server address!");
            }
            //store all instances of service class as each instance is a separate dll and loaded each time into memory
            string hash = Webhash(WebServer, WebServerU, WebServerP);

            if (WebServices.ContainsKey(hash))
            {
                return(WebServices[hash]);
            }

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                CorrectWebAddress(ref WebServer);

                System.IO.Stream stream = client.OpenRead(WebServer + ObjectManagerServiceName + ".asmx?wsdl");
                importer.ProtocolName = "Soap12";
                ServiceDescription description = ServiceDescription.Read(stream);
                importer.AddServiceDescription(description, null, null);
                importer.Style = ServiceDescriptionImportStyle.Client;
            }

            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            CodeNamespace nmspace = new CodeNamespace();

            NameSpaceCounter++;
            CodeCompileUnit CompileUnit = new CodeCompileUnit();

            CompileUnit.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, CompileUnit);

            if (warning == 0)
            {
                string[] assemblyReferences = new string[2] {
                    "System.Web.Services.dll", "System.Xml.dll"
                };
                CompilerParameters parms = new CompilerParameters(assemblyReferences);
                CompilerResults    results;
                using (CodeDomProvider DomProvider = CodeDomProvider.CreateProvider("CSharp"))
                {
                    results = DomProvider.CompileAssemblyFromDom(parms, CompileUnit);
                }

                object wsvcClass = results.CompiledAssembly.CreateInstance(ObjectManagerServiceName);
                WebServices[hash] = wsvcClass;
                return(wsvcClass);
            }
            throw new Exception(message: "Failed to connect to web servie. Check web server exists.");
        }
Example #24
0
        CompilerResults Compile(CodeCompileUnit compileUnit, AssemblyName assemblyName)
        {
            var options = assemblyName != null
                ? new CompilerParameters(AssemblyReferences, assemblyName.CodeBase, true)
                : new CompilerParameters(AssemblyReferences)
            {
                GenerateInMemory = true
            };

            return(codeProvider.CompileAssemblyFromDom(options, compileUnit));
        }
        private Tuple <CompilerResults, string> Compile(TypeContext context)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces,
                                                 context.TemplateType, context.ModelType);

            var @params = new CompilerParameters
            {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/target:library /optimize"
            };

            var assemblies = CompilerServicesUtility
                             .GetLoadedAssemblies()
                             .Where(a => !a.IsDynamic)
                             .Select(a => a.Location);

            var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty <string>());

            assemblies = assemblies.Concat(includeAssemblies)
                         .Select(a => a)
                         .Where(a => !string.IsNullOrWhiteSpace(a))
                         .Distinct();

            //@params.ReferencedAssemblies.AddRange(assemblies.ToArray());
            @params.ReferencedAssemblies.Add("mscorlib.dll");
            @params.ReferencedAssemblies.Add("System.dll");
            @params.ReferencedAssemblies.Add("System.Web.Razor.dll");
            @params.ReferencedAssemblies.Add("DWServer.exe");
            @params.ReferencedAssemblies.Add("System.Core.dll");

            string sourceCode = null;

            if (Debug)
            {
                var builder = new StringBuilder();
                using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
                {
                    _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
                    sourceCode = builder.ToString();
                }

                sourceCode += string.Join("\n", assemblies.ToArray());
            }

            return(Tuple.Create(_codeDomProvider.CompileAssemblyFromDom(@params, compileUnit), sourceCode));
        }
        public static void Build(string[] dlls)
        {
            CompilerParameters opt = new CompilerParameters(new string[] {
                "System.dll", "IICCommonLibrary.dll"
            });

            if (dlls != null)
            {
                foreach (var dll in dlls)
                {
                    opt.ReferencedAssemblies.Add(dll);
                }
            }
            opt.GenerateExecutable      = false;
            opt.TreatWarningsAsErrors   = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory        = true;

            CodeDomProvider provider = CodeDomProvider.CreateProvider("cs");

            StringWriter sw = new StringWriter();

            provider.GenerateCodeFromCompileUnit(CompileUnit, sw, null);
            string output = sw.ToString();

            _tracing.Info(output);
            sw.Close();

            CompilerResults results = provider.CompileAssemblyFromDom(opt, CompileUnit);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                _tracing.Warn("Compilation failed.");
                throw new ApplicationException("Compilation failed.");
            }
            else
            {
                _tracing.Info("completed successfully.");
            }

            Type typeMethodHelper = results.CompiledAssembly
                                    .GetType("Imps.Generics.DynamicTypes.TransparentMethodHelper");

            foreach (var pair in dict)
            {
                RpcGetArgsDelegate getArgs;
                MethodInfo         mi = typeMethodHelper.GetMethod(pair.Key);
                getArgs = (RpcGetArgsDelegate)RpcGetArgsDelegate.CreateDelegate(
                    typeof(RpcGetArgsDelegate), mi);
                pair.Value.GetArgs = getArgs;
            }
        }
Example #27
0
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            object obj3;
            string name = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = GetWsClassName(url);
            }
            try
            {
                WebClient                  client             = new WebClient();
                ServiceDescription         serviceDescription = ServiceDescription.Read(client.OpenRead(url + "?WSDL"));
                ServiceDescriptionImporter importer           = new ServiceDescriptionImporter {
                    ProtocolName          = "Soap",
                    Style                 = ServiceDescriptionImportStyle.Client,
                    CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties
                };
                importer.AddServiceDescription(serviceDescription, "", "");
                CodeNamespace   namespace2      = new CodeNamespace(name);
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(namespace2);
                importer.Import(namespace2, codeCompileUnit);
                CodeDomProvider    provider = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters options  = new CompilerParameters {
                    GenerateExecutable = false,
                    GenerateInMemory   = true
                };
                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.XML.dll");
                options.ReferencedAssemblies.Add("System.Web.Services.dll");
                options.ReferencedAssemblies.Add("System.Data.dll");
                CompilerResults results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { codeCompileUnit });
                if (results.Errors.HasErrors)
                {
                    StringBuilder builder = new StringBuilder();
                    foreach (CompilerError error in results.Errors)
                    {
                        builder.Append(error.ToString());
                        builder.Append(Environment.NewLine);
                    }
                    throw new Exception(builder.ToString());
                }
                Type   type = results.CompiledAssembly.GetType(name + "." + classname, true, true);
                object obj2 = Activator.CreateInstance(type);
                obj3 = type.GetMethod(methodname).Invoke(obj2, args);
            }
            catch (Exception exception)
            {
                throw new Exception(exception.InnerException.Message, new Exception(exception.InnerException.StackTrace));
            }
            return(obj3);
        }
        /// <summary>
        /// 根据WebService的URL,生成一个本地的dll,并返回WebService的实例
        /// 创建人:程媛媛 创建时间:2010-6-21
        /// </summary>
        /// <param name="url">WebService的UR</param>
        /// <returns></returns>
        public static object GetWebServiceInstance(string url)
        {
            string @namespace = "ServiceBase.WebService.DynamicWebLoad";
            string classname  = WebServiceHelper.GetClassName(url);
            // 1. 使用 WebClient 下载 WSDL 信息。
            WebClient web    = new WebClient();
            Stream    stream = web.OpenRead(url + "?WSDL");
            // 2. 创建和格式化 WSDL 文档。
            ServiceDescription description = ServiceDescription.Read(stream);
            // 3. 创建客户端代理代理类。
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName          = "Soap";                               // 指定访问协议。
            importer.Style                 = ServiceDescriptionImportStyle.Client; // 生成客户端代理。
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
            importer.AddServiceDescription(description, null, null);               // 添加 WSDL 文档。
            // 4. 使用 CodeDom 编译客户端代理类。
            CodeNamespace   nmspace = new CodeNamespace(@namespace);               // 为代理类添加命名空间,缺省为全局空间。
            CodeCompileUnit unit    = new CodeCompileUnit();

            unit.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters parameter = new CompilerParameters();

            parameter.GenerateExecutable = false;
            parameter.OutputAssembly     = Application.StartupPath + "//DBMS_Service.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");
            CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

            if (result.Errors.HasErrors)
            {
                // 显示编译错误信息
                System.Text.StringBuilder sb = new StringBuilder();
                foreach (CompilerError ce in result.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new Exception(sb.ToString());
            }
            //生成代理实例
            System.Reflection.Assembly assembly = Assembly.Load("DBMS_Service");
            Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
            object obj = Activator.CreateInstance(t);

            return(obj);
        }
Example #29
0
        /// <summary>
        /// 获取类型
        /// </summary>
        /// <param name="url">服务网址</param>
        /// <param name="className">服务类型名称</param>
        /// <returns>返回Type</returns>
        private static Type GetType(string url, string className)
        {
            Type   result     = null;
            string @namespace = "HIIStest.UIBase.Temp.WebService";

            if (string.IsNullOrEmpty(className))
            {
                className = WebServiceHelper.GetWsClassName(url);
            }
            //获取WSDL
            WebClient                  wc     = new WebClient();
            Stream                     stream = wc.OpenRead(url + "?WSDL");
            ServiceDescription         sd     = ServiceDescription.Read(stream);
            ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, "", "");
            //生成客户端代理类代码
            CodeNamespace   np  = new CodeNamespace(@namespace);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(np);
            sdi.Import(np, ccu);
            //获取c#编译器的实例
            CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
            //设定编译参数
            CompilerParameters param = new CompilerParameters();

            param.GenerateExecutable = false;
            param.GenerateInMemory   = true;
            param.ReferencedAssemblies.Add("System.dll");
            param.ReferencedAssemblies.Add("System.XML.dll");
            param.ReferencedAssemblies.Add("System.Web.Services.dll");
            param.ReferencedAssemblies.Add("System.Data.dll");
            //编译代理类
            CompilerResults cr = provider.CompileAssemblyFromDom(param, 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;
            //反射获取类型
            result = assembly.GetType(@namespace + "." + className, true, true);
            return(result);
        }
Example #30
0
        private IotMService()
        {
            string serviceUrl = System.Configuration.ConfigurationManager.AppSettings["IotMServiceUrl"];


            // 1. 使用 WebClient 下载 WSDL 信息。
            WebClient web    = new WebClient();
            Stream    stream = web.OpenRead(serviceUrl);

            // 2. 创建和格式化 WSDL 文档。
            ServiceDescription description = ServiceDescription.Read(stream);

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

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

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

            // 4. 使用 CodeDom 编译客户端代理类。
            CodeNamespace   nmspace = new CodeNamespace(); // 为代理类添加命名空间,缺省为全局空间。
            CodeCompileUnit unit    = new CodeCompileUnit();

            unit.Namespaces.Add(nmspace);

            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");


            CompilerParameters parameter = new CompilerParameters();

            parameter.GenerateExecutable = false;
            parameter.OutputAssembly     = "IotMService.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");


            CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

            if (result.Errors.HasErrors)
            {
                // 显示编译错误信息
            }

            asm = Assembly.LoadFrom("IotMService.dll");
            t   = asm.GetType("OlbService");
        }