Solved

C# code to send an XML to a webservice

Posted on 2010-09-03
35
29,578 Views
Last Modified: 2014-05-28
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

0
Comment
Question by:Rajkumar Gs
  • 19
  • 11
  • 2
  • +1
35 Comments
 
LVL 4

Assisted Solution

by:dschauhan82
dschauhan82 earned 250 total points
ID: 33594977
http://www.codeproject.com/kb/webservices/aspwebsvr.aspx

Please check this , Hope it will help u
0
 
LVL 4

Expert Comment

by:dschauhan82
ID: 33594986
//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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33609436
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33624347
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33624352
How can I send XML to a Webservice and receive the response from Webservice in Asp.Net application using C# code ?

Raj
0
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33624606
have you 'escaped' all special characters like "<" and ">" ? you should replace them by ">" etc.
0
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33624616
oops, the last ">" should read "semicolon & gt" - replace words by appropriate character and remove spaces
0
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625052
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
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33625078
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625120
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625138
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
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33625144
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625190
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
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33625241
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625302
When I passed a string 'test' instead of XML - same error message :(

Raj
0
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33625339
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625381
Webservice is not ours. It is the webservice provided by client. So no scope with debugging webservice :)

Raj

0
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625435
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625446
Sorry. missed the attachment.

Raj
SendXMLCode.JPG
0
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33625475
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33625543
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33633822
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
 
LVL 24

Assisted Solution

by:alexey_gusev
alexey_gusev earned 250 total points
ID: 33634221
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
 
LVL 23

Accepted Solution

by:
Rajkumar Gs earned 0 total points
ID: 33634709
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
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33634756
excellent :) , so all encoding/decoding is done in XMLHTTP
0
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33634789
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33634925
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
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33634947
no objections from my side :)
0
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33634971
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
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33634993
I guess you should assign points to your own answer too
0
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33635067
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
 
LVL 23

Author Comment

by:Rajkumar Gs
ID: 33753763
0
 

Expert Comment

by:DerAdler82
ID: 40095493
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

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now