代码演练
第一个 Web 服务被称为 GeoPhone。以下就是具体方法:
private void btnFindPerson_Click(object sender,
System.EventArgs e)
{
// Instantiate Web Service
GeoPhone geoPhone = new GeoPhone();
// Reset all controls to default
resetControls();
// Show wait cursor
Cursor.Current = Cursors.WaitCursor;
try
{
// Check that server is available over HTTP
(port 80)
if(CheckConnection.Once(geoPhone.Url))
{
// Get address
Contact Person =
geoPhone.GetPhoneInfo(txtPhoneNumber.Text,"0").Contacts[0];
// Display address
txtName.Text = Person.Name;
txtAddress.Text = Person.Address;
txtCity.Text = Person.City;
txtState.Text = Person.State;
txtZip.Text = Person.Zip;
this.btnYellowPages.Enabled = true;
}
else
{
// No connection!
MessageBox.Show("Connection to Web Service
server could not be established!");
}
}
catch (Exception ex)
{
// Disable Save As Contact button
this.btnYellowPages.Enabled = false;
MessageBox.Show("Could not make Web Service calls
(" + ex.Message + ")!");
}
finally
{
// Restore default cursor
Cursor.Current = Cursors.Default;
}
}
在调用 Web 服务之前,首先验证服务器是否可用非常重要。在用户等待响应时,光标设置为沙漏。
在返回响应后,用户可以点击“Find Hotel & Restaurants”来查找附近的旅馆和餐馆。使用以下代码来调用 YellowPages Web 服务:
private void btnFindBusiness_Click(object sender,
System.EventArgs e)
{
DOTSYellowPages YP = new DOTSYellowPages();
Listings HotelListings = new Listings();
Listings RestaurantListings = new Listings();
// Show wait cursor
Cursor.Current = Cursors.WaitCursor;
try
{
// Check that server is available over HTTP (port
80)
if(CheckConnection.Once(YP.Url))
{
// Get hotels
HotelListings = YP.GetYPListingsByCategoryID(1279, YPZip, int.Parse(txtMiles.Text), "0");
// Get restaurants
RestaurantListings = YP.GetYPListingsByCategoryID(655, YPZip, int.Parse(txtMiles.Text), "0");
// Clear treeview
tvwBusiness.Nodes.Clear();
// Call to fill the treeview with hotels
FillTreeView(HotelListings);
// Call to fill the treeview with
restaurants
FillTreeView(RestaurantListings);
}
else
{
// No connection!
MessageBox.Show("Connection to Web Service
server could not be established!");
}
}
catch (Exception ex)
{
MessageBox.Show("Could not make Web Service calls
(" + ex.Message + ")!");
}
finally
{
// Restore default cursor
Cursor.Current = Cursors.Default;
}
}
可以在以下网址找到 YellowPages WSDL:http://ws2.serviceobjects.net/yp/YellowPages.asmx?WSDL