Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 Express Edition - From Novice To Professional (2006)

.pdf
Скачиваний:
387
Добавлен:
17.08.2013
Размер:
21.25 Mб
Скачать

470

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

a progress bar. Of course, you don’t have a progress bar on the form yet to work with, so head back into the form’s design view and drop a progress bar at the bottom of the form, as in Figure 17-12.

Figure 17-12. Add a progress bar to the form.

Name the progress bar downloadProgress and then hit F7 to jump back into the code. Find the ProgressChanged event handler and add a single line of code to it, as shown here:

Private Sub ProgressChanged(ByVal sender As Object, _

ByVal e As DownloadProgressChangedEventArgs)

downloadProgress.Value = e.ProgressPercentage

End Sub

Finally, let’s code up the DownloadComplete() method. What you’ll need to do here is make sure your progress bar shows 100 percent, and then check that the download operation was not cancelled. Assuming it wasn’t, you can call your AddBooksToListBox() and GetBookDetailsFromWebPage() methods to finish the app:

Private Sub DownloadComplete(ByVal sender As Object, _

ByVal e As DownloadStringCompletedEventArgs)

downloadProgress.Value = 100 If Not e.Cancelled Then

Dim newBooksPage As String = e.Result AddBooksToListBox(GetBookDetailsFromWebPage(newBooksPage))

End If

End Sub

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

471

And you’re finished. After the download completes, this event fires and you can grab the downloaded string from the DownloadStringCompletedEventArgs passed into the handler. You can use that string to then call GetBookDetailsFromWebPage() (which you’ll remember returns a MatchCollection), and pass the results straight into AddBooksToListBox() (which you’ll remember expects a MatchCollection).

Run the application now and you’ll see the screen shown in Figure 17-13.

Figure 17-13. Run the application now and you’ll get an updating progress bar while the page downloads on a separate thread.

The app seems to work just as it did before, but behind the scenes you’ve got some key differences. First, your code structure is much better with each operation living in its own method and the click event handler for the button focusing on doing just one thing. Second, and probably more important for your users, is that if the connection to Apress’s website is slow, they’ll get feedback on the status of the download through the progress bar on the form because the download runs asynchronously.

472

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

Using Web Services

Although being able to access the Internet to download and upload stuff from an application is great fun, one of the biggest noises in the industry concerning .NET has to be web services. Prior to web services arriving, the World Wide Web was nothing more than a collection of disparate websites, some interactive, some not, that presented information to humans. Web services changes that, providing a way for people to share functionality as well as data, and at last making it easy for applications to be built from lots of different pieces all over the world.

Whole books have been written about web services and the intricacies of using them— Keith Ballinger’s excellent tome .NET Web Services: Architecture and Implementation with

.NET (Addison-Wesley Professional, 2003) being a prime example—but for our needs they are really very simple. Think of a web service as a class, with methods, that just happens to live on someone else’s machine. Amazon.com, for example, provides web services that you can use to find out about the books they stock, providing you with the means to write applications that use parts of Amazon.com’s code within them.

My good friend Walter Vijaykumar runs a fabulous website called WebserviceX.NET that hosts dozens and dozens of web services for anyone and everyone to use, covering everything from rendering text as Braille to finding numeric converters, and much more. He’s kindly agreed for us to play with his site as we explore web services (thanks, Walter!).

So, let’s get started. Launch a web browser (bet you didn’t see that one coming) and point it at http://www.webservicex.net. After the page loads, you’ll see a site much like that in Figure 17-14.

The site lists the top web services on the left side, and the most recent on the right. At the bottom of the page is a list of categories, so if you were after a service that could convert Celsius to Fahrenheit, for example, you’d click on the Value Manipulation / Unit Converter category. There’s also a search box at the top right of the page. Clicking in this and keying in the word Weather produces the page shown in Figure 17-15.

There are three weather-related web services up at WebserviceX.NET, according to the results. To find out more about the service and get to the single most important page of the entire site, you’d just click one. For example, I clicked on USA Weather Forecast and got the page shown in Figure 17-16.

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

473

Figure 17-14. The WebserviceX.NET home page

Figure 17-15. You can also search for web services.

474

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

Figure 17-16. Clicking on an individual web service takes you to its definition page.

Why is this the most important page in the site? Well, the page shows you three important pieces of information: the web service definition, its location, and a description of the methods.

As I mentioned earlier, you can think of a web service as a class that lives on someone else’s machine. Rather than having to have the source to the class on your own machine, you just need to know where the service lives, what it can do, and where it’s described.

Those three things are what this web page is all about.

WEBSERVICEX.NET AND THE SPIRIT OF EXPRESS

Aside from being useful for us to learn how to work with web services in Visual Basic 2005 Express, Walter’s website really does exemplify everything Microsoft had in mind with the Express products. Here’s a guy that in his spare time loves nothing more than to mess around with .NET code (personally, I prefer smashing Orcs and Trolls in online games), so he decided to set up a website to show off his efforts.

WebserviceX.NET is a collection of numerous web services written in C# that Walter uses not only to keep his coding skills up-to-date for fun, but also to make available to the world to use, for free. His site has become so popular that it gets around a million hits a day, and numerous businesses rely on his web services within their own critical applications.

Who said hobbyist coders can’t make a difference?

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

475

The top of the page is taken up with a scrolling box showing you the Web Service Definition Language (WSDL). WSDL is the XML standard for describing a web service. It describes in excruciating detail every aspect of the web service, including the names of the methods it supports, the data types of any parameters to those methods, and so on. Take a look through it and you’ll see that it’s a pretty big document and quite confusing. The good news is that you don’t have to be a WSDL expert to use a web service; understanding WSDL is something Visual Basic 2005 Express is quite happy doing on its own. If you decide you really want to know more about the WSDL format, you will find there are some great articles about all the deeper aspects of web services in the online help. Knowing that stuff, though, is most important if you intend to create your own web services, something that VB Express can’t do.

The second item on the page is just a single line preceded by the heading WSDL Schema Location. In the case of the USA Weather Forecast web service, that location is http://_www.webservicex.net/WeatherForecast.asmx?WSDL. This innocuous, tiny piece of information is probably the single most important part of the page for you, because it provides the information you’ll need to tell VB Express how to connect to the web service.

The bottom of the page shows the methods on the web service, the methods in the class if you like, that you can call. There are two here: GetWeatherByPlaceName() and GetWeatherByZipCode(). Clicking on either one of them takes you to yet another page, showing you the format of the method call itself, as you can see in Figure 17-17.

Figure 17-17. Clicking on a method on the web service info page shows you detailed information about the method itself.

476

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

Okay, so now you know how to find information about some web services, but how do you use them from VB Express? Well, the whole process is just as simple as working with a regular class. With a project loaded, you right-click on it in the Solution Explorer and choose Add Web Reference from the context menu that appears. You’ll then be taken to a wizard to connect to the web service; this wizard looks like Figure 17-18.

Figure 17-18. Selecting Add Web Reference takes you to the Add Web Reference dialog.

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

477

The first thing you need to do is enter the URL of the web service location. After that’s done, the dialog changes to the one in Figure 17-19.

Figure 17-19. Entering the URL of a web service changes the dialog to show information about it.

All that remains is to enter a name for the class in the text box at the lower right of the dialog, and you’re all set.

At this point, I think it makes sense to do this for real. Let’s write a simple console application for calculating the exchange rate anywhere in the world.

478

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

Try It Out: Calling a Web Service

Start up a new console project and call it ExchangeRate. When the Solution Explorer appears, right-click the name of the project and choose Add Web Reference to display the Add Web Reference dialog.

Enter http://www.webservicex.net/CurrencyConvertor.asmx?WSDL as the URL of the service and click the Go button. The dialog changes to the one you just saw.

In the Web Reference Name dialog box, name the service WebServiceX and click the Add Reference button. The dialog vanishes and your Solution Explorer changes to show that you have a new web service reference in the project, as in Figure 17-20.

Figure 17-20. Adding a web reference causes it to show up in the Solution Explorer.

From this point on, you can write code and treat the web service just as if it were a typical class. Now, what you just did is add a reference to a web service. In real terms, that just creates a new namespace within your project. So if you named the project ExchangeRate, then you’ll find the web service classes in ExchangeRate.WebServiceX. The first thing you need to do then is add an Imports clause to the code to

Module1.vb:

Imports ExchangeRate.WebServiceX

Module Module1

Sub Main()

End Sub

End Module

C H A P T E R 1 7 T H E I N T E R N E T A N D V I S U A L B A S I C

479

Now you’re ready to write code. The CurrencyConvertor service you are going to use has just one method, ConversionRate(). You pass in two enums that the service defines, representing the currency you want to convert from and the currency to convert to, and the method returns the exchange rate. Go ahead and add the code:

Imports ExchangeRate.WebServiceX

Module Module1

Sub Main()

Dim service As New CurrencyConvertor()

Dim rate As Double

rate = service.ConversionRate(Currency.GBP, Currency.USD) Console.WriteLine( _

"The conversion rate from British Pounds to Dollars is {0}", _ rate)

Console.ReadLine()

End Sub

End Module

If you run the program now, you’ll see it display the conversion rate for British pounds to US dollars (Figure 17-21).

Figure 17-21. Run the program, and the web service is used to find the exchange rate.