动态添加web引用

5 篇文章 0 订阅

 项目:xx  之 手工派单

内容介绍:

在本系统中,考虑到各个大区emos系统提供的鉴权服务 webserverce的地址不同,因此,不可能在系统中 把wsdl路径设定死,需要可以动态的引用wsdl.幸好,公司同事给了个dll,满足了该功能.

dll 文件:文件上传不上来,

 

[ClassInterface(ClassInterfaceType.AutoDual)]
public   class  DynWebService : IDisposable
{
    
// Fields
    private Assembly assembly = null;
    
private const string defNameSpace = "BOCO.APP.Common.DynWSCallDefaultNameSpace";
    
private string nameSpace = "BOCO.APP.Common.DynWSCallDefaultNameSpace";

    
// Methods
    public bool Binding(string url, string keyFile, ClassInterfaceType intfType)
    
{
        
if (url.ToLower().EndsWith(".dll"))
        
{
            
this.assembly = Assembly.LoadFile(url);
            
return true;
        }

        
string wsdlUrl = url;
        CompilerResults results 
= this.CompilerCSharp(wsdlUrl, keyFile, intfType, false);
        
if (results == null)
        
{
            
return false;
        }

        
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());
        }

        
this.assembly = results.CompiledAssembly;
        
return true;
    }


    
public DynWSClassBinding BindingClass(string className)
    
{
        
if (this.assembly == null)
        
{
            
throw new Exception("请先绑定Web服务。");
        }

        DynWSClassBinding binding 
= new DynWSClassBinding();
        
string str = this.FormatClassName(className);
        
if (binding.BindingClass(this.assembly, str))
        
{
            
return binding;
        }

        
return null;
    }


    
public DynWSMethodBinding BindingMethod(string className, string methodName)
    
{
        
if (this.assembly == null)
        
{
            
throw new Exception("请先绑定Web服务。");
        }

        
string str = "";
        
if ((className == null|| (className.Length == 0))
        
{
            str 
= this.FindClassNameByMethoadName(methodName);
        }

        
else
        
{
            str 
= this.FormatClassName(className);
        }

        DynWSClassBinding binding 
= this.BindingClass(str);
        
if (binding == null)
        
{
            
return null;
        }

        
return binding.BindingMethod(methodName);
    }


    
public CompilerResults CompilerCSharp(string wsdlUrl, string keyFile, ClassInterfaceType intfType, bool generateInMemory)
    
{
        CodeCompileUnit compilationUnit 
= this.GeneratorCodeUnit(wsdlUrl, keyFile, intfType);
        
if (compilationUnit == null)
        
{
            
return null;
        }

        ICodeCompiler compiler 
= new CSharpCodeProvider().CreateCompiler();
        CompilerParameters options 
= new CompilerParameters();
        options.GenerateExecutable 
= false;
        options.GenerateInMemory 
= generateInMemory;
        options.ReferencedAssemblies.Add(
"System.dll");
        options.ReferencedAssemblies.Add(
"System.XML.dll");
        options.ReferencedAssemblies.Add(
"System.Web.Services.dll");
        options.ReferencedAssemblies.Add(
"System.Data.dll");
        
return compiler.CompileAssemblyFromDom(options, compilationUnit);
    }


    
public void Dispose()
    
{
        Assembly assembly 
= this.assembly;
    }


    
public string FindClassNameByMethoadName(string methodName)
    
{
        
foreach (Type type in this.assembly.GetExportedTypes())
        
{
            
if (type.IsSubclassOf(typeof(SoapHttpClientProtocol)))
            
{
                MethodInfo method 
= null;
                
try
                
{
                    method 
= type.GetMethod(methodName);
                }

                
catch (Exception exception)
                
{
                    
throw new Exception(string.Format("从{0}查找方法{1}异常:{2}", type.FullName, methodName, exception.Message));
                }

                
if (method != null)
                
{
                    
return type.FullName;
                }

            }

        }

        
return "";
    }


    
private string FormatClassName(string cls)
    
{
        
if (cls.Length == 0)
        
{
            
return this.GetFirstClassName();
        }

        
if ((this.nameSpace.Length > 0&& !cls.StartsWith(this.nameSpace))
        
{
            cls 
= this.nameSpace + "." + cls;
        }

        
return cls;
    }


    
private string FormatWSDLUrl(string url)
    
{
        
string str = url.ToLower();
        
if (!str.StartsWith("http:"))
        
{
            
return url;
        }

        
if (str.EndsWith("?wsdl"))
        
{
            
return url;
        }

        
return (url + "?WSDL");
    }


    
private CodeCompileUnit GeneratorCodeUnit(string wsdlUrl, string keyFile, ClassInterfaceType intfType)
    
{
        
if (this.nameSpace.Length == 0)
        
{
            
this.nameSpace = "BOCO.APP.Common.DynWSCallDefaultNameSpace";
        }

        WebClient client 
= new WebClient();
        ServiceDescription description 
= ServiceDescription.Read(client.OpenRead(this.FormatWSDLUrl(wsdlUrl)));
        ServiceDescriptionImporter importer 
= new ServiceDescriptionImporter();
        importer.AddServiceDescription(description, 
"""");
        CodeCompileUnit unit 
= new CodeCompileUnit();
        
if ((keyFile != null&& (keyFile.Length > 0))
        
{
            unit.AssemblyCustomAttributes.Add(
new CodeAttributeDeclaration("System.Reflection.AssemblyKeyFile"new CodeAttributeArgument[] new CodeAttributeArgument(new CodePrimitiveExpression(keyFile)) }));
            unit.AssemblyCustomAttributes.Add(
new CodeAttributeDeclaration("System.Reflection.AssemblyKeyName"new CodeAttributeArgument[] new CodeAttributeArgument(new CodePrimitiveExpression("")) }));
        }

        CodeNamespace namespace2 
= new CodeNamespace(this.nameSpace);
        unit.Namespaces.Add(namespace2);
        importer.Import(namespace2, unit);
        
if (intfType != ClassInterfaceType.None)
        
{
            
foreach (CodeNamespace namespace3 in unit.Namespaces)
            
{
                
foreach (CodeTypeDeclaration declaration in namespace3.Types)
                
{
                    declaration.CustomAttributes.Insert(
0new CodeAttributeDeclaration("System.Runtime.InteropServices.ClassInterfaceAttribute"new CodeAttributeArgument[] new CodeAttributeArgument(new CodePrimitiveExpression((int) intfType)) }));
                }

            }

        }

        
return unit;
    }


    
public bool GeneratorCSharpCode(string wsdlUrl, string keyFile, ClassInterfaceType intfType, out string code)
    
{
        code 
= null;
        CodeCompileUnit e 
= this.GeneratorCodeUnit(wsdlUrl, keyFile, intfType);
        
if (e == null)
        
{
            
return false;
        }

        
new CSharpCodeProvider();
        ICodeGenerator generator 
= new CSharpCodeProvider().CreateGenerator();
        CodeGeneratorOptions o 
= new CodeGeneratorOptions();
        o.BlankLinesBetweenMembers 
= true;
        o.BracingStyle 
= "C";
        o.ElseOnClosing 
= false;
        o.IndentString 
= "    ";
        StringBuilder sb 
= new StringBuilder();
        StringWriter w 
= new StringWriter(sb);
        generator.GenerateCodeFromCompileUnit(e, w, o);
        code 
= sb.ToString();
        w.Close();
        
return true;
    }


    
public string GetFirstClassName()
    
{
        
foreach (Type type in this.assembly.GetExportedTypes())
        
{
            
if (type.IsSubclassOf(typeof(SoapHttpClientProtocol)))
            
{
                
return type.FullName;
            }

        }

        
return "";
    }


    
// Properties
    public string NameSpace
    
{
        
get
        
{
            
return this.nameSpace;
        }

        
set
        
{
            
if ((value != null&& (value.Length > 0))
            
{
                
this.nameSpace = value;
            }

            
else
            
{
                
this.nameSpace = "";
            }

        }

    }

}


 
[ClassInterface(ClassInterfaceType.AutoDual)]
public   class  DynWSClassBinding : IDisposable
{
    
// Fields
    private Assembly assembly = null;
    
private string className = "";
    
private object classObject = null;
    
private SoapHttpClientProtocol classObjectSoapHttpClient = null;
    
private Type classType = null;

    
// Methods
    public bool BindingClass(Assembly assembly, string className)
    
{
        
this.assembly = assembly;
        
this.className = className;
        
this.classType = this.assembly.GetType(this.className, truetrue);
        
this.classObject = Activator.CreateInstance(this.classType);
        
try
        
{
            
this.classObjectSoapHttpClient = this.classObject as SoapHttpClientProtocol;
        }

        
catch
        
{
        }

        
return true;
    }


    
public DynWSMethodBinding BindingMethod(string methodName)
    
{
        
if ((this.assembly == null|| (this.classObject == null))
        
{
            
throw new Exception("请先绑定类。");
        }

        DynWSMethodBinding binding 
= new DynWSMethodBinding();
        
if (binding.BindingMethod(this, methodName))
        
{
            
return binding;
        }

        
return null;
    }


    
public void Dispose()
    
{
        
if (this.classObjectSoapHttpClient != null)
        
{
            
this.classObjectSoapHttpClient.Dispose();
        }

    }


    
public object GetFieldValue(string attName)
    
{
        
if (this.classObject == null)
        
{
            
throw new Exception("请先绑定类。");
        }

        
try
        
{
            
return this.classType.InvokeMember(attName, BindingFlags.GetProperty, nullthis.classObject, new object[0]);
        }

        
catch
        
{
            
return this.classType.InvokeMember(attName, BindingFlags.GetField, nullthis.classObject, new object[0]);
        }

    }


    
public bool SetFieldValue(string attName, object attValue)
    
{
        
if (this.classObject == null)
        
{
            
throw new Exception("请先绑定类。");
        }

        
try
        
{
            
this.classType.InvokeMember(attName, BindingFlags.SetProperty, nullthis.classObject, new object[] { attValue });
        }

        
catch
        
{
            
this.classType.InvokeMember(attName, BindingFlags.SetField, nullthis.classObject, new object[] { attValue });
        }

        
return true;
    }


    
// Properties
    public Assembly Assembly
    
{
        
get
        
{
            
return this.assembly;
        }

    }


    
public string ClassName
    
{
        
get
        
{
            
return this.className;
        }

    }


    
public object ClassObject
    
{
        
get
        
{
            
return this.classObject;
        }

    }


    
public Type ClassType
    
{
        
get
        
{
            
return this.classType;
        }

    }


    
public string Url
    
{
        
get
        
{
            
return this.GetFieldValue("Url").ToString();
        }

        
set
        
{
            
this.SetFieldValue("Url", value);
        }

    }

}


 
 [ClassInterface(ClassInterfaceType.AutoDual)]
public   class  DynWSMethodBinding : IDisposable
{
    
// Fields
    private DynWSClassBinding classBinding = null;
    
private MethodInfo methodInfo = null;
    
private string methodName = "";
    
private ParameterInfo[] methodParams = null;
    
private object[] methodParamsValue = null;

    
// Methods
    public bool BindingMethod(DynWSClassBinding classBND, string methodName)
    
{
        
this.classBinding = classBND;
        
this.methodName = methodName;
        
this.methodInfo = this.classBinding.ClassType.GetMethod(this.methodName);
        
if (this.methodInfo != null)
        
{
            
this.methodParams = this.methodInfo.GetParameters();
            
this.methodParamsValue = new object[this.methodParams.Length];
            
return true;
        }

        
return false;
    }


    
public void ClearParamsValue()
    
{
        
this.methodParamsValue = new object[this.methodParams.Length];
    }


    
public void Dispose()
    
{
        
if (this.classBinding != null)
        
{
            
this.classBinding.Dispose();
        }

    }


    
private int GetParamIndex(string paramName)
    
{
        
if (this.methodParams != null)
        
{
            
foreach (ParameterInfo info in this.methodParams)
            
{
                
if (info.Name.ToLower() == paramName.ToLower())
                
{
                    
return info.Position;
                }

            }

        }

        
return -1;
    }


    
public ParameterInfo GetParamInfo(string paramName)
    
{
        
foreach (ParameterInfo info in this.methodParams)
        
{
            
if (info.Name.ToLower() == paramName.ToLower())
            
{
                
return info;
            }

        }

        
return null;
    }


    
public string GetParamInfoString()
    
{
        StringBuilder builder 
= new StringBuilder();
        
if (this.methodParams != null)
        
{
            
int num = 0;
            
foreach (ParameterInfo info in this.methodParams)
            
{
                
object obj2 = (this.methodParamsValue != null? this.methodParamsValue[info.Position] : null;
                
string str = (obj2 == null? "<null>" : obj2.ToString();
                builder.Append(
string.Format("序号:{0}/{1} 参数:{2} 值:{3} 类型:{4} "new object[] { num++, info.Position, info.Name, str, info.ParameterType }));
            }

        }

        
return builder.ToString();
    }


    
public object Invoke()
    
{
        
return this.methodInfo.Invoke(this.classBinding.ClassObject, this.methodParamsValue);
    }


    
public bool SetParamValue(string paramName, object paramValue)
    
{
        
try
        
{
            
object obj2 = null;
            
foreach (ParameterInfo info in this.methodParams)
            
{
                
if (info.Name.ToLower() == paramName.ToLower())
                
{
                    obj2 
= Convert.ChangeType(paramValue, info.ParameterType);
                    
this.methodParamsValue[info.Position] = obj2;
                    
return true;
                }

            }

            
return false;
        }

        
catch
        
{
            
return false;
        }

    }


    
// Properties
    public DynWSClassBinding ClassBinding
    
{
        
get
        
{
            
return this.classBinding;
        }

    }


    
public MethodInfo MethodInfo
    
{
        
get
        
{
            
return this.methodInfo;
        }

    }


    
public string MethodName
    
{
        
get
        
{
            
return this.methodName;
        }

    }


    
public ParameterInfo[] Params
    
{
        
get
        
{
            
return this.methodParams;
        }

    }


    
public object[] ParamValues
    
{
        
get
        
{
            
return this.methodParamsValue;
        }

    }

}


 
 
 


 

 

使用介绍:

 

  public   bool  CheckUser( string  strUName,  string  strPwd)
        {
            
try
            {
                DynWebService ws 
=   new  DynWebService();
                ws.Binding(WSDLUrl, 
"" , System.Runtime.InteropServices.ClassInterfaceType.None);
                DynWSClassBinding cls 
=  ws.BindingClass( "" );
                cls.Url 
=  Url;
                DynWSMethodBinding method 
=  cls.BindingMethod( " eomsAuthentication " );
                method.SetParamValue(
" serSupplier " "" );
                method.SetParamValue(
" serCaller " "" );
                method.SetParamValue(
" callerPwd " "" );
                
// pMethod->SetParamValue(_bstr_t("serSupplier"),_variant_t((LPCTSTR)CGlobal::GetAppSetting("Supplier")));
                
// pMethod->SetParamValue(_bstr_t("serCaller"),_variant_t((LPCTSTR)CGlobal::GetAppSetting("Caller")));
                
// CString strCallerPwd = (LPCTSTR)CGlobal::GetAppSetting("CallerPwd");
                
// strCallerPwd = CEnc::DecodeAndAutoCheck(strCallerPwd);
                 string  callTime  =  DateTime.Now.ToString( " yyyy-mm-hh HH:MM:SS " );
                method.SetParamValue(
" callTime " , callTime);
                method.SetParamValue(
" userName " , strUName);
                method.SetParamValue(
" userPassword " , strPwd);

                
object  ret  =  method.Invoke();
                
string  sret  =  ret  ==   null   ?   ""  : ret.ToString();
                
if  (sret.Length  ==   0 )
                {
                    
return   true ;
                }
                
else
                {
                    
throw   new  Exception( " 登录失败: "   +  sret);
                }
            }
            
catch
            {
                
return   false ;
            }
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值