C# soap request - c#

I have done a request SOAP with SOAPUI and all works fine. The request is equal to the xmlString with Basic Authentication type.
I need to do this request into a c# solution but my code doesn't work:
string xmlString = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:soap=""http://soap.service.tracking.sda.it/"">
<soapenv:Header/>
<soapenv:Body>
<soap:doIt>
<arg0>
<!--Optional:-->
<codCliente>00000000001</codCliente>
<!--1 to 10 repetitions:-->
<datiSpedizione>
<!--You may enter the following 3 items in any order-->
<!--Optional:-->
<idLdv>000001</idLdv>
<!--Optional:-->
<ultimoStato>N</ultimoStato>
</datiSpedizione>
<descrizioneStatus>E</descrizioneStatus>
<!--Optional:-->
<postazione>00001</postazione>
<tipologiaCliente>SDA</tipologiaCliente>
</arg0>
</soap:doIt>
</soapenv:Body>
</soapenv:Envelope>";
HttpWebRequest request = CreateWebRequest("https://ws.sda.it/TRACKING","user","pass");
request.PreAuthenticate = true;
request.ReadWriteTimeout = 32000;
request.Timeout = 32000;
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(xmlString);
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
}
}
And this is the createWebRequestMethod:
public static HttpWebRequest CreateWebRequest(string url, string user, string pass)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Credentials = new NetworkCredential(user, pass);
webRequest.Headers.Add(#"SOAPAction", "TRACKING");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
When i try to use this code i go into an exception of "Null reference" in the request.GetResponse()

Related

HTTPWebRequest Response Error when sending SOAP

I am using XDocument to manually build a SOAP request and send it using HTTPWebRequest. The final output of the XDocument object is valid and when I capture and send it to the end point using SOAPUI it works fine, however; I have been unable to get this to work using HTTPWebRequest. I receive internal server server errors, but nothing really specific that I can work from. I am excluding the XDocument object for brevity. Any guidance would be appreciated.
var _url = "http://xxx.xx.x.xx:9191/aa/bb/cc/dd";
var _action = "http://xxx.xx.x.xx:9191/aa/bb/cc/dd?op=submit";
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(_url);
webRequest.Headers.Add(#"SOAPAction", _action);
webRequest.Credentials = new NetworkCredential("xxxxx", "xxxxxx");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
using (Stream stream = webRequest.GetRequestStream())
{
xd.Save(stream);
}
// get the response from the completed web request.
string soapResult;
try
{
using (WebResponse webResponse = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Response.Write(soapResult);
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Response.Write("Status Code : " + ((HttpWebResponse) ex.Response).StatusCode);
Response.Write("Status Description : " + ((HttpWebResponse) ex.Response).StatusDescription);
}
}
UPDATE (included small sample of SOAP):
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<enrollment xmlns="xxxxxxxxxxx">
<asOfDate xmlns="">2018-01-01</asOfDate>
<activate xmlns="">false</activate>
<subscription xmlns="">
<receiptDate>2018-06-01</receiptDate>
<accountMatchData>
<accountHccIdentifier>
<accountHccIdentificationNumber>xxxxxxxxxx</accountHccIdentificationNumber>
</accountHccIdentifier>
<asOfDate>2018-01-01</asOfDate>
</accountMatchData>
<informationSourceCode>
<codeEntry>3</codeEntry>
</informationSourceCode>
</subscription>
</enrollment>
</s:Body>
</s:Envelope>
UPDATE (Solved):
I cannot believe it was something as stupid as how it was sending the credentials. I used the below code to generate the credentials and add them to the HTTPWebRequest and it worked.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("xxxx" + ":" + "xxxxxxx"));
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(_url);
webRequest.Headers[HttpRequestHeader.Authorization] = string.Format(
"Basic {0}", credentials);

LinkedIn send a message

I want to send a message to LinkedIn user from my connections. I try the following code:
string s = #"<?xml version='1.0' encoding='UTF-8'?>
<mailbox-item>
<recipients>
<recipient>
<person path='/people/1234567' />
</recipient>
</recipients>
<subject>Congratulations on Test.</subject>
<body>Test Here</body>
</mailbox-item>";
string url = "https://api.linkedin.com/v1/people/~/mailbox?oauth2_access_token=XXXXXXXXXXXX";
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Timeout = 10000;
webRequest.ContentType = "text/xml";
webRequest.Method = "POST";
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(s);
}
WebResponse response = webRequest.GetResponse();
I get an exception "The remote server returned an error: (400) Bad Request." on the last string. What is incorrectly?

Post SOAP envelop to MS Dynamics NAV Web Service

I am trying to post SOAP Envelope directly to Dynamics NAV Webservices using HttpWebRequest, HttpWebResponse.
Code:
private void button1_Click(object sender, EventArgs e)
{
string requestString = LoadData();
HttpWebRequest request;
HttpWebResponse response = null;
string url = "http://localhost:7047/DynamicsNAV70/WS/Page/nav_Item";
byte[] requestBuffer = null;
Stream postStream = null;
Stream responseStream = null;
StreamReader responseReader = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.ProtocolVersion = new Version(1,1);
request.Method = "POST";
//request.Headers.Add("SOAPAction", #"urn:microsoft-dynamics-schemas/page/nav_item:create");
request.Headers.Add("Action", #"urn:microsoft-dynamics-schemas/page/nav_item");
//request.Headers.Add("Content-Type", #"text/xml; charset=utf-8");
request.ContentType = #"application/xml; charset=utf-8";
requestBuffer = Encoding.ASCII.GetBytes(requestString);
request.ContentLength = requestBuffer.Length;
request.UseDefaultCredentials = true;
postStream = request.GetRequestStream();
postStream.Write(requestBuffer, 0, requestBuffer.Length);
postStream.Close();
response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
string response_result=string.Empty;
if (responseStream != null)
{
responseReader = new StreamReader(responseStream);
response_result = responseReader.ReadToEnd();
}
MessageBox.Show(response_result);
}
private string LoadData()
{
// throw new NotImplementedException();
XmlDocument oCustomer = new XmlDocument();
oCustomer.Load(#"C:\Users\kishore.LOCAL.000\Desktop\NAV_DEMO\NAV_DEMO\bin\Debug\input\item.xml");
return oCustomer.InnerXml;
}
Format of SOAP Envelope is below:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins="urn:microsoft-dynamics-schemas/page/nav_item">
<soapenv:Header/>
<soapenv:Body>
<ins:Create>
<ins:nav_Item>
<!--Optional:-->
<ins:Key>?</ins:Key>
<!--Optional:-->
<ins:No>1234</ins:No>
<!--Optional:-->
<ins:Description>Test Item</ins:Description>
</ins:nav_Item>
</ins:Create>
</soapenv:Body>
</soapenv:Envelope>
But when I am trying to get response without Header in HttpWebRequest, its returning whole web service in xml format with Status OK, but Item is not inserting in NAV.
When I am trying to get response with Header in HttpWebRequest, its {"The remote server returned an error: (500) Internal Server Error." System.Net.WebExceptionStatus.ProtocolError}
I want to create Item in NAV using soap envelope not by direct referencing the service.
Any help will helpful to me.
With Regards
Kishore K
It looks like you using SOAPui to create request xml. This app always adds invisible chars at the end of each line. Delete them.
Also try to unformat your request, e.g. make it in one line. For unknown reason Nav threats linebreake between certain tags as error (throws http 500). I just forgot which tags (header and body may be). The rest linebreaks are fine.
And SOAPAction header is mandatory so use it or you will get wsdl in response all the time.
P.s. beta of SOAPui works fine with Nav and supports NTLM so you can use it to test different request xml and find which format is correct.
I am new to using intergrating with nav web services, I am trying to send an xml request using a simple c# console application but it is always returning a 401(unauthorised)
static void Main(string[] args)
{
Console.WriteLine("We have started");
string pageName = "http://hrp-dmu.uganda.hrpsolutions.co.ug:9047/DynamicsNAV80/WS/Uganda%20Management%20Institute/Page/CustomerWS";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pageName);
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
req.ProtocolVersion = new Version(1, 1);
req.Headers.Add("SOAPAction", #"urn:microsoftdynamicsschemas/page/customerws:Create");
Console.WriteLine("After preparing request object");
string xmlRequest = GetTextFromXMLFile("E:\\tst3.xml");
Console.WriteLine("xml request : "+xmlRequest);
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
req.ContentLength = reqBytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("GetRequestStreamException : " + ex.Message);
}
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
Console.WriteLine("GetResponseException : " + exc.Message);
}
string xmlResponse = null;
if (resp == null)
{
Console.WriteLine("Null response");
}
else
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine("The response");
Console.WriteLine(xmlResponse);
}
Console.ReadKey();
}
private static string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}

Internal Server Error (500) when doing SOAP request

I am trying to do a SOAP request but the server is returning an 500 error.
The SOAP request returns correctly the XML message via jmeter for example, so it must be something in my code, but i fail to see what. Can you help?
private void soapRequest(string regID)
{
string soapReq= #"<?xml version=""1.0"" encoding=""utf-8""?>";
soapReq= "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:mpc=\"urn://mobility-platform.de/mpcustomerdb/\">\n";
soapReq += "<soapenv:Header/>\n";
soapReq += "<soapenv:Body>\n";
soapReq += "<mpc:findRegistrationByID>\n";
soapReq += "<registrationID>" + regID + "</registrationID>\n";
soapReq += "</mpc:findRegistrationByID>\n";
soapReq += "</soapenv:Body>\n";
soapReq += "</soapenv:Envelope>";
//Builds the connection to the WebService.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://url?wsdl");
req.Credentials = new NetworkCredential("user", "pass");
req.Headers.Add("SOAP:Action");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
//Passes the SoapRequest String to the WebService
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soapReq.ToString());
}
}
try
{
//Gets the response
HttpWebResponse soapResponse = (HttpWebResponse)req.GetResponse();
//Writes the Response
Stream responseStream = soapResponse.GetResponseStream();
//read the stream
XmlDocument soapResponseXML = new XmlDocument();
StreamReader responseStreamRead = new StreamReader(responseStream);
soapResponse.ContentType = "text/xml";
//MessageBox.Show(responseStreamRead.ReadToEnd().ToString());
string soapURL = responseStreamRead.ReadToEnd().ToString();
soapResponseXML.LoadXml(soapURL);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
Here is the soap request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mpc="urn://mobility-platform.de/mpcustomerdb/">
<soapenv:Header/>
<soapenv:Body>
<mpc:findRegistrationByID>
<registrationID>2304580</registrationID>
</mpc:findRegistrationByID>
</soapenv:Body>
</soapenv:Envelope>
Later edit:
If i change
req.Headers.Add("SOAP:Action"); to:
req.Headers.Add("SOAPAction", ""\"http://url\"" + "findRegistrationByID");
i get an different error:
"This property is not implemented by this class"
Is not very easy to make an proper soap request with this method. I am strongly recommending to use rather the whole web service, and rather make the request like this:
WebService aa = new WebService;
registrationName = aa.findRegistrationByID("123");
This will accomplish all the above code ;)

SOAP Request Failure

I'm trying to make a SOAP request in C#. Using SoapUI, I have successfully made the required request, so I basically copied the request string into the LoadXml of the following C# code:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#"https://w8cert.iconnectdata.com:443/FleetCreditWS/services/FleetCreditWS0200");
webRequest.Headers.Add(#"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(#"<?xml version=""1.0"" encoding=""utf-8"" ?><soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:main=""http://fleetCredit02.comdata.com/maintenance/"" xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
<soapenv:Header>
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>{MyUserName}</wsse:Username>
<wsse:Password>{MyPassword}</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<main:ProprietaryIntradayRequest>
<startDate>2018-02-06</startDate>
<maskCardFlag>false</maskCardFlag>
</main:ProprietaryIntradayRequest>
</soapenv:Body>
</soapenv:Envelope>");
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
WebResponse response;
try
{
using (response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
}
}
}
catch (WebException e)
{
StreamReader str = new StreamReader(e.Response.GetResponseStream());
System.Diagnostics.Debugger.Break();
}
This code throws the ever-fun (500) Internal Server Error on the "using (response = webRequest.GetResponse())" line. I even tried to capture the web exception response, but get the same 500 error.
Can anyone see something I'm missing that would cause the same request to work in SoapUI, but fail in C#?

Categories

Resources