In depth.net call webservice summary analysis

  • 2020-06-12 08:50:37
  • OfStack

I recently worked on a project where app was developed in someone else's framework, resulting in a number of limitations, one of which is that you cannot refer to webservice directly.
As we all know, the easiest way to call webserivice is to right click on "Reference", select "Reference web Service", and enter the service address.
Once it's done, it generates an ES6en.config and then it automatically generates some configuration information.
You can't do that with the project you're doing right now. A subsequent search revealed several other ways to call webservice dynamically.
Without further ado, here is the webservice code

View Code 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace TestWebService
{
    /// <summary>
    /// Service1  Summary description of 
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/",Description=" my Web service ")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    //  To allow use  ASP.NET AJAX  Call this from the script  Web  Service, please uncomment the downlink. 
    // [System.Web.Script.Services.ScriptService]
    public class TestWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return " test Hello World";
        }
        [WebMethod]
        public string Test()
        {
            return " test Test";
        }

        [WebMethod(CacheDuration = 60,Description = " test ")]
        public List<String> GetPersons()
        {
            List<String> list = new List<string>();
            list.Add(" test 1");
            list.Add(" test 2");
            list.Add(" test 3");
            return list;
        }  
    }
}

Example of dynamic invocation:
Method 1:
We can see that many dynamic calls to WebService are just dynamic call addresses. The following is not only a call based on address, but also a method name can be specified by itself. The main principle is to generate a proxy class based on the WSDL address specified by WebService, and then to invoke the method inside by reflection

View Code 
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.Net;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Text;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.Windows.Forms;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient client = new WebClient();
            String url = "http://localhost:3182/Service1.asmx?WSDL";// This address can be written in Config Inside the file, just take it out here . After the original address, add:  ?WSDL
            Stream stream = client.OpenRead(url);
            ServiceDescription description = ServiceDescription.Read(stream);
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();// Create the client proxy proxy class. 
            importer.ProtocolName = "Soap"; // Specifies the access protocol. 
            importer.Style = ServiceDescriptionImportStyle.Client; // Generate the client proxy. 
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
            importer.AddServiceDescription(description, null, null); // add WSDL The document. 
            CodeNamespace nmspace = new CodeNamespace(); // The namespace 
            nmspace.Name = "TestWebService";
            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 = "MyTest.dll";// Output the name of the assembly 
            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)
            {
                //  Displays a compile error message 
            }
            Assembly asm = Assembly.LoadFrom("MyTest.dll");// Load the previously generated assembly 
            Type t = asm.GetType("TestWebService.TestWebService");
            object o = Activator.CreateInstance(t);
            MethodInfo method = t.GetMethod("GetPersons");//GetPersons Is the method name on the server side , Any method you want to invoke on the server can be changed here , The best packaging 1 Under the 
            String[] item = (String[])method.Invoke(o, null);
            // Note: method.Invoke(o, null) Returns the 1 a Object, If your server returns a DataSet, This is also used here (DataSet)method.Invoke(o, null) turn 1 Under the line ,method.Invoke(0,null) Here, null You can pass the parameters needed to call the method ,string[] In the form of 
            foreach (string str in item)
                Console.WriteLine(str);
            // The above is based on WebService Address, analog generation 1 A proxy class , If you want to see what the generated code file looks like, you can save it in the following code bin Under the directory 
            TextWriter writer = File.CreateText("MyTest.cs"); 
            provider.GenerateCodeFromCompileUnit(unit, writer, null);
            writer.Flush();
            writer.Close();
        } 
    }
}

Method 2: Use ES23en. exe to generate webservice proxy class:
Generate the webservice proxy class from the supplied wsdl, and then reference the class file in the code.
Steps:
1. Find Visual Studio Tools under Microsoft Visual Studio 2010 in the start menu, click Visual Studio command prompt (2010) and open the command line.
2, at the command line input: wsdl/language: c # / n: TestDemo/out: d: / Temp/TestService cs http: / / jm1 services. gmcc. net ad/Services/AD asmx? wsdl
Compile the last service address and generate the testservice file in the D disk temp directory.
3. Copy the cs file compiled by the above command into our project. After new 1 is directly out of the project code, it can be called.
Post the code compiled from the command line:

View Code 
//------------------------------------------------------------------------------
// <auto-generated>
//      This code is generated by the tool. 
//      Runtime version :4.0.30319.225
//
//      Changes to this file may cause incorrect behavior, and if 
//      Regenerate the code and these changes will be lost. 
// </auto-generated>
//------------------------------------------------------------------------------
// 
//  This source code is provided by  wsdl  Automatically generate , Version=4.0.30319.1 . 
// 
namespace Bingosoft.Module.SurveyQuestionnaire.DAL {
    using System;
    using System.Diagnostics;
    using System.Xml.Serialization;
    using System.ComponentModel;
    using System.Web.Services.Protocols;
    using System.Web.Services;
    using System.Data;

    
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="WebserviceForILookSoap", Namespace="http://tempuri.org/")]
    public partial class WebserviceForILook : System.Web.Services.Protocols.SoapHttpClientProtocol {

        private System.Threading.SendOrPostCallback GetRecordNumOperationCompleted;

        private System.Threading.SendOrPostCallback GetVoteListOperationCompleted;

        private System.Threading.SendOrPostCallback VoteOperationCompleted;

        private System.Threading.SendOrPostCallback GiveUpOperationCompleted;

        private System.Threading.SendOrPostCallback GetQuestionTaskListOperationCompleted;

        /// <remarks/>
        public WebserviceForILook() {
            this.Url = "http://st1.services.gmcc.net/qnaire/Services/WebserviceForILook.asmx";
        }

        /// <remarks/>
        public event GetRecordNumCompletedEventHandler GetRecordNumCompleted;

        /// <remarks/>
        public event GetVoteListCompletedEventHandler GetVoteListCompleted;

        /// <remarks/>
        public event VoteCompletedEventHandler VoteCompleted;

        /// <remarks/>
        public event GiveUpCompletedEventHandler GiveUpCompleted;

        /// <remarks/>
        public event GetQuestionTaskListCompletedEventHandler GetQuestionTaskListCompleted;

        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetRecordNum", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public int[] GetRecordNum(string appcode, string userID) {
            object[] results = this.Invoke("GetRecordNum", new object[] {
                        appcode,
                        userID});
            return ((int[])(results[0]));
        }

        /// <remarks/>
        public System.IAsyncResult BeginGetRecordNum(string appcode, string userID, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("GetRecordNum", new object[] {
                        appcode,
                        userID}, callback, asyncState);
        }

        /// <remarks/>
        public int[] EndGetRecordNum(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((int[])(results[0]));
        }

        /// <remarks/>
        public void GetRecordNumAsync(string appcode, string userID) {
            this.GetRecordNumAsync(appcode, userID, null);
        }

        /// <remarks/>
        public void GetRecordNumAsync(string appcode, string userID, object userState) {
            if ((this.GetRecordNumOperationCompleted == null)) {
                this.GetRecordNumOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRecordNumOperationCompleted);
            }
            this.InvokeAsync("GetRecordNum", new object[] {
                        appcode,
                        userID}, this.GetRecordNumOperationCompleted, userState);
        }

        private void OnGetRecordNumOperationCompleted(object arg) {
            if ((this.GetRecordNumCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.GetRecordNumCompleted(this, new GetRecordNumCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
            }
        }

        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetVoteList", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public System.Data.DataSet GetVoteList(string appcode, string userID) {
            object[] results = this.Invoke("GetVoteList", new object[] {
                        appcode,
                        userID});
            return ((System.Data.DataSet)(results[0]));
        }

        /// <remarks/>
        public System.IAsyncResult BeginGetVoteList(string appcode, string userID, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("GetVoteList", new object[] {
                        appcode,
                        userID}, callback, asyncState);
        }

        /// <remarks/>
        public System.Data.DataSet EndGetVoteList(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((System.Data.DataSet)(results[0]));
        }

        /// <remarks/>
        public void GetVoteListAsync(string appcode, string userID) {
            this.GetVoteListAsync(appcode, userID, null);
        }

        /// <remarks/>
        public void GetVoteListAsync(string appcode, string userID, object userState) {
            if ((this.GetVoteListOperationCompleted == null)) {
                this.GetVoteListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetVoteListOperationCompleted);
            }
            this.InvokeAsync("GetVoteList", new object[] {
                        appcode,
                        userID}, this.GetVoteListOperationCompleted, userState);
        }

        private void OnGetVoteListOperationCompleted(object arg) {
            if ((this.GetVoteListCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.GetVoteListCompleted(this, new GetVoteListCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
            }
        }

        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Vote", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public bool Vote(string appcode, string userID, string qTaskID, string answer) {
            object[] results = this.Invoke("Vote", new object[] {
                        appcode,
                        userID,
                        qTaskID,
                        answer});
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public System.IAsyncResult BeginVote(string appcode, string userID, string qTaskID, string answer, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("Vote", new object[] {
                        appcode,
                        userID,
                        qTaskID,
                        answer}, callback, asyncState);
        }

        /// <remarks/>
        public bool EndVote(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public void VoteAsync(string appcode, string userID, string qTaskID, string answer) {
            this.VoteAsync(appcode, userID, qTaskID, answer, null);
        }

        /// <remarks/>
        public void VoteAsync(string appcode, string userID, string qTaskID, string answer, object userState) {
            if ((this.VoteOperationCompleted == null)) {
                this.VoteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnVoteOperationCompleted);
            }
            this.InvokeAsync("Vote", new object[] {
                        appcode,
                        userID,
                        qTaskID,
                        answer}, this.VoteOperationCompleted, userState);
        }

        private void OnVoteOperationCompleted(object arg) {
            if ((this.VoteCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.VoteCompleted(this, new VoteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
            }
        }

        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GiveUp", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public bool GiveUp(string appcode, string userID, string qTaskID) {
            object[] results = this.Invoke("GiveUp", new object[] {
                        appcode,
                        userID,
                        qTaskID});
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public System.IAsyncResult BeginGiveUp(string appcode, string userID, string qTaskID, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("GiveUp", new object[] {
                        appcode,
                        userID,
                        qTaskID}, callback, asyncState);
        }

        /// <remarks/>
        public bool EndGiveUp(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public void GiveUpAsync(string appcode, string userID, string qTaskID) {
            this.GiveUpAsync(appcode, userID, qTaskID, null);
        }

        /// <remarks/>
        public void GiveUpAsync(string appcode, string userID, string qTaskID, object userState) {
            if ((this.GiveUpOperationCompleted == null)) {
                this.GiveUpOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGiveUpOperationCompleted);
            }
            this.InvokeAsync("GiveUp", new object[] {
                        appcode,
                        userID,
                        qTaskID}, this.GiveUpOperationCompleted, userState);
        }

        private void OnGiveUpOperationCompleted(object arg) {
            if ((this.GiveUpCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.GiveUpCompleted(this, new GiveUpCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
            }
        }

        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetQuestionTaskList", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public System.Data.DataSet GetQuestionTaskList(string appcode, string userID) {
            object[] results = this.Invoke("GetQuestionTaskList", new object[] {
                        appcode,
                        userID});
            return ((System.Data.DataSet)(results[0]));
        }

        /// <remarks/>
        public System.IAsyncResult BeginGetQuestionTaskList(string appcode, string userID, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("GetQuestionTaskList", new object[] {
                        appcode,
                        userID}, callback, asyncState);
        }

        /// <remarks/>
        public System.Data.DataSet EndGetQuestionTaskList(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((System.Data.DataSet)(results[0]));
        }

        /// <remarks/>
        public void GetQuestionTaskListAsync(string appcode, string userID) {
            this.GetQuestionTaskListAsync(appcode, userID, null);
        }

        /// <remarks/>
        public void GetQuestionTaskListAsync(string appcode, string userID, object userState) {
            if ((this.GetQuestionTaskListOperationCompleted == null)) {
                this.GetQuestionTaskListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetQuestionTaskListOperationCompleted);
            }
            this.InvokeAsync("GetQuestionTaskList", new object[] {
                        appcode,
                        userID}, this.GetQuestionTaskListOperationCompleted, userState);
        }

        private void OnGetQuestionTaskListOperationCompleted(object arg) {
            if ((this.GetQuestionTaskListCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.GetQuestionTaskListCompleted(this, new GetQuestionTaskListCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
            }
        }

        /// <remarks/>
        public new void CancelAsync(object userState) {
            base.CancelAsync(userState);
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    public delegate void GetRecordNumCompletedEventHandler(object sender, GetRecordNumCompletedEventArgs e);

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GetRecordNumCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

        private object[] results;

        internal GetRecordNumCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }

        /// <remarks/>
        public int[] Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((int[])(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    public delegate void GetVoteListCompletedEventHandler(object sender, GetVoteListCompletedEventArgs e);

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GetVoteListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

        private object[] results;

        internal GetVoteListCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }

        /// <remarks/>
        public System.Data.DataSet Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((System.Data.DataSet)(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    public delegate void VoteCompletedEventHandler(object sender, VoteCompletedEventArgs e);

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class VoteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

        private object[] results;

        internal VoteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }

        /// <remarks/>
        public bool Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((bool)(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    public delegate void GiveUpCompletedEventHandler(object sender, GiveUpCompletedEventArgs e);

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GiveUpCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

        private object[] results;

        internal GiveUpCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }

        /// <remarks/>
        public bool Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((bool)(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    public delegate void GetQuestionTaskListCompletedEventHandler(object sender, GetQuestionTaskListCompletedEventArgs e);

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

        private object[] results;

        internal GetQuestionTaskListCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }

        /// <remarks/>
        public System.Data.DataSet Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((System.Data.DataSet)(this.results[0]));
            }
        }
    }
}

Method 3: get and post using http protocol
This is the most flexible approach.

View Code 
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Bingosoft.RIA.Common
{
    /// <summary>
    ///   using WebRequest/WebResponse for WebService A class is called 
    /// </summary>
    public class WebServiceCaller
    {
        #region Tip: Directions for use 
        //webServices  Should support Get and Post A call, web.config The following code should be added 
        //<webServices>
        //  <protocols>
        //    <add name="HttpGet"/>
        //    <add name="HttpPost"/>
        //  </protocols>
        //</webServices>
        // Example call: 
        //Hashtable ht = new Hashtable();  //Hashtable  for webservice The set of parameters required 
        //ht.Add("str", "test");
        //ht.Add("b", "true");
        //XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);
        //MessageBox.Show(xx.OuterXml);
        #endregion
        /// <summary>
        ///  Need to be WebService support Post call 
        /// </summary>
        public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            SetWebRequest(request);
            byte[] data = EncodePars(Pars);
            WriteRequestData(request, data);
            return ReadXmlResponse(request.GetResponse());
        }
        /// <summary>
        ///  Need to be WebService support Get call 
        /// </summary>
        public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            SetWebRequest(request);
            return ReadXmlResponse(request.GetResponse());
        }
        /// <summary>
        ///  general WebService call (Soap), parameter Pars for String Type parameter name, parameter value 
        /// </summary>
        public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
        {
            if (_xmlNamespaces.ContainsKey(URL))
            {
                return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
            }
            else
            {
                return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
            }
        }
        private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
        {
            _xmlNamespaces[URL] = XmlNs;// Add cache to improve efficiency 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "text/xml; charset=utf-8";
            request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
            SetWebRequest(request);
            byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
            WriteRequestData(request, data);
            XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
            doc = ReadXmlResponse(request.GetResponse());
            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
            mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
            doc2.LoadXml("<root>" + RetXml + "</root>");
            AddDelaration(doc2);
            return doc2;
        }
        private static string GetNamespace(String URL)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
            SetWebRequest(request);
            WebResponse response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sr.ReadToEnd());
            sr.Close();
            return doc.SelectSingleNode("//@targetNamespace").Value;
        }
        private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"></soap:Envelope>");
            AddDelaration(doc);
            //XmlElement soapBody = doc.createElement_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
            XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
            //XmlElement soapMethod = doc.createElement_x_x(MethodName);
            XmlElement soapMethod = doc.CreateElement(MethodName);
            soapMethod.SetAttribute("xmlns", XmlNs);
            foreach (string k in Pars.Keys)
            {
                //XmlElement soapPar = doc.createElement_x_x(k);
                XmlElement soapPar = doc.CreateElement(k);
                soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
                soapMethod.AppendChild(soapPar);
            }
            soapBody.AppendChild(soapMethod);
            doc.DocumentElement.AppendChild(soapBody);
            return Encoding.UTF8.GetBytes(doc.OuterXml);
        }
        private static string ObjectToSoapXml(object o)
        {
            XmlSerializer mySerializer = new XmlSerializer(o.GetType());
            MemoryStream ms = new MemoryStream();
            mySerializer.Serialize(ms, o);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
            if (doc.DocumentElement != null)
            {
                return doc.DocumentElement.InnerXml;
            }
            else
            {
                return o.ToString();
            }
        }
        /// <summary>
        ///  Set the credentials and timeout 
        /// </summary>
        /// <param name="request"></param>
        private static void SetWebRequest(HttpWebRequest request)
        {
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000;
        }
        private static void WriteRequestData(HttpWebRequest request, byte[] data)
        {
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
        }
        private static byte[] EncodePars(Hashtable Pars)
        {
            return Encoding.UTF8.GetBytes(ParsToString(Pars));
        }
        private static String ParsToString(Hashtable Pars)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in Pars.Keys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }
                //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
            }
            return sb.ToString();
        }
        private static XmlDocument ReadXmlResponse(WebResponse response)
        {
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Close();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(retXml);
            return doc;
        }
        private static void AddDelaration(XmlDocument doc)
        {
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.InsertBefore(decl, doc.DocumentElement);
        }
        private static Hashtable _xmlNamespaces = new Hashtable();// The cache xmlNamespace To avoid repeated calls GetNamespace
    }
}


Related articles: