Dynamic Web Service Invocation using Aync Method

Matt Paisley 116 Reputation points
2020-10-27T17:26:39+00:00

Hello,

I am trying to implement a class library that I can use to dynamically invoke Web Services. I have built the following code from samples that I have found on the web:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
using System.ServiceModel;  
using System.ServiceModel.Description;  
  
using System.Net;  
using System.IO;  
using System.Web;  
using System.Text.RegularExpressions;  
using System.Runtime.Remoting.Messaging;  
  
  
namespace DynamicBP  
{  
    public class WebServiceClient  
    {  
        #region Delegates  
        public delegate string DelegateInvokeService();  
        #endregion  
  
        #region Enumerators  
        public enum ServiceType  
        {  
            Traditional =0,  
            WCF = 1  
        }  
        #endregion  
  
        #region Classes  
        public class Parameter  
        {  
            public string Name { get; set; }  
            public string Value { get; set; }  
        }  
        #endregion  
  
        #region Member Variables  
        string _soapEnvelope =  
                @"<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:Body></soap:Body></soap:Envelope>";  
  
        #endregion  
  
        #region Properties  
        public string Url { get; set; }  
  
        public string WebMethod { get; set; }  
  
        public List<Parameter> Parameters { get; set; }  
  
        public ServiceType WSServiceType { get; set; }  
  
        public string WCFContractName { get; set; }  
          
        public string Lid { get; set; }  
  
        public string Lpw { get; set; }  
  
        #endregion  
  
        #region Private Methods  
        private string CreateSoapEnvelope()  
        {  
            string MethodCall = "<" + this.WebMethod + @" xmlns=""http://tempuri.org/"">";  
            string StrParameters = string.Empty;  
  
            foreach (Parameter param in this.Parameters)  
            {  
                StrParameters = StrParameters + "<" + param.Name + ">" + param.Value + "</" + param.Name + ">";  
            }  
  
            MethodCall = MethodCall + StrParameters + "</" + this.WebMethod + ">";  
  
            StringBuilder sb = new StringBuilder(_soapEnvelope);  
            sb.Insert(sb.ToString().IndexOf("</soap:Body>"), MethodCall);  
  
            return sb.ToString();  
        }  
  
        private HttpWebRequest CreateWebRequest()  
        {  
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(this.Url);  
            if (this.WSServiceType == WebServiceClient.ServiceType.WCF)  
                webRequest.Headers.Add("SOAPAction", "\"http://tempuri.org/" + this.WCFContractName + "/" + this.WebMethod + "\"");  
            else  
                webRequest.Headers.Add("SOAPAction", "\"http://tempuri.org/" + this.WebMethod + "\"");  
  
            webRequest.Headers.Add("To", this.Url);  
  
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";  
            webRequest.Accept = "text/xml";  
            webRequest.Method = "POST";  
            return webRequest;  
        }  
  
        private string StripResponse(string SoapResponse)  
        {  
            string RegexExtract = @"<" + this.WebMethod + "Result>(?<Result>.*?)</" + this.WebMethod + "Result>";  
  
            return Regex.Match(SoapResponse, RegexExtract).Groups["Result"].Captures[0].Value;  
        }  
        #endregion  
  
        #region Public Methods  
        public void BeginInvokeService(AsyncCallback InvokeCompleted)  
        {  
            DelegateInvokeService Invoke = new DelegateInvokeService(this.InvokeService);  
  
             IAsyncResult result = Invoke.BeginInvoke(InvokeCompleted, null);  
        }  
  
        public string EndInvokeService(IAsyncResult result)  
        {  
            var asyncResult = (AsyncResult)result;  
            ReturnMessage msg = (ReturnMessage)asyncResult.GetReplyMessage();  
  
            return msg.ReturnValue.ToString();  
        }  
  
        public string InvokeService()  
        {  
            WebResponse response = null;  
            string strResponse = "";  
  
            //Create the request  
            HttpWebRequest req = this.CreateWebRequest();  
  
            //write the soap envelope to request stream  
            using (Stream stm = req.GetRequestStream())  
            {  
                using (StreamWriter stmw = new StreamWriter(stm))  
                {  
                    stmw.Write(this.CreateSoapEnvelope());  
                }  
            }  
  
            //get the response from the web service  
            response = req.GetResponse();  
  
            Stream str = response.GetResponseStream();  
  
            StreamReader sr = new StreamReader(str);  
  
            strResponse = sr.ReadToEnd();              
  
            return this.StripResponse(HttpUtility.HtmlDecode(strResponse));  
        }  
        #endregion  
    }  
}  

I have built the following Test Application:

using System;  
using System.Collections.Generic;  
using DynamicBP;  
  
namespace TestDynamicBP  
{  
      
    class TestDynamicBP  
    {  
        static DynamicBP.WebServiceClient client = null;  
  
   
        static void Main(string[] args)  
        {  
            List<WebServiceClient.Parameter> lstParameters = new List<WebServiceClient.Parameter>();  
  
  
            lstParameters.Add(new WebServiceClient.Parameter { Name = "bpinstance", Value = "auto" });  
            lstParameters.Add(new WebServiceClient.Parameter { Name = "CorporateName", Value = "Amphenol" });  
  
  
  
            client = new WebServiceClient  
  
            {  
  
                WebMethod = "EntitySearch",  
  
                Url = "http://DESKTOP-OODBQR9:8185/ws/CorporateSearchCT",  
  
                WSServiceType = WebServiceClient.ServiceType.Traditional,  
  
                WCFContractName = "IDynamicBP",  
  
                Parameters = lstParameters  
  
            };  
  
            client.BeginInvokeService(InvokeCompleted);  
  
  
  
            Console.ReadLine();  
        }  
  
        private static void InvokeCompleted(IAsyncResult result)  
        {  
            string returnFromService = client.EndInvokeService(result);  
        }  
    }  
}  

When I run the Test Application in Debug an error is thrown from inside of my DynamicBP library: Operation is not supported on this platform.

Any assistance that can be provided will be greatly appreciated. Thank you.

Matthew Paisley

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,624 questions
{count} votes

Accepted answer
  1. Matt Paisley 116 Reputation points
    2020-10-29T16:01:41.87+00:00

    Thanks to PengDing,

    I created a new project using .NET Standard and imported my code into it. The error was resolved with the Root Cause being that originally the project was built with .NET Core , which does not support the methods I was using.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Peng Ding-MSFT 96 Reputation points
    2020-10-30T01:25:25.383+00:00

    Hi @Matt Paisley , The reason for this error is that the Async delegates is not in .NET Core. This error will occur if you use Async delegates in .Net Core.

    Async delegates are not in .NET Core for several reasons:

    1. Async delegates use deprecated IAsyncResult-based async pattern. This pattern is generally not supported throughout .NET Core base libraries, e.g. System.IO.Stream does not have IAsyncResult-based overloads for Read/Write methods in .NET Core.
    2. Async delegates depend on remoting (System.Runtime.Remoting) under the hood. Remoting is not in .NET Core - implementation of async delegates without remoting would be challenging.

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments