Connect and use a web service in windows phone apps

This article explains how to connect to any web service and use it with a windows phone application. In my example I used this public weather SOAP web service.
For more public open web services: http://www.service-repository.com/

So first we have to add a service reference to the web service.

Now that we have our service reference, we can initialize a new client. Afterwards we can call any web method from this service client.

ServiceReference.WeatherSoapClient client = new ServiceReference.WeatherSoapClient();

All calls from windows phone applications to services are always asynchronous. So the method names will look like ‘GetMethodAsync‘. In the example we’ll use the method GetCityWeatherByZIPAsync with parameter value 18001.

client.GetCityForecastByZIPAsync("18001");

At certain time after calling the method, the data will return. At that point the method completed event will be raised and we have to react to it with an EventHandler. But this handler has to be set up before the call is made.
So you have to put this line of code before the async call.

client.GetCityWeatherByZIPCompleted += new EventHandler<ServiceReference.GetCityWeatherByZIPCompletedEventArgs>(client_GetCityWeatherByZIPCompleted);

The handler method will return the result of the service. That result is in the EventArgs variable e.

void client_GetCityWeatherByZIPCompleted(object sender, ServiceReference.GetCityWeatherByZIPCompletedEventArgs e)
{
      MessageBox.Show(String.Format("Temperature: {0} °F", e.Result.Temperature));
}

Advertisements

Comments are closed.

%d bloggers like this: