Click here to Skip to main content
15,867,911 members
Articles / Web Development / ASP.NET
Tip/Trick

Web Service communication

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
9 Sep 2013CPOL2 min read 16.2K   2   10   4
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. 
C#
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.

C#
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.

C#
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. 

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) Applexus Technologies
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionI have values as follow, but it doesn't displaying any values. Pin
Manoj Prabhu T2-Dec-14 0:49
Manoj Prabhu T2-Dec-14 0:49 
QuestionAuthenticated Pin
Cristiano F. Moura9-Sep-13 5:00
Cristiano F. Moura9-Sep-13 5:00 
AnswerRe: Authenticated Pin
Praveen Maniyath9-Sep-13 5:13
Praveen Maniyath9-Sep-13 5:13 
AnswerRe: Authenticated Pin
Cristiano F. Moura9-Sep-13 7:13
Cristiano F. Moura9-Sep-13 7:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.