Click here to Skip to main content
11,409,450 members (61,031 online)
Click here to Skip to main content

Web Service communication

, 9 Sep 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Praveen Maniyath
Software Developer (Junior) Applexus Technologies
India India
No Biography provided

Comments and Discussions

 
QuestionI have values as follow, but it doesn't displaying any values. PinmemberManoj Prabhu T2-Dec-14 1:49 
QuestionAuthenticated PinmemberCristiano F. Moura9-Sep-13 6:00 
AnswerRe: Authenticated PinmemberPM889-Sep-13 6:13 
AnswerRe: Authenticated PinmemberCristiano F. Moura9-Sep-13 8:13 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.5 | Last Updated 9 Sep 2013
Article Copyright 2013 by Praveen Maniyath
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid