Moduler>Webservices>Værobservasjon
Værobservasjoner
Vi lager en vanlig Windows Applikasjon, kopler til webservicen som referanse og skriver følgende kode:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace wapp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PostInitialize();
}
private void PostInitialize()
{
comboBox1.SelectedIndex=0;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// user has selected a country
String CountryName =
comboBox1.Items[comboBox1.SelectedIndex].ToString();
listBox1.Items.Clear();
try
{
String S = globalWeather1.GetCitiesByCountry(CountryName);
// testing and raw output
testBox1.Text = S;
XmlDocument doc = new XmlDocument();
doc.LoadXml(S);
XmlNodeList list = doc.GetElementsByTagName("City");
for (int ix = 0; ix < list.Count; ix++)
{
listBox1.Items.Add(list[ix].InnerText);
}
}
catch (Exception ex)
{
textBox2.Text = ex.Message;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// user has selected a city
String cityName =
(String)listBox1.Items[listBox1.SelectedIndex].ToString();
String CountryName =
comboBox1.Items[comboBox1.SelectedIndex].ToString();
try
{
String S = globalWeather1.GetWeather(cityName, CountryName);
// testing and raw output
testBox1.Text = S;
XmlDocument doc = new XmlDocument();
doc.LoadXml(S);
doc.Normalize();
XmlNode vaeret = doc.GetElementsByTagName("CurrentWeather")[0];
XmlNodeList list = vaeret.ChildNodes;
PresentWeather(list);
}
catch (Exception ex)
{
NoWeatherPresentation();
}
}
private void PresentWeather(XmlNodeList list)
{
String T = "";
for (int ix = 0; ix < list.Count; ix++)
{
String tagName = list[ix].Name;
if(tagName.CompareTo("Location")==0)
{
String tmp = list[ix].InnerText;
int pos = tmp.IndexOf(',');
if (pos != -1)
tmp = tmp.Substring(0, pos);
labelLocation.Text = tmp;
}
else if(tagName.CompareTo("Time")==0)
{
String tmp = list[ix].InnerText;
int pos = tmp.IndexOf('/');
if(pos !=-1)
tmp = tmp.Substring(0,pos);
labelTime.Text = tmp;
}
else
{
T += list[ix].Name;
T += list[ix].InnerText + "\r\n";
}
}
textBox2.Text = T;
}
private void NoWeatherPresentation()
{
labelLocation.Text =
(String)listBox1.Items[listBox1.SelectedIndex].ToString();
labelTime.Text = "";
textBox2.Text = "Finner ikke data";
}
private void button1_Click(object sender, EventArgs e)
{
// toggle display of box with raw text
testBox1.Visible = !testBox1.Visible;
}
private void linkLabel1_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e)
{
// link to service provider
string target = "http://www.webservicex.net/";
try
{
System.Diagnostics.Process.Start(target);
}
catch (System.Exception other)
{
MessageBox.Show(other.Message);
}
}
}
}