Search This Blog

Tuesday, November 26, 2019

Web Service Manual calling using C# console app


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Net;
using System.Security.Cryptography.X509Certificates;

namespace ManualSOAPCall
{
    public class TrustAllCertificatePolicy : ICertificatePolicy
    {
        public TrustAllCertificatePolicy() { }

        public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
        {
            return true;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // using System.Net;
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
            // Use SecurityProtocolType.Ssl3 if needed for compatibility reasons

            #region ContactServiceTest
            var contactServiceUrl = ConfigurationManager.AppSettings["ContactServiceURL"];
            //var actionName = "GetSoldToBPandContact";
            var actionName = "getItemPrice";
            var actionNameSpace = "http://www.test.com/businessinterface/DW_ItemPrice_CT";
            // var typeObject = "GetSoldToBPandContactRequest";
            var typeObject = "getItemTestRequest";
            var requestObject = "SW_ItemPrice_ST";
            var parms = new Dictionary<string, string>();
            parms.Add("ProcessingScope", "request");
            ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
            string contactResult = SOAPHelper.SendSOAPRequest(contactServiceUrl, actionName, actionNameSpace, typeObject, requestObject, parms, "", false);
            Console.Write(contactResult);
            Console.ReadLine();



        }
    }
}
  public static class SOAPHelper
    {
        /// <summary>
        /// Sends a custom sync SOAP request to given URL and receive a request
        /// </summary>
        /// <param name="url">The WebService endpoint URL</param>
        /// <param name="action">The WebService action name</param>
        /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
        /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
        /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
        /// <returns>A string containing the raw Web Service response</returns>
        public static string SendSOAPRequest(string url, string actionName, string actionNameSpace, string typeObject, string requestObject, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
        { // using System.Net;
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
            // Create the SOAP envelope
            XmlDocument soapEnvelopeXml = new XmlDocument();

            var xmlStrPrice = (useSOAP12)
  ? @"<?xml version=""1.0"" encoding=""utf-8""?><soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope""><soap12:Body><{0} xmlns=""{1}""><{2}>{3}</{2}></{0}></soap12:Body></soap12:Envelope>"
  : @"<?xml version=""1.0"" encoding=""utf-8""?><soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""  xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                <soap:Body><{0} xmlns=""{1}""><{2} xmlns=""""><ControlArea><{3}>{4}</{3}></ControlArea></{2}></{0}>
                </soap:Body>
                </soap:Envelope>";
            string parmsPrice = string.Join(url, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
            var str = String.Format(xmlStrPrice, actionName, actionNameSpace, typeObject, requestObject, parmsPrice);
            soapEnvelopeXml.LoadXml(str);

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

            HttpWebRequest request = (HttpWebRequest)
                            HttpWebRequest.Create(url);

            String xmlString = str;
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] bytesToWrite = encoding.GetBytes(xmlString);

            request.Method = "POST";
            request.ContentLength = bytesToWrite.Length;
            request.Headers.Add("SOAPAction: \"\""); //You need to change this
            request.ContentType = "text/xml; charset=utf-8";

            request.Timeout = Timeout.Infinite;
            request.KeepAlive = true;
            Stream newStream = request.GetRequestStream();
            newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);

            string responseFromServer = reader.ReadToEnd();

            return responseFromServer;
        }
    }

No comments:

Post a Comment