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

Beginning Visual Basic 2005 (2006)

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

Chapter 19

Case XmlNodeType.Text

‘ do we have an address?

If Not addressData Is Nothing Then addressData.Add(reader.Value, elementName)

End If

As you work through the file, you’ll get to this point for each of the elements stored in the Address element. Effectively, by the time you reach </Address>, addressData will contain entries for each value stored against the address in the document.

To detect when you get to the </Address> tag, you need to look for EndElement nodes:

‘ is it the end of an element? Case XmlNodeType.EndElement

When you get one of these, if Name is equal to Address, you know that you have reached </Address>, and this means that addressData should be fully populated. You form a string and add it to the list:

‘ if it is, you should have an entire address stored...

If reader.Name = “Address” Then

‘ try to create a new listview item...

Dim item As String Try

item = addressData(“firstname”) & _ “ “ & addressData(“lastname”)

item &= “ (“ & addressData(“email”) & “)” Catch

End Try

add the item to the list...

lstEmails.Items.Add(item)

reset...

addressData = Nothing End If

You’ll notice that in your Try . . . Catch you won’t do anything if an exception does occur. To keep this example simple, you’re going to ignore any problems that do occur. Specifically, you’ll run into problems if the Address element you’re looking through has subelements missing — for example, you might not always have an e-mail address for each address, as was shown in Figure 19-8.

You then continue the loop. On each iteration of the loop, XmlTextReader.Read will be called, which advances the pointer to the next node. If there are no more nodes in the document, Read returns False, and the loop stops:

End Select

Loop

End Sub

I hope that this example has illustrated the power of XML from a software integration perspective. With very little work, you’ve managed to integrate the Address Book and Address List applications together.

If you want to experiment with this a little, try adding and deleting addresses from the Address Book. You’ll need to close the program to save the changes to AddressBook.xml, but each time you start Address List, you should see the changes you made.

646

Visual Basic 2005 and XML

Summar y

This chapter introduced the concept of XML. XML is a language based on open standards that can be used as a tool for software integration. Within a single organization, XML can be used to transport data across platforms easily. It also allows two organizations to define a common format for data exchange and, because XML is text-based, it can easily be moved around using Internet technologies such as e-mail, the Web, and FTP. XML is based on building up a document constructed of tags and data.

XML is primarily used for integration work to make the tasks of data transportation and exchange easier, and you, as a newcomer to Visual Basic and programming in general, are unlikely to do integration work (as it’s typically done by developers with lots of experience). Nevertheless, this chapter has “dipped your toes in” so to speak, by focusing on using the System.Xml.Serialization.XmlSerializer class to save entire objects to disk (known as serialization). This same object was used to load objects from disk (known as deserialization). You built a fully functional address book application that was able to use an XML file stored on the local computer as its primary source of data.

To round off the chapter and to demonstrate that XML is great for software integration work, you wrote a separate application that was able to load and make sense of the XML document used by the Address Book application.

To summarize, you should:

Have a better understanding of XML and know what it looks like

How to serialize and deserialize XML data into objects

How to manipulate XML data in your applications

How to use the XMLTextReader class to walk through an XML document

Exercises

Exercise 1

Create an XML document that describes a table lamp. You can describe the lamp using a number of different alternatives. You should describe items such as shade, bulbs and base. You can validate your XML at a site such as www.w3schools.com/dom/dom_validate.asp that offers a free validator.

Exercise 2

For exercise 2, you will expand on what you learned in the chapter by investigating how to place comments in an XML file. As a beginner, one of the most important tasks you can learn is how to research and find answers to questions. For this exercise, search the Web using your favorite search engine and try to find the syntax for inserting comments in XML Once you find the answer, test the comment in the same XML validator you used to test Exercise 1.

647

20

Web Ser vices and .NET Remoting

Industry watchers have been predicting for some time that Web Services are going to be the “next big thing” in Internet development. This chapter introduces the concept of Web Services and shows you how to build your own. This chapter also looks at .NET Remoting and offers some guidance for choosing between .NET Remoting and XML Web Services.

In this chapter, you will:

Get an overview of SOAP, the method used to exchange data with Web Services

Build multiple Web Services

Learn how to test the Web Services using the built-in test harness

Build front-end applications that consume Web services

Get an overview and hands-on experience with .NET Remoting

What Is a Web Ser vice?

When you use the Internet, the two things you most likely use it for are sending (and receiving) e-mail and surfing the Web. These two applications are, by far, the most popular uses of the Internet.

Chapter 20

However, from time to time as Internet usage grows, new technologies and applications that have the potential to change forever the way you use the Internet are released. In recent times, Napster was a commercial product that grew from nothing to “ridiculously huge” in a very short space of time. (In fact, the rate of growth of Napster, until the various court decisions that clipped its wings took hold, was far in excess of the rate of growth of the Web itself!) Naturally, its fall from grace was just as fast!

Building upon the success of the World Wide Web as you know it today, Web Services have the potential to be “the next big thing.”

The Web is a great way to share information. However, the problem with the Web as it is today is that to use it you have to be a human. Web sites are built to be read with human eyes and interpreted with the human mind. Web Services, on the other hand, are built to be read and interpreted by computer programs, not by humans. Web services are, in effect, Web sites for computers to use. These Web sites tend to be dynamic in nature, so they don’t contain static unchanging content but can react and adapt to choices and selections. For example, I might want to use a Web Service that accepts a quantity in U.S. dollars and returns the number of equivalent euros.

Why is this a good thing? Well, when building computer systems in a commercial information technology environment, the most costly factor always involved is integrating disparate computer systems. Imagine you have two pieces of software: one used to keep track of stock in your warehouse, the other used to capture customer orders. These two pieces of software were developed by different companies and bought at different times. However, when an order is placed using the second piece of software, that software should be able to tell the warehousing software that a quantity of a particular product has been sold. This may trigger some autonomous action in the warehousing software, such as placing an order to replenish the stock or asking someone to go and pick it off the shelf.

When two pieces of software work together, you call it integration. Integration is rarely easy, and on large installations it often involves hiring teams of consultants and spending thousands of dollars on customwritten integration software.

Without going into too much detail, Web Services make integration far, far easier. By making something that much easier, you inevitably make it far, far cheaper, and that’s why it’s predicted to be the next big thing. Not only will companies who are already integrating have a more cost-effective option than before, but companies will also be able to integrate their computer systems in previously unseen ways. Web Services will also provide opportunities for new businesses wanting to introduce specialized services with relative ease.

The commercial pros and cons of Web Services, together with a discussion of the movers and shakers in this particular space, are beyond the scope of this book. However, if you would like to learn more, take a look at http://msdn.microsoft.com/webservices.

How Does a Web Service Work?

First of all, Web Services are based upon completely open standards that are not tied to any particular platform or any particular company. Part of their attraction is that it doesn’t matter whether you deploy your Web Service on Solaris, Unix, Macintosh, or Windows; anyone will be able to connect to and use

650

Web Services and .NET Remoting

your Web Service. This is the same with normal Web sites; you do not care what platform the Web sites you visit every day actually run on, as long as they work.

Second, the .NET implementation of Web Services is entirely based around a programming paradigm with which developers have been falling in love for years: object orientation. If you’re used to using objects (and by Chapter 20 of this book, you should be!), you’ll have absolutely no problems with Web Services.

The principle behind a Web Service is that you build a class that has methods. However, the traditional method of deployment and instantiation does not apply. Here is what happens traditionally:

A developer builds a class.

That class is installed (copied onto a computer).

A piece of software running on that same computer creates an instance of the class (the “object”).

The piece of software calls a method on the object.

The object does something and returns a value.

The piece of software receives the value and does something with it.

But here is what happens with a Web Service:

A developer builds a class.

That class is copied onto a server computer running a Web server such as Microsoft IIS.

A piece of software running on a different, remote computer (usually located somewhere on the Internet) asks the Web server to run a particular method on the class.

The server creates an instance of the class and calls the method.

The server returns the results of the method to the calling computer.

The piece of software on the remote computer receives the value and does something with it.

You can see that the technique is very similar, but there’s a disconnection between the server that the object is actually installed on and the computer that wants to use the object. In fact, with a Web Service, there is a huge process gulf (namely, the Internet) between the client of the object and the object itself. A solution to handle this disconnection is provided by the standards used by and specifically developed for Web Services.

SOAP

As Web services are, in effect, “Web sites for computers to use,” they’ve been built on the same technology that’s made the World Wide Web so popular — specifically, the Hypertext Transfer Protocol (HTTP) standard that powers all Web servers.

651

Chapter 20

When you’re dealing with “Web sites for people to read,” the client (browser) and server usually exchange a mixture of documents. Hypertext Markup Language (HTML) documents, and their extension technologies like Dynamic HTML and JavaScript, describe the page layout and text on the page, and common image formats like GIF and JPEG are used to exchange images.

However, when you’re dealing with “Web sites for computers to use,” you exchange only one kind of document. These are known as SOAP documents.

SOAP was originally an acronym for Simple Object Access Protocol, but the current standard at W3C has removed this terminology.

When a client application wants to ask the Web Service for some information, such as the current stock level for a product or the status of an order or to get the computer at the end of the connection to do something such as converting currencies or placing an order, the application constructs a SOAP request document. Using HTTP, this document is sent over the Internet to the Web server that powers the Web Service. This document contains all the information that the Web Service needs to determine what has been asked for. As Web Services work on the common object/method paradigm, the request document includes such things the name of the method and any data that should be passed through to the method as parameters.

At the server end, the Web Service receives the SOAP request, deserializes it, and runs the appropriate piece of software. (You’re going to build some of these appropriate pieces of software in this chapter.) During the call, the method generates a SOAP response document that contains the information to be passed back to the caller. Like the request document, this new document is transferred using HTTP through the Web server.

SOAP documents are constructed with XML. This means that if you read a SOAP document, it’ll look very similar to the sort of document that you saw in Chapter 19. However, at the level of Visual Basic, you don’t need to look too hard at the SOAP documents. As you work through the chapter, you’ll see some of the SOAP response documents that come back from the server, but you won’t be seeing any of the request documents.

You know that Web Service technology is not tied to a specific platform, so from a developer’s perspective the value of choosing one platform over another is determined by how transparent this SOAP document construction and transfer work actually is or what is available at the site where development will take place. .NET is very good for both building and using Web Services; you don’t have to go within a hundred yards of a SOAP document. (This is why in this chapter you’re not going to dwell on SOAP too much, even though without SOAP you wouldn’t be able to do anything you can do in this chapter.) On some other platforms that are equally good for building Web Services, you need to jump through a few more hoops to create powerful Web Services.

Obviously, this chapter is concerned with how Web Services work with .NET. But first, have a close look at Figure 20-1, as it provides a simple form of the architecture behind Web Services.

652

Web Services and .NET Remoting

GetCustomerDetails

Object CreateOrder

CheckStockLevel

Supplier’s Web Server

4

The Web Server packages the stock level into a SOAP response, and sends it back to the customer’s computer.

Methods

The code inside the CheckStockLevel method connects to a database, determines the level and returns the quantity.

3

The Web Service (running on the Web server) receives the SOAP request and passes the request on the object.

Internet

2

5

The customer’s computer receives the SOAP response and passes the stock level onto the customer.

Figure 20-1

The customer needs to check the stock levels of a product with the supplier.

The customer’s application formulates a SOAP request asking for the CheckStockLevel method and

provides a product ID.

1

Customer’s Computer

Building a Web Ser vice

Building Web Services with Visual Studio 2005 is a breeze! In this section, you’ll build a simple Web Service and will be introduced to some of the concepts involved. Specifically, you’ll see how to include the appropriate attributes to expose a method as a Web Service method. You’ll also learn how to test your Web methods using the test harness built into Web Services.

653

Chapter 20

A Web Services Demonstration

A Web Service is basically a class that sits on the server. Some of the methods on that class are marked in a special way, and it’s by looking for these special marks that .NET knows which methods to publish on the service. You’ll see how this works as you go through the first Try It Out in this chapter. Anyone wishing to use the Web Service can then call these methods on the remote Web Service, as if the method existed in a class installed on their local computer. You’ll also see a method that allows us to test the Web Service from within Internet Explorer.

Try It Out

A Demonstration Web Service

1.Open Visual Studio and select File New Web Site from the menu.

2.Make sure Visual Basic is selected in the language box and HTTP in the location box and select ASP.NET Web Service from the upper list. Enter the name as http://DemoService and click OK (see Figure 20-2).

Figure 20-2

Web Services are based on ASP.NET technology, so the project will be created in the same way as the Web applications you worked with in Chapter 17. If you have problems creating the project, look back at that chapter for troubleshooting information.

Visual Studio 2005 will create a new virtual directory and create a new page called Service

.asmx, where .asmx stands for Active Server Methods. (The extra x comes from the original name of ASP.NET: ASP+. The x is the plus sign turned through 45 degrees.) This page represents one service, and a Web Service project (or site) can contain many different services.

3.If the service.vb code-behind page is not open, use the Solution Explorer to open it. Just rightclick Service.asmx and select View Code. When Visual Studio 2005 created the page, it put an example method on the service called HelloWorld. The code looks like the code shown here:

654

Web Services and .NET Remoting

<WebMethod()> _

Public Function HelloWorld() As String

Return “Hello World”

End Function

Run the project by selecting Debug Start Debugging from the menu. You will be asked to either run the project without debugging or add a config file to enable debugging. Choose to create a config file with debugging enabled, and continue. For security reasons, you would turn off debugging before releasing an application into production. The project will be compiled and Internet Explorer will open and display the Service.asmx page. This is the test interface. On this initial page, all of the methods supported by the service appear in a bulleted list at the top of the page.

You will use the web.config file to make numerous changes to your site configuration in the real world. For the purposes of this example, we will not go into detail on this file, but know that you can make sitewide changes to security, caching, custom settings and more. You can learn more about using the web.config file by searching for web.config at http://msdn2.microsoft.com.

4.Click the HelloWorld link. This will open another page that lets you run the method. This page contains the Web method name, a button to invoke the Web method for testing, and the protocols supported for this Web method. Notice that two protocols are listed: SOAP and HTTP POST.

5.Click the Invoke button. This will open another browser window. This window contains the SOAP response from the server, as shown in the following code:

<?xml version=”1.0” encoding=”utf-8” ?>

<string xmlns=”http://tempuri.org/”>Hello World</string>

How It Works

Just as in Web forms you have a class behind the .aspx page, you also have a class behind each .asmx page with Web Services. This class is the one that you enabled the HelloWorld method on. If you look at the definition for the class, you’ll see that it’s inherited from System.Web.Services.WebService:

Public Class Service

Inherits System.Web.Services.WebService

The WebService class is responsible for presenting the pages that you clicked through in Internet Explorer to invoke the HelloWorld method. (You can use another browser to test the service, but Visual Studio 2005 chooses Internet Explorer by default.) These pages are known as the test interface. Methods on the class that you want exposed to the Web Service must be marked with the WebMethod attribute. You can see this attribute defined at the beginning of the method (note that it must be encased in a similar fashion to HTML tags):

<WebMethod()> __

Public Function HelloWorld() As String Return “Hello World”

End Function

Before the test page opens, you are asked to add a config file to enable debugging or continue without debugging. If you plan to test the web service, choose to add a config file. A new file, named web. config, is added to the project. Remember always to disable debugging before releasing your Web

655