博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

动态调用WebService的工具类(做个记录,备忘)

Posted on 2010-04-23 23:06  codingsilence  阅读(519)  评论(0编辑  收藏  举报
代码
using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace Gren.Framework
{
    
/// <summary>
    
/// 动态调用WebService的工具类
    
/// </summary>
    public class WebServiceUtils
    {
        
private string url;
        
private string methodName;
        
private object[] args;

        
private string username;
        
private string password;
        
private string domain;
        
private bool needCredential;

        
/// <summary>
        
/// web服务的地址
        
/// </summary>
        public string Url
        {
            
get { return url; }
            
set { url = value; }
        }

        
/// <summary>
        
/// web服务的方法名
        
/// </summary>
        public string MethodName
        {
            
get { return methodName; }
            
set { methodName = value; }
        }

        
/// <summary>
        
/// web服务的方法参数
        
/// </summary>
        public object[] Args
        {
            
get { return args; }
            
set { args = value; }
        }

        
/// <summary>
        
/// 用户名
        
/// </summary>
        public string Username
        {
            
get { return username; }
            
set { username = value; }
        }

        
/// <summary>
        
/// 密码
        
/// </summary>
        public string Password
        {
            
get { return password; }
            
set { password = value; }
        }

        
/// <summary>
        
/// 域名
        
/// </summary>
        public string Domain
        {
            
get { return domain; }
            
set { domain = value; }
        }

        
/// <summary>
        
/// 是否需要身份验证
        
/// </summary>
        public bool NeedCredential
        {
            
get { return needCredential; }
            
set { needCredential = value; }
        }

        
public WebServiceUtils()
        { 
            
this.url = string.Empty;
            
this.methodName = string.Empty;
            
this.args = null;
            
this.username = string.Empty;
            
this.password = string.Empty;
            
this.domain = string.Empty;
            
this.needCredential = false;
        }

        
/// <summary>
        
/// 调用WebService
        
/// </summary>
        public object Response()
        {
            
object obj = null;

            Type t 
= typeof(WebServiceProxy);
            
            AppDomain otherDomain 
= AppDomain.CreateDomain("WebServieDoamin");

            
try
            {
                WebServiceProxy proxy 
= (WebServiceProxy)otherDomain.CreateInstanceAndUnwrap(t.Assembly.FullName, t.FullName);
                proxy.Url 
= this.url;
                proxy.MethodName 
= this.methodName;
                proxy.Args 
= this.args;
                proxy.Username 
= this.username;
                proxy.Password 
= this.password;
                proxy.Domain 
= this.domain;
                proxy.NeedCredential 
= this.needCredential;

                obj 
= proxy.InvokeWebService();
            }
            
finally
            {
                AppDomain.Unload(otherDomain);
            }

            
return obj;
        } 
    }


    
/// <summary>
    
/// WebService代理类,不直接使用
    
/// </summary>
    public class WebServiceProxy : MarshalByRefObject
    {
        
private string url;
        
private string methodName;
        
private object[] args;

        
private string username;
        
private string password;
        
private string domain;
        
private bool needCredential;

        
/// <summary>
        
/// web服务的地址
        
/// </summary>
        public string Url
        {
            
get { return url; }
            
set { url = value; }
        }

        
/// <summary>
        
/// web服务的方法名
        
/// </summary>
        public string MethodName
        {
            
get { return methodName; }
            
set { methodName = value; }
        }

        
/// <summary>
        
/// web服务的方法参数
        
/// </summary>
        public object[] Args
        {
            
get { return args; }
            
set { args = value; }
        }

        
/// <summary>
        
/// 用户名
        
/// </summary>
        public string Username
        {
            
get { return username; }
            
set { username = value; }
        }

        
/// <summary>
        
/// 密码
        
/// </summary>
        public string Password
        {
            
get { return password; }
            
set { password = value; }
        }

        
/// <summary>
        
/// 域名
        
/// </summary>
        public string Domain
        {
            
get { return domain; }
            
set { domain = value; }
        }

        
/// <summary>
        
/// 是否需要身份验证
        
/// </summary>
        public bool NeedCredential
        {
            
get { return needCredential; }
            
set { needCredential = value; }
        }

        
private string GetWsClassName(string wsUrl)
        {
            
string[] parts = wsUrl.Split('/');
            
string[] pps = parts[parts.Length - 1].Split('.');

            
return pps[0];
        }

        
public object InvokeWebService()
        {
            
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
            
            
string classname = this.GetWsClassName(this.url);

            
try
            {
                NetworkCredential myCredential 
= new NetworkCredential(this.username, this.password, this.domain);

                
//获取WSDL
                WebClient wc = new WebClient();

                
if (this.needCredential)
                {
                    wc.Credentials 
= myCredential;
                }

                System.IO.Stream stream 
= wc.OpenRead(this.url + "?WSDL");
                ServiceDescription sd 
= ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi 
= new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, 
"""");
                CodeNamespace cn 
= new CodeNamespace(@namespace);

                
//生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                CodeDomProvider csc 
= CodeDomProvider.CreateProvider("C#");

                
//设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable 
= false;
                cplist.GenerateInMemory 
= true;
                cplist.ReferencedAssemblies.Add(
"System.dll");
                cplist.ReferencedAssemblies.Add(
"System.XML.dll");
                cplist.ReferencedAssemblies.Add(
"System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add(
"System.Data.dll");

                
//编译代理类
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                
if (cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb 
= new System.Text.StringBuilder();
                    
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    
throw new Exception(sb.ToString());
                }

                
//生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t 
= assembly.GetType(@namespace + "." + classname, truetrue);
                
object obj = Activator.CreateInstance(t);

                
if (this.needCredential)
                {
                    System.Reflection.PropertyInfo pi 
= t.GetProperty("Credentials");
                    pi.SetValue(obj, myCredential, 
null);
                }
                
                System.Reflection.MethodInfo mi 
= t.GetMethod(this.methodName);

                
return mi.Invoke(obj, args);
            }
            
catch (Exception ex)
            {
                
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }

        }

        
    }
}