Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XML Response From PostAsync()

I am using PostAsync() to send data and the code executes exactly as it should. The site that I send the data to provides an XML response notification informing of a success or a fail. The XML response is like so: A succesful post returns a 1

<?xml version="1.0" encoding="utf-8" ?>
<result>
 <success>1</success>
 <uploadid/>
 </errors>
</result>

while a non-success returns a reason between a <error> tag

<?xml version="1.0" encoding="utf-8" ?>
<result>
 <success>0</success>
 <iploadid/>
 <errors>
    <error>File is not in correct format</error>
 </errors>
</result>

This is my C# syntax that I am using to perform the PostAsync() what do I need to add to read the XML response from the page?

private void SendAsyncData()
{
  string connectionString = "Data Source=hmod;Initial Catalog=salesdb;uid=userid;password=password;MultipleActiveResultSets=True";
  DataTable grds = new DataTable();
  using (var con = new SqlConnection(connectionString))
  using (var cmd = new SqlCommand("procedureone", con))
  using (var da = new SqlDataAdapter(cmd))
  {
    cmd.CommandType = CommandType.StoredProcedure;
    da.Fill(grds);
  }
  var client = new HttpClient();
  var q = string.Empty;
  foreach (DataRow row in grds.Rows)
  {
    var parameterSet = new List<KeyValuePair<string, string>>();
    for (int i = 0; i < grds.Columns.Count; ++i)
    {
        parameterSet.Add(new KeyValuePair<string, string>(grds.Columns[i].ColumnName, row[i].ToString()));

    }

    var result = client.PostAsync("http://weneedsampledata/ashx", new FormUrlEncodedContent(parameterSet)).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
  }
}

EDIT
Currently this syntax returns a code of 200 (success) even if the site receiving the data throws an error, I need a way of "reading" the XML response to determine if the data was actually successful or not. I attempted to add in the below to read the response, but it gives me a compile error of:

'System.Net.Http.HttpResponseMessage' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.Http.HttpResponseMessage' could be found (are you missing a using directive or an assembly reference?)

var response = result.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var postresult = readStream.ReadToEnd();
var xml = System.Xml.Linq.XElement.Parse(postresult);
if (xml.Elements("success").FirstOrDefault().Value == "1")
{
  lblgoodbad.Text = "It was good.";
}
else
{
  var errors = xml.Elements("errors");
  foreach (var error in errors.Elements("error"))
  {
    lblgoodbad.Text = error.Value;
  }
}

EDIT #2
Thanks to the help of @Hussey - I simply made one quick tweak to my syntax and it is functioning as it should. My full syntax reads like such:

    private void SendAsyncData()
{
  string connectionString = "Data Source=hmod;Initial Catalog=salesdb;uid=userid;password=password;MultipleActiveResultSets=True";
  DataTable grds = new DataTable();
  using (var con = new SqlConnection(connectionString))
  using (var cmd = new SqlCommand("procedureone", con))
  using (var da = new SqlDataAdapter(cmd))
  {
    cmd.CommandType = CommandType.StoredProcedure;
    da.Fill(grds);
  }
  var client = new HttpClient();
  var q = string.Empty;
  foreach (DataRow row in grds.Rows)
  {
    var parameterSet = new List<KeyValuePair<string, string>>();
    for (int i = 0; i < grds.Columns.Count; ++i)
    {
        parameterSet.Add(new KeyValuePair<string, string>(grds.Columns[i].ColumnName, row[i].ToString()));

    }

    var result = client.PostAsync("http://weneedsampledata/ashx", new FormUrlEncodedContent(parameterSet)).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
    var xml = System.Xml.Linq.XElement.Parse(resultContent);
    if (xml.Elements("success").FirstOrDefault().Value == "1")
    {
      lblgoodbad.Text = "It was good.";
    }
    else
    {
      var errors = xml.Elements("errors");
      foreach (var error in errors.Elements("error"))
      {
        lblgoodbad.Text = error.Value;
      }
    }
  }
}
like image 345
NadineSmithJonesPicard Avatar asked Nov 08 '22 17:11

NadineSmithJonesPicard


1 Answers

Could you please add this line and try:

After this line:

string resultContent = await result.Content.ReadAsStringAsync();

Add this:

XElement incomingXml = XElement.Parse(resultContent);

Or you can also try this option with ReadAsStreamAsync to read the stream into the XmlDocument:

string resultContent = await result.Content.ReadAsStreamAsync();

XDocument incomingXml = XDocument.Load(resultContent);
like image 158
Husein Avatar answered Nov 14 '22 23:11

Husein