Tuesday, December 27, 2011

Calling a web Service

Many examples on the web are just too complex to actually tweak and get working. Here is a very simple example. You may need to code additional event handlers, network check, etc.. But this will work well. The example checks the current temperature in Phoenix, AZ, USA:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Linq.Expressions;
 
 
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
ListBox mylistbox;
 
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait SupportedPageOrientation.Landscape;
//http://ws.cdyne.com/WeatherWS/Weather.asmx?WSDL
//Uri url = new Uri("http://api.bart.gov/api/stn.aspx?cmd=stns&key=MW9S-E7SL-26DU-VV8V", UriKind.Absolute);
Uri url = new Uri("http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=85020", UriKind.Absolute);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(url);
mylistbox = new ListBox();
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ListBoxItem areaItem = null;
 
StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
string imageName = String.Empty;
string areaName = String.Empty;
string fileName = String.Empty;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "Temperature")
{
//if (true == reader.MoveToFirstAttribute())
//{
//reader.MoveToContent();
areaName = reader.ReadElementContentAsString();
//areaName = reader.Value.ToString();
areaItem = new ListBoxItem();
areaItem.Content = areaName;
//listBox
listBox1.Items.Add(areaItem);
//}
}
}
}
}
}
 
}
}