動態添加web引用

 項目: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;
            }
        }
發佈了38 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章