A day with .Net

My day to day experince in .net

Call XML webservice through c#.net

Posted by vivekcek on July 21, 2009

I am working in a project for online reesrvation of airlines,Hotels etc in asp.net.Online reservation is by XML webservices

beacause XML is the language independent information exchange language.So i developed a common application to send XML

request to webservice and getting response from them and populte the result in a grid view.
The application includes two text boxes one for inputing XML one to show out put XML from webservice.
The UI and code for the same is given below
XML tester

In the coding section first line shows the declration of web service URL as

static Uri Url = new Uri(“https://example.com/exampleapi/RequestListenerServlet”);

In the submit button click event

we format the xml string entered in the input test box and convert it int an XML document


XmlElement _xmlResponse =ResponseListElement(doc);

In the above code we call the function for sending our formated xml document to webservice and return an xml result

ResponseListElement()

Then we load the result XML into a dataset and shows in gridview

using GTAApp;
using System.IO;
using System.Net;
//using System.Web.Services.Protocols;
using System.Diagnostics;
using System.IO.Compression;

using System.Data.SqlClient;
using System.Xml;

namespace MyApp
{
    public partial class XMLtesterGta : Form
    {
        static Uri Url = new Uri("https://example.com/exampleapi/RequestListenerServlet");
        
        public XMLtesterGta()
        {
            InitializeComponent();
        }
        
        DataSet ds;
        private void ccBtnSubmit_Click(object sender, EventArgs e)
        {
            string unformattedXml = ccTxtInput.Text;
            string formattedXML = IndentXMLString(unformattedXml);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(formattedXML);
            
            XmlElement _xmlResponse =ResponseListElement(doc);
            if (_xmlResponse != null)
            {
                string formattedXML1 = IndentXMLString(_xmlResponse.OuterXml);
                ccTxtOutput.Text = formattedXML1;
                ds = new DataSet();

                byte[] reqData = Encoding.ASCII.GetBytes(_xmlResponse.OuterXml);
                System.IO.MemoryStream m = new System.IO.MemoryStream(reqData);
                ds.ReadXml(m);
                foreach (DataTable dt in ds.Tables)
                {
                    ccDdlTables.Items.Add(dt.TableName.ToString());

                }
            }

        }
        private static string IndentXMLString(string xml)
      {
         string outXml = string.Empty;
         MemoryStream ms = new MemoryStream();
         // Create a XMLTextWriter that will send its output to a memory stream (file)
         XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode);
         XmlDocument doc = new XmlDocument();

         try
         {
            // Load the unformatted XML text string into an instance 
            // of the XML Document Object Model (DOM)
            doc.LoadXml(xml);

            // Set the formatting property of the XML Text Writer to indented
            // the text writer is where the indenting will be performed
            xtw.Formatting = Formatting.Indented;

            // write dom xml to the xmltextwriter
            doc.WriteContentTo(xtw);
            // Flush the contents of the text writer
            // to the memory stream, which is simply a memory file
            xtw.Flush();

            // set to start of the memory stream (file)
            ms.Seek(0, SeekOrigin.Begin);
            // create a reader to read the contents of 
            // the memory stream (file)
            StreamReader sr = new StreamReader(ms);
            // return the formatted string to caller
            return sr.ReadToEnd();
         }
         catch (Exception ex)
         {
            MessageBox.Show(ex.ToString());
            return string.Empty;
         }
      }

        private void ccDdlTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            ccGdTables.DataSource=ds.Tables[ccDdlTables.SelectedItem.ToString()];
        }
        public XmlElement ResponseListElement(XmlDocument xDocs)
        {
            try
            {
                byte[] reqData = Encoding.ASCII.GetBytes(xDocs.OuterXml);
                System.IO.Stream st = null;

                // Send Request
                HttpWebRequest httpWR = (HttpWebRequest)HttpWebRequest.Create(Url);
                //httpWR.Timeout = 6000;
                //httpWR.ReadWriteTimeout = 8000;
                httpWR.Method = "POST";
                httpWR.ContentType = "text/xml";
                httpWR.ContentLength = reqData.Length;
                httpWR.GetRequestStream().Write(reqData, 0, reqData.Length);

                //Receive Response
                st = httpWR.GetResponse().GetResponseStream();

                StringBuilder sbResponse = new StringBuilder();
                int numBytesToRead = 1024;
                byte[] resData = new byte[numBytesToRead];

                while (true)
                {
                    int n = st.Read(resData, 0, numBytesToRead);
                    if (n == 0) break;

                    sbResponse.Append(Encoding.ASCII.GetString(resData, 0, n));
                }

                XmlDocument ret = new XmlDocument();
                ret.LoadXml(sbResponse.ToString());
                return ret.DocumentElement;
            }
            catch (WebException wEx)
            {
                MessageBox.Show(wEx.Message.ToString());
                //long len = wEx.Response.GetResponseStream().Length;
                //byte[] exMsg = new byte[len];
                //wEx.Response.GetResponseStream().Read(exMsg, 0, (int)len);

                //Debug.Assert(false, Encoding.ASCII.GetString(exMsg));
            }
            return null;
        }

        private void ccBtnClear_Click(object sender, EventArgs e)
        {
            ccTxtInput.Clear();
            ccTxtOutput.Clear();
            ccDdlTables.Items.Clear();
            ds.Clear();
            ccDdlTables.SelectedText = "";
        }
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s