Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Web Service communication

0.00/5 (No votes)
9 Sep 2013 1  
A SOAP WebService communication sample.

Introduction

This article provide you code to communicate with a web-service using SOAP. 

The article is meant for begginers in web-service communication with Windows Mobile or Windows Phone.

Background

I searched a lot for the web-service  communication with Windows Mobile.Had found many articles for each functionality. So I am trying out combining them and  include the entire functionality in one single project. Here I have used with windows mobile 6.5 , I had tried this in Windows Phone platform also and found it working. 

Using the code

In this project I have used a single form which contains a button ,in its click a web-service to convert the currency is called and the output is notified through the message box.

  1. Web-service  used for currency conversion : http://www.webservicex.net/CurrencyConvertor.asmx  
  2. An XML need to POST to the web-service which contains two currency code field (first one from which currency second  one to which it has to be converted) and the response XML contains the resulting Rate. 
string fCurrency = "USD";
string tCurrency = "AUD";
string pXml = @"<soapenv:Envelope xmlns:soapenv=""http://" + 
  @"schemas.xmlsoap.org/soap/envelope/"" xmlns:web=""http://www.webserviceX.NET/"">" +
            "<soapenv:Header/><soapenv:Body><web:ConversionRate>" +
            "<web:FromCurrency>" + fCurrency + "</web:FromCurrency>" +
            "<web:ToCurrency>" + tCurrency + "</web:ToCurrency>" +
            "</web:ConversionRate></soapenv:Body></soapenv:Envelope>";
ServiceConnection cs = new ServiceConnection();
cs.ServiceCall(pXml);
cs.OnEndResponse += new ServiceConnection.OnServerEndResponse(serviceConnection_OnEndResponse);

The above function builds and XML content the currency code. The class ServiceConnection is used to establish the connection with the webservice.

class ServiceConnection
{
    public string Url = "";
    private string postXml;

    public delegate void OnServerEndResponse(string response, int statusCode);
    public event OnServerEndResponse OnEndResponse;

    public ServiceConnection()
    {
        Url = "http://www.webservicex.net/CurrencyConvertor.asmx";

    }

    public void ServiceCall(string pxml)
    {
        postXml = pxml;
        WebRequest request = WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "text/xml;charset=UTF-8";
        request.ContentLength = pxml.Length;
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
    }

    void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
        Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
        string postData = postXml;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();
        webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
    }

    void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response;
            response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamResponse);
            string Response = streamReader.ReadToEnd();
            streamResponse.Close();
            streamReader.Close();
            response.Close();
            OnEndResponse(Response, Convert.ToInt32(response.StatusCode));
        }
        catch
        { }
    }

}

The delegate function OnServerEndResponse is mapped back when the response is obtained.

void serviceConnection_OnEndResponse(string response, int statusCode)
{
    MessageBox.Show(ParseXml(response));
}

private string ParseXml(string xml)
{
    string rate = "";
    XDocument doc = XDocument.Parse(xml);
    foreach (XElement element in doc.Root.Elements())
        rate = element.Value;
    return rate;
}

The ParseXml function parses the obtained response from the web-service. Since we have only single node from the response not much complicated parsing is required. 

And we will get obtain the converted rate as notification. 

Below is the entire content of the file. 

button1_Click can be mapped to a button in the designer. 

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.IO;

namespace CurrencyConvertor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string fCurrency = "USD";
            string tCurrency = "AUD";
            string pXml = @"<soapenv:Envelope xmlns:soapenv=""http://schemas." + 
               @"xmlsoap.org/soap/envelope/"" xmlns:web=""http://www.webserviceX.NET/"">" +
                        "<soapenv:Header/><soapenv:Body><web:ConversionRate>" +
                        "<web:FromCurrency>" + fCurrency + "</web:FromCurrency>" +
                        "<web:ToCurrency>" + tCurrency + "</web:ToCurrency>" +
                        "</web:ConversionRate></soapenv:Body></soapenv:Envelope>";
            ServiceConnection cs = new ServiceConnection();
            cs.ServiceCall(pXml);
            cs.OnEndResponse += 
              new ServiceConnection.OnServerEndResponse(serviceConnection_OnEndResponse);

        }


        void serviceConnection_OnEndResponse(string response, int statusCode)
        {
            MessageBox.Show(ParseXml(response));
        }

        private string ParseXml(string xml)
        {
            string rate = "";
            XDocument doc = XDocument.Parse(xml);
            foreach (XElement element in doc.Root.Elements())
                rate = element.Value;
            return rate;
        }
    }
}

class ServiceConnection
{
    public string Url = "";
    private string postXml;

    public delegate void OnServerEndResponse(string response, int statusCode);
    public event OnServerEndResponse OnEndResponse;

    public ServiceConnection()
    {
        Url = "http://www.webservicex.net/CurrencyConvertor.asmx";
    }

    public void ServiceCall(string pxml)
    {
        postXml = pxml;
        WebRequest request = WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "text/xml;charset=UTF-8";
        request.ContentLength = pxml.Length;
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
    }

    void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
        Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
        string postData = postXml;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();
        webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
    }

    void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response;
            response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamResponse);
            string Response = streamReader.ReadToEnd();
            streamResponse.Close();
            streamReader.Close();
            response.Close();
            OnEndResponse(Response, Convert.ToInt32(response.StatusCode));
        }
        catch
        { }
    }
}

Points of Interest 

Since this is freely available web-service over the internet we can check the application without any fail. The project file for windows mobile is provided. Either you can copy the code for using for Windows Phone. It is just a beginner level article. Feel free to comment. Thank you.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here