asp.Net動的にwebserviceを呼び出し、カスタムSoapHeaderから渡す

21679 ワード

クライアントコード:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Web.Services.Description;
using System.Net;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;
using System.Web.Configuration;
using System.Xml.Serialization;
using System.Xml;
using System.Globalization;
using System.Security.Permissions;
namespace WebServiceTest
{
    /// <summary>
    ///     WebService(  SaopHeader)
    /// </summary>
    public class WebServiceHelper
    {
        /// <summary>   
        ///   WebService      
        /// </summary>   
        /// <param name="wsUrl">WebService  </param>   
        /// <returns>  WebService   </returns>   
        private static string GetWsClassName(string wsUrl)
        {
            string[] parts = wsUrl.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');
            return pps[0];
        }
        /// <summary>   
        ///   WebService(  SoapHeader)
        /// </summary>   
        /// <param name="wsUrl">WebService  </param>   
        /// <param name="methodName">    </param>   
        /// <param name="args">    </param>   
        /// <returns>      </returns>   
        public static object InvokeWebService(string wsUrl, string methodName, object[] args)
        {
            return InvokeWebService(wsUrl, null, methodName, null, args);
        }
        /// <summary>   
        ///   WebService( SoapHeader)
        /// </summary>   
        /// <param name="wsUrl">WebService  </param>   
        /// <param name="methodName">    </param>   
        /// <param name="soapHeader">SOAP </param>   
        /// <param name="args">    </param>   
        /// <returns>      </returns>
        public static object InvokeWebService(string wsUrl, string methodName, SoapHeader soapHeader, object[] args)
        {
            return InvokeWebService(wsUrl, null, methodName, soapHeader, args);
        }
        /// <summary>   
        ///   WebService
        /// </summary>   
        /// <param name="wsUrl">WebService  </param>   
        /// <param name="className">  </param>   
        /// <param name="methodName">    </param>   
        /// <param name="soapHeader">SOAP </param>
        /// <param name="args">    </param>   
        /// <returns>      </returns>    
        public static object InvokeWebService(string wsUrl, string className, string methodName, SoapHeader soapHeader, object[] args)
        {
            string @namespace = "IDPSystem.WebUI.WebService";
            if ((className == null) || (className == ""))
            {
                className = GetWsClassName(wsUrl);
            }
            try
            {
                //  WSDL   
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(wsUrl + "?wsdl");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.Style = ServiceDescriptionImportStyle.Client;//       
                sdi.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.None | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOrder;
                sdi.ProtocolName = "Soap12";
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);
                //             
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                //CSharpCodeProvider csc = new CSharpCodeProvider();
                //ICodeCompiler icc = csc.CreateCompiler();
                CodeDomProvider icc = CodeDomProvider.CreateProvider("CSharp");
                // icc.GenerateCodeFromCompileUnit(ccu, Console.Out, new CodeGeneratorOptions());     
                //         
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.OutputAssembly = @namespace + ".dll";//        
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                cplist.ReferencedAssemblies.Add("System.ServiceModel.dll");
                cplist.IncludeDebugInformation = true;
                //        
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, 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());
                }
                //     WebService  ,         ,                  ,           ,      bin    
                TextWriter writer = File.CreateText("MyTest3.cs");
                icc.GenerateCodeFromCompileUnit(ccu, writer, null);
                writer.Flush();
                writer.Close();
                //      ,        
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + className, true, true);
                FieldInfo[] arry = t.GetFields();
                FieldInfo client = null;
                // PropertyInfo pro = null; 
                object clientkey = null;
                if (soapHeader != null)
                {
                    //Soap    
                    client = t.GetField(soapHeader.ClassName + "Value");
                    //             soap 
                    Type typeClient = assembly.GetType(@namespace + "." + soapHeader.ClassName);
                    //         soap    
                    clientkey = Activator.CreateInstance(typeClient);
                    //    
                    foreach (KeyValuePair<string, object> property in soapHeader.Properties)
                    {
                        typeClient.GetField(property.Key).SetValue(clientkey, property.Value);
                        // typeClient.GetProperty(property.Key).SetValue(clientkey, property.Value, null);
                    }
                    //Soap       
                }
                //         
                object obj = Activator.CreateInstance(t);
                if (soapHeader != null)
                {
                    //  Soap 
                    client.SetValue(obj, clientkey);
                    //pro.SetValue(obj, soapHeader, null);
                }
                ///  object  
                List<object> objlist = new List<object>();
                //    staff   
                Type ProxyStaff = assembly.GetType("IDPSystem.WebUI.WebService.Entity");
                ///    
                Type ProxyStaffArray = ProxyStaff.MakeArrayType(1);
                SameWSEntity[] wsEntityList = (SameWSEntity[])args[(args.Length - 1)];
                MethodInfo[] melist = ProxyStaffArray.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                object array = ProxyStaffArray.InvokeMember("Set", BindingFlags.CreateInstance, null, wsEntityList, new object[] { wsEntityList.Length });
                int i = 0;//array
                foreach (SameWSEntity staff in wsEntityList)
                {
                    //      staff   
                    object ProxyStaffEntity = Activator.CreateInstance(ProxyStaff);
                    //    
                    foreach (FieldInfo item in ProxyStaff.GetFields())
                    {
                        //         
                        object objVal = typeof(SameWSEntity).GetProperty(item.Name).GetValue(staff, null);
                        item.SetValue(ProxyStaffEntity, objVal);
                    }
                    MethodInfo[] list = ProxyStaffArray.GetMethods();
                    ProxyStaffArray.GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }).Invoke(array, new object[] { ProxyStaffEntity, i });
                    i++; 
                    //  object  
                    objlist.Add(ProxyStaffEntity);
                }
                //  object  
                args[args.Length - 1] = array; // objlist.ToArray();
                System.Reflection.MethodInfo mi = t.GetMethod(methodName);
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
				
				//     ,    
  			private static ErrorMessage ConvertToErrMsg(object obj)
        {
            ErrorMessage errMsg = new ErrorMessage();
            List<ErrorMessage.ErrorData> errdata = new List<ErrorMessage.ErrorData>();
            Type t = obj.GetType();
            foreach (FieldInfo item in t.GetFields())
            {
                Type tlist = item.FieldType;
                if (tlist.IsArray)
                {
                    object[] val = item.GetValue(obj) as object[];
                    Type errType = val.GetType();
                    object array = errType.InvokeMember("Set", BindingFlags.CreateInstance, null, val, new object[] { val.Length });
                    MethodInfo method = errType.GetMethod("GetValue", new Type[] { typeof(int) });
                    for (int i = 0; i < val.Length; i++)
                    {
                        ErrorMessage.ErrorData err = new ErrorMessage.ErrorData();
                        object val2 = method.Invoke(val, new object[] { 0 });
                        Type errWS = val2.GetType();
                        foreach (FieldInfo field in errWS.GetFields())
                        {
                            switch (field.Name)
                            {
                                case "ID":
                                    err.ID = field.GetValue(val2).ToString();
                                    break;
                                case "Message":
                                    err.Message = field.GetValue(val2).ToString();
                                    break;
                            }
                        }
                        errdata.Add(err);
                    }
                }
                else
                {
                    object val = item.GetValue(obj);
                    switch (item.Name)
                    {
                        case "ErrorCode":
                            errMsg.ErrorCode = Convert.ToInt32(val);
                            break;
                        case "ErrorMsg":
                            errMsg.ErrorMsg = val.ToString();
                            break;
                    }
                }
            }
            errMsg.ErrorList = errdata.ToArray();
            return errMsg;
        }
        
        /// <summary>
        /// SOAP 
        /// </summary>
        public class SoapHeader
        {
            /// <summary>
            ///     SOAP 
            /// </summary>
            public SoapHeader()
            {
                this.Properties = new Dictionary<string, object>();
            }
            /// <summary>
            ///     SOAP 
            /// </summary>
            /// <param name="className">SOAP    </param>
            public SoapHeader(string className)
            {
                this.ClassName = className;
                this.Properties = new Dictionary<string, object>();
            }
            /// <summary>
            ///     SOAP 
            /// </summary>
            /// <param name="className">SOAP    </param>
            /// <param name="properties">SOAP          </param>
            public SoapHeader(string className, Dictionary<string, object> properties)
            {
                this.ClassName = className;
                this.Properties = properties;
            }
            /// <summary>
            /// SOAP    
            /// </summary>
            public string ClassName { get; set; }
            /// <summary>
            /// SOAP          
            /// </summary>
            public Dictionary<string, object> Properties { get; set; }
            /// <summary>
            ///  SOAP         
            /// </summary>
            /// <param name="name">SOAP      </param>
            /// <param name="value">SOAP      </param>
            public void AddProperty(string name, object value)
            {
                if (this.Properties == null)
                {
                    this.Properties = new Dictionary<string, object>();
                }
                Properties.Add(name, value);
            }
        }
    }
}

---------------------------------------------------------------------------------------サーバ側メソッドとオブジェクト
オブジェクト:
 
using System;
using System.Web.Services.Protocols;
using IDPSystem.BLL;
using IDPSystem.BLL.DictionaryEnum.StaffRole;
namespace IDPSystem.WebUI.WebService
{
    /// <summary>
    ///         
    /// </summary>
    public class Certificate : SoapHeader
    {
        public Certificate() { }
        /// <summary>
        ///    
        /// </summary>
        public string LoginUserName { get; set; }
        /// <summary>
        ///   
        /// </summary>
        public string LoginPassword { get; set; }
    }
    /// <summary>
    /// WebService     
    /// </summary>
    [Serializable]
    public class Staff
    {
        #region   
        /// <summary>
        ///   ID
        /// </summary> 
        public string Identity
        {
            get;
            set;
        }
        /// <summary>
        ///     
        /// </summary>
        public string Number
        {
            get;
            set;
        }
        /// <summary>
        ///     
        /// </summary>
        public string Name
        {
            get;
            set;
        }
     
        /// <summary>
        ///     
        /// </summary>
        public bool Dimission
        {
            get;
            set;
        } 
        /// <summary>
        ///           
        /// </summary>
        internal string LastUpdateUserInfoID
        {
            get;
            set;
        }
 
        /// <summary>
        ///       
        /// </summary> 
        internal string UserInfoIdentity
        {
            get;
            set;
        }
        /// <summary>
        ///   ID
        /// </summary>
        internal string CorparionID
        {
            get;
            set;
        } 
     
        #endregion
        #region     
        public Staff()
        {
            this.UpdateTime = DateTime.Now.ToString();
            this.InsertTime = DateTime.Now.ToString();
        }
    /// <summary>
    /// WebService   
    /// </summary>
    public class WS_ErrorMessage
    {
        public struct ErrorData
        {
            public string ID;
            public string Message;
            public ErrorData(string id, string msg)
            {
                this.ID = id;
                this.Message = msg;
            }
        }
        /// <summary>
        ///          
        /// </summary>  
        private ErrorData[] errorList;
        public ErrorData[] ErrorList
        {
            get { return errorList; }
            set { errorList = value; }
        }
        /// <summary>
        ///     0   1   2    
        /// </summary>
        private int errorCode;
        public int ErrorCode
        {
            get { return errorCode; }
            set { errorCode = value; }
        }
        /// <summary>
        ///     
        /// </summary>
        private string errorMsg;
        public string ErrorMsg
        {
            get { return errorMsg; }
            set { errorMsg = value; }
        }
    } 
}

 
方法:
 		[XmlInclude(typeof(Staff[])), XmlInclude(typeof(ErrorMessage)), XmlInclude(typeof(IDPSystem.WebUI.WebService.WS_ErrorMessage.ErrorData))]
    public class WS_StaffOperate : System.Web.Services.WebService
    {
        /// <summary>
        ///     
        /// </summary>
        public Certificate certificate = new Certificate();
        [SoapHeader("certificate")]
        [WebMethod]
        public WS_ErrorMessage HelloWorld(Staff staff)
        { 
           
        }
}

 
--------------------------------------------クライアントオブジェクト:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebServiceTest
{
    public class ErrorMessage
    {
        public class ErrorData
        {
            public string ID;
            public string Message;
            public ErrorData(string id, string msg)
            {
                this.ID = id;
                this.Message = msg;
            }
            public ErrorData()
            {
            }
        }
        /// <summary>
        ///          
        /// </summary>  
        private ErrorData[] errorList;
        public ErrorData[] ErrorList
        {
            get { return errorList; }
            set { errorList = value; }
        }
        /// <summary>
        ///     0   1   2    
        /// </summary>
        private int errorCode;
        public int ErrorCode
        {
            get { return errorCode; }
            set { errorCode = value; }
        }
        /// <summary>
        ///     
        /// </summary>
        private string errorMsg;
        public string ErrorMsg
        {
            get { return errorMsg; }
            set { errorMsg = value; }
        }
    }
}