C# code to send an XML to a webservice

I have attached the C# code that I have tried, but it is returning an error message. (In this code, I am reading the XML file contents and sent it to the web service.)
"The remote server returned an error: (500) Internal Server Error."

I have tried the same XML in the tool soapUI 3.5 ( http://www.soapui.org/ ). This tool is showing the response from webservice.
I am trying to the do the same thing in C# code and display the response code in web page using ASP.Net / C#

What am I doing wrong... ?

Thanks
Raj
using System;
using System.Configuration;
using System.Data;
using System.Net;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(HttpContext.Current.Server.MapPath(".") + "\\createEmployee.XML");
        StringBuilder rawXml = new StringBuilder();
        rawXml.Append(GetXmlString(xmlDoc));

        PostXml("http://xxx.com/webservice/services/yyyService?wsdl", rawXml.ToString());
        
    }

    public void PostXml(string url, string xml)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(xml);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentLength = bytes.Length;
        request.ContentType = "text/xml";
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(bytes, 0, bytes.Length);
        }


	// <-- Error :- The remote server returned an error: (500) Internal Server Error." (Attached the code)
        HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
        if (response.StatusCode != HttpStatusCode.OK)
        {
            string message = String.Format("POST failed. Received HTTP {0}",
            response.StatusCode);
            throw new ApplicationException(message);
        }
    }

    static string GetXmlString(XmlDocument xmlDoc)
    {

        // Now create StringWriter object to get data from xml document.
        StringWriter sw = new StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);
        xmlDoc.WriteTo(xw);
        return sw.ToString();
    }

}

Open in new window

LVL 23
Rajkumar GsSoftware EngineerAsked:
Who is Participating?
 
Rajkumar GsConnect With a Mentor Software EngineerAuthor Commented:
Alas! Finally achieved my goal!!

Here is the working code.
 [embed=snippet 1019357]
I got msxml2.dll (namespace used in this code) from http://www.dlldump.com/download-dll-files.php/dllfiles/M/msxml2.dll/download.html

Now I able to send an XML to Workspeed webservice and able to receive the response XML and write it an XML file.

It is the same VBScript coding that client provided early! As they suggested, my code was missing this header line
  objXmlHTTP.setRequestHeader "SOAPAction:" , serviceUrl

I was behind the code using 'HttpWebRequest'. Used 'XMLHTTP' instead and working now :)
using MSXML2;

public void PostXMLtoWebService(string sourceXMLFile)
    {
        MSXML2.XMLHTTP objXmlHTTP = new XMLHTTP();
        string serviceUrl = "http://acpt2-newmenu.workspeed.com/webservice/services/MessageService";

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(sourceXMLFile);

        objXmlHTTP.open("POST", serviceUrl, false, null, null);
        objXmlHTTP.setRequestHeader("SOAPAction:", serviceUrl);
        objXmlHTTP.send(xmlDoc.InnerXml);
        string strSOAPResponse = objXmlHTTP.responseText.ToString();

        // Write the response XML to an XML file
        TextWriter tw = new StreamWriter("C:\\XML\\response.xml");
        tw.WriteLine(strSOAPResponse);
        tw.Close();
    }

Open in new window

0
 
dschauhan82Connect With a Mentor Commented:
http://www.codeproject.com/kb/webservices/aspwebsvr.aspx

Please check this , Hope it will help u
0
 
dschauhan82Commented:
//the URL is on the application
string strURL = this.txtURL.Text;
//go find the raw XML
this.openFileDialog1.Filter = "XML files (*.xml) | *.xml";
this.openFileDialog1.ShowDialog();

//load the XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(this.openFileDialog1.FileName.ToString ());
//Create the Web request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(strURL);

//set the properties
request.Method = "POST";
request.ContentType = "text/xml" ;
request.Timeout = 30 * 1000;
//open the pipe?
Stream request_stream = request.GetRequestStream();
//write the XML to the open pipe (e.g. stream)
xmlDoc.Save(request_stream);
//CLOSE THE PIPE !!! Very important or next step will time out!!!!
request_stream.Close();

//get the response from the webservice
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream r_stream = response.GetResponseStream();
//convert it
StreamReader response_stream = new
StreamReader(r_stream,System.Text.Encoding.GetEnco ding("utf-8"));
string sOutput =response_stream.ReadToEnd();

//display it
this.txtAbstract.Text = sOutput;
MessageBox.Show(sOutput);

//clean up!
response_stream.Close();

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Rajkumar GsSoftware EngineerAuthor Commented:
Thanks dschauhan82 for your help!

I have tried this code and getting the same error messsage - "The remote server returned an error: (500) Internal Server Error."

As I mentioned in question, the tool soapUI tool displays the exact error message.
Can you please tell why the exact error response message is not displaying in your code & mine...!?

Thanks again
Raj
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
I used soapUI tool ( http://www.soapui.org/ ) to send XML to a webservice. This tool shows the repsonse from Webservice.

But when I tried the code ( http:#33594986 ), it is showing another error instead of showing the response from Webservice.

(Please open the attached screenshot)

What's I am doing wrong here ?

Thanks
Raj
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
How can I send XML to a Webservice and receive the response from Webservice in Asp.Net application using C# code ?

Raj
0
 
alexey_gusevCommented:
have you 'escaped' all special characters like "<" and ">" ? you should replace them by ">" etc.
0
 
alexey_gusevCommented:
oops, the last ">" should read "semicolon & gt" - replace words by appropriate character and remove spaces
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Thanks for your comment, alexey.

I have n't anything regarding handling special characters. - actually i was not aware about that.
Could you please post the C# code regarding the same ?

Regards
Raj
0
 
alexey_gusevCommented:
it is just as simple as the following snippet. I'm not 100% sure it resolves your problems, but it's worth a try


str = str.Replace(">","&gt;").Replace("<","&lt;");

Open in new window

0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Attached one was the code I used to post XML to web service.

I modified these lines

        // XML File
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(sourceXMLFile);
        byte[] postBytes = encoding.GetBytes(xmlDoc.InnerXml.ToString());

to

        // XML File
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(sourceXMLFile);
        string XMLFileContents = "";
        XMLFileContents = xmlDoc.InnerXml.ToString();
        XMLFileContents = XMLFileContents.Replace(">", ">").Replace("<", "<");
        byte[] postBytes = encoding.GetBytes(XMLFileContents);

and tried as per your suggestion. Still getting the same error message.

Raj
public string PostXMLtoWebService(string sourceXMLFile)
    {
        // Webservice
        HttpWebRequest hwrRequest = (HttpWebRequest)HttpWebRequest.Create("http://acpt2-newmenu.workspeed.com/webservice/services/MessageService");
        hwrRequest.Method = "POST";
        hwrRequest.ContentType = "text/xml";
        UTF8Encoding encoding = new UTF8Encoding();

        // XML File
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(sourceXMLFile);
        byte[] postBytes = encoding.GetBytes(xmlDoc.InnerXml.ToString());

        hwrRequest.ContentLength = postBytes.Length;


        Stream postStream = hwrRequest.GetRequestStream();
        postStream.Write(postBytes, 0, postBytes.Length);
        postStream.Close();

        HttpWebResponse hwrResponse = (HttpWebResponse)hwrRequest.GetResponse();
        Stream responseStream = hwrResponse.GetResponseStream();
        XmlTextReader xtrSmp = new XmlTextReader(responseStream);

        string strXm = xtrSmp.ReadInnerXml();
        xtrSmp.Close();
        hwrResponse.Close();

        return strXm;
    }

Open in new window

0
 
Rajkumar GsSoftware EngineerAuthor Commented:
If I am right, If there is anything wrong with the input XML to Webservice, we should get the proper error response from webservice in XML format. (See attached error response I got from webservice, when passed invalid values in XML file using soapUI tool)

But in this case, some other crash seems to be happening.

Is the code is right intended to post XML to a webservice ? Any alternative method using C# code ?

Thanks
Raj
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server</faultcode>
         <faultstring>| UPDATEENTITY: NO ENTITY FOUND FOR EXTERNAL_ENTITY_ID = 222</faultstring>
         <faultactor/>
         <detail/>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

Open in new window

0
 
alexey_gusevCommented:
ok, what I don't understand - in the string after Replace().Replace() - do you have any special xml characters?
(see http://xml.silmaril.ie/authors/specials/   for details)

what happens when you send some arbitrary string instead of xml?
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
I have attached the XML file that I used.
I have renamed some relevant portions (text only), which is private to our company

Thanks
Raj
myXML.xml
0
 
alexey_gusevCommented:
hmm, I don't think it is anything to do with xml. I've tried sending plain text with the same exact result.

can you debug it at web service side? what language was it developed in? from the url in your code it doesn't seem to be a webservice at all :)

in general, you'd like to add a web reference or service reference (depending on the VS version), so then VS builds a wrapper for you and does all 'black jobs' for you in terms of serializing objects
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
When I passed a string 'test' instead of XML - same error message :(

Raj
0
 
alexey_gusevCommented:
so what about debugging the web service (or whatever it is)? you should be able to put a breakpoint and see what happens.

right now it looks like you have some virtual folder on your webserver, and when one access it the default script is executed and writes back to http response stream :)
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Webservice is not ours. It is the webservice provided by client. So no scope with debugging webservice :)

Raj

0
 
Rajkumar GsSoftware EngineerAuthor Commented:
I tried it in a different way. Instead of posting XML with the code I posted before, tried to use their class. (See attachment)

Only this object is available in their webservice class now, where we need to pass I think XML.
( message.process(object process1)  )

When I tried this way

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sourceXMLFile);

com.abc.acpt2_newmenu.MessageServiceService message = new com.abc.acpt2_newmenu.MessageServiceService();
message.process(xmlDoc.InnerXml);

Error is - "java.io.IOException: Unknown 'process' element found in body of SOAP message"

When I tried like
message.process(xmlDoc);
Error message is
"There was an error generating the XML document."


Any idea ?
Raj
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Sorry. missed the attachment.

Raj
SendXMLCode.JPG
0
 
alexey_gusevCommented:
ahh, that's what I was looking for ;) - so it is java ws, and it does give you a wrapper class.

try simple text string as a parameter - and you need to read their docs to see what's expected in MessageServiceService.process() method

In general, if you're fancy connecting to web service over raw HTTP then you MUST build all SOAP enveloping stuff manually, it's not just HTTP POST :)

But I'm sure you have the wrapper (MessageServiceService class) and can use it with proper parameter
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Yes. I think we are more close to the right way :)

I will ask client what type of parameter, we need to pass. Now simply, it is 'object process1' - which is confusing. I tried those ways that I mentioned in previous comment - http:#33625435

Thanks
Raj
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
We asked client about the error regarding sending XML over HTTP POST. We are having a VBScript file that was sent by them previously, which they successfully tested over their webservice.

Regarding our query, client replied with a doubt that we may have missed this setting
objXmlHTTP.setRequestHeader "SOAPAction:" , serviceUrl
in our C# code. (Please see the attached vbs file)

Cheers
Raj
SendSOAPtoACPT.vbs
0
 
alexey_gusevConnect With a Mentor Commented:
yes, your client is correct, "SOAPAction" should be added as this is what was returned from my simple test html form, but pay attention they used XMLHTTP object. For some example see eg here

http://stackoverflow.com/questions/189934/whats-the-equivalent-of-xmlhttp-from-vb6-in-c-net-2005
0
 
alexey_gusevCommented:
excellent :) , so all encoding/decoding is done in XMLHTTP
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
dschauhan82,

The link you provided in your first comment - http:#33594977 - have the right code which in javascript, which need converting to C#. But I was behind your second comment - http:#33594986 - as it is C#, I thought it will work with some modification.

Thanks for your help
Raj

0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Hi Alexey &  dschauhan82,
Thanks you guys for your help.

I think it is better to accept my comment as the 'Accepted Solution' (0 points) and yours as 'Assisted Solution', only because for any one who search in future in EE for similar issue - "How to send an XML to a Webservice in C#' - would first get into the comment having right code and description.

As you both provided me the same solution, I think it is justice to split points to you both.

Cheers
Raj
0
 
alexey_gusevCommented:
no objections from my side :)
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
Thanks alexey. Hope dschauhan82 also :) But I cannot close this question - Error message "Each point split must be at least 20 points" Points I assigned for each split is much far above 20 points!    Requesting Admin Attention...    Raj
0
 
alexey_gusevCommented:
I guess you should assign points to your own answer too
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
For my comments, there is no option to assign points. For other expert's comments only have option to select and assign points.

Normally asker's solution will be assigned 0 points.

Raj
0
 
Rajkumar GsSoftware EngineerAuthor Commented:
0
 
DerAdler82Commented:
Hi, I've got a question for RajkumarGS or anybody that can help me.

I'm handling a similar scenario (using Visual C# 2010): I should send an XML file to a WebService.
The solution in the post  33634709 seems to be really close to my needs.
I just need to understand how to refer to a specific method of the Web Service, to which send the XML file.

To define the Service URL in the code above, RajkumarGS wrote:
string serviceUrl = "http://acpt2-newmenu.workspeed.com/webservice/services/MessageService";

Open in new window

In my case, the Web Service URL includes the .asmx extension; then something like:
http://site.somewhere.com/PWSName/PSName.asmx

There're two different methods that could be called to pass the XML file (eg. MethodName1 and MethodName2).
I tried to edit the ServiceUrl with something like:
string serviceUrl = "http://site.somewhere.com/PWSName/PSName.asmx?op=MethodName1";

Open in new window

but I got a fault error:
<faultcode>soap:Client</faultcode>
  <faultstring>System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://site.somewhere.com/PWSName/PSName.asmx?op=MethodName1 ... </faultstring>

So, the question is: how do I adapt the RajkumarGS code (if possible) to achieve this, or how it is supposed to be done. I'm quite new to Web Service etc, so I'm looking for an easy way to perform it.
Any code examples are really welcome and would be appreciated.
Remember, I'm using the Visual C# environment (but if you got any easier way, like stand-alone scripts, please don't hesitate to post it!)
0
All Courses

From novice to tech pro — start learning today.