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

Beginning ASP.NET 2

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

Web Services

Namespaces

As with the rest of ASP.NET, occasionally you will need to specify other namespaces so that you can appropriate other classes and functions within your own web service. These namespaces are defined after the @WebService attribute in the file. In ASP.NET 1.x you had to import three namespaces as a minimum; in ASP.NET 2.0 you still have three to import, but they are slightly different ones:

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

These web services are required as an absolute minimum, because they contain classes needed for web services to handle network connection issues and other related tasks.

Public Class

The class is simply a container for the web service, and the name of the class signifies the name of the web service:

Public Class FixturesService

Inherits System.Web.Services.WebService

...

End Class

The class name needs to correspond with the Class attribute that is specified within the processing directive. Then for all other intents and purposes, it is just a normal object, albeit one that is exposed to the Web. The trick with our web server, though, is that any calls to the object will look like they came from the same machine, and not via a foreign source.

Web Methods

To signify that a particular method (or property) is callable via the Web, you need to add a <WebMethod> declaration. In ASP.NET 1.x, you could only expose methods to the Web, but in ASP.NET 2.0 you can also expose properties as well.

The <WebMethod> declaration is really the part that does all of the legwork. You can define one or more web methods, and not only that, you can make sure some web methods are publicly accessible, whereas others can have access to them restricted via the protected keyword. Though the syntax does vary slightly between VB.NET and C# (VB.NET uses greater-than and less-than symbols, whereas C# uses square brackets to define the method call), they are both recognizably similar.

The syntax in VB.NET is as follows:

<WebMethod()> _

Public Function Hello (ByVal strName As String) As String

....

End Function

This defines a web method that accepts a string as a parameter and returns a string as a result, just like a normal function.

439

Chapter 12

The syntax in C# is as follows:

[WebMethod]

public string Hello (string strName)

{

....

}

This also defines a web method that accepts a string as a parameter and returns a string as a result. If you don’t want to expose a particular web method to the public, you simply remove the declaration.

Web methods also take parameters of their own. You can set the different attributes to modify the behavior of the web service. This allows you to customize the web service in several ways. For instance you can use the CacheDuration attribute to specify the number of seconds for which you want the WebMethod declaration to cache its results. When a consumer browses to the web service inside this allotted period, instead of the web service going back to retrieve the result, it gets a cached copy of the results instead.

In VB.NET you can specify an attribute as follows:

<WebMethod(CacheDuration:=60)> _

Public Function Hello (ByVal strName As String) As String

....

End Function

In C# you can specify an attribute as follows:

[WebMethod(CacheDuration=60)] public string Hello (string strName)

{

....

}

You can specify multiple attributes by separating them with commas. The Description attribute allows you to specify a little detail about your web method, which can help potential consumers identify whether or not they want to use it.

In VB.NET you can specify multiple attributes as follows:

<WebMethod(Description:=”A web service that says hello to you”, _ CacheDuration:=60)> _

Public Function Hello (ByVal strName As String) As String

....

End Function

In C# you can specify multiple attributes as follows:

[WebMethod(Description=”A web service that says hello to you”,CacheDuration=60)] public string Hello (string strName)

{

....

}

440

Web Services

You can see the effect of adding a description to a web method in Figure 12-6. The text is displayed next to the web service so that in a list of web services, you would be able to differentiate between each one.

Figure 12-6

For more information on WebMethod attributes, go to http://msdn.microsoft.com/library/

default.asp?url=/library/en-us/cpref/html/ frlrfsystemwebserviceswebmethodattributememberstopic.asp.

Creating a Web Service

So far you’ve consumed a third-party web service and seen how you can send and receive responses via a standard interface provided from the .asmx endpoint. However, it isn’t the .asmx file that is the web service, it just points you in the direction of the web service. As stated earlier, we didn’t have the capability to provide weather forecasting in the Wrox United application, so we borrowed someone else’s service. What happens, though, if you want to create your own web service?

Creating a web service in the past hasn’t always been as easy as it should’ve been. If you created ASP.NET 1.x pages with Notepad, you would find yourself delving around the murky world of the command prompt to compile the service, and having to create an application by hand with which to consume the service. Here you’re only going to worry about the first two stages of the life cycle, creating a web service with which you can call and transmit the data.

In this Try It Out you create an example web service that is able to return the list of results and fixtures from the Wrox United web site.

Try It Out

The Fixtures Web Service

1.With the Chapter12\WroxUnited solution (C:\BegASPNET2\Chapters\Begin\ Chapter12\WroxUnited) open go to Solution Explorer and select the top line, which reads C:\...\WroxUnited. Right-click it and select Add New Item.

2.A new dialog appears. In this dialog make sure that the Language is set to Visual Basic. Type in the name FixtureService.asmx, select the Web Service option, and click Add, as shown in Figure 12-7.

441

Chapter 12

Figure 12-7

3.This creates a template web service from which to work. If it doesn’t appear automatically, go to the App_Code folder in Solution Explorer and click FixtureService.vb, which will now have appeared, as shown in Figure 12-8.

Figure 12-8

442

Web Services

4.Add the following lines to the list of namespaces at the top of the page:

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports System.Data

Imports System.Data.SqlClient

5.Remove the lines from <WebMethod())> to End Class (because this is just a default test web service), and replace it with the following code:

<WebMethod()> _

Public Function Fixtures() As DataSet

Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings(“WroxUnited”).ConnectionString

)

Dim adapter As New SqlDataAdapter(“SELECT FixtureDate, Opponents, FixtureType, GoalsFor, GoalsAgainst FROM Fixtures ORDER BY FixtureDate”, conn)

Dim ds As New DataSet()

adapter.Fill(ds, “Fixtures”)

Return ds

End Function

End Class

6.Next, change the namespace attribute at the top of the page to the following:

<WebService(Namespace:=”http://wroxunited.net/”)> _

7.Finally, save this file.

How It Works

Inside your WebMethod() declaration you have a simple function, which creates a connection using the connection string, then creates a SQLDataAdapter and passes it the SQL to query the fixtures table:

Public Function Fixtures() As DataSet Dim conn As New

SqlConnection(ConfigurationManager.ConnectionStrings(“WroxUnited”).ConnectionString

)

Dim adapter As New SqlDataAdapter(“SELECT FixtureDate, Opponents, FixtureType, GoalsFor, GoalsAgainst FROM Fixtures ORDER BY FixtureDate”, conn)

Dim ds As New DataSet()

adapter.Fill(ds, “Fixtures”)

Return ds

End Function

443

Chapter 12

You create a dataset, and fill this dataset with the contents of the adapter (in other words the result of your query) and then return the dataset as a result. You also had to add in a couple of namespaces because the SqlDataAdapter isn’t accessible by default, and so to use it you have to add System.Data and System.Data.SqlClient to enable you to create a connection and to hook up to your SQL database. You also changed the default namespace from http://tempuri.org (the default namespace provided by Microsoft), to http://www.wroxunited.net, which is the URL of the Wrox United site.

There is absolutely nothing unusual about this function; it’s actually the code that surrounds this function that is important. This is what you look at in the next section.

Testing Your Web Service

So you’ve created your web service and taken a look at its structure, but you haven’t actually done anything with it yet, not even gone as far as testing it. Fortunately you already have tools at your disposal to test the web service. Being able to browse to the endpoint of your service allows you once more to try the web service out.

Try It Out

Testing Our Fixtures Web Service

1.When you created FixtureService.vb and placed it in the App_Code folder, it automatically created an endpoint (.asmx file) for you. Go to Solution Explorer and select FixtureService

.asmx. Right-click it and select View in Browser. You will see something similar to Figure 12-9.

Figure 12-9

2.Click Fixtures, and you will arrive at a screen similar to that displayed in Figure 12-10. From here you can test your service. Note that the service doesn’t require any input.

444

Web Services

Figure 12-10

3.Click Invoke and scroll down the screen until you see the XML depicted in Figure 12-11.

Figure 12-11

445

Chapter 12

How It Works

You can see that the test has returned within the XML the fixtures and results of Wrox United’s matches. The answers supplied are in pure text, so this is something that can be easily passed back and forth across the Web. You started by going to the endpoint of the service and clicking the link. From the testing page you clicked Invoke to produce the web service result in XML. This web service generated a set of fixtures from the class FixtureService.vb and the resulting dataset is rendered as a set of XML elements: <FixtureDate>, <Opponents>, <FixtureType>, <GoalsFor>, and <GoalsAgainst>.

The WSDL Contract

If you go back to the endpoint FixtureService.asmx and browse it again, you’ll find a line with a link reading, “For a formal definition, please review the Service Description.” If you click the Service Description link, you will see the page shown in Figure 12-12, containing the WSDL.

Figure 12-12

This is yet more behind-the-scenes work. WSDL is short for Web Services Description Language and it is an XML file that defines how the interaction between a web service and its consumer will occur. For example, WSDL states whether the web service uses GET, POST, or SOAP. The WSDL document defines whether the web service requires zero, one, or twenty parameters, and defines how many you expect back. It can also

446

Web Services

specify that when, for example, a web service expects two specific parameters and returns a single value, what the names, order, and data types of each input and output value should be. With WSDL all of the information necessary is present to begin using the web service functionality. WSDL is yet another standard managed by W3.org and you can find the standard details at www.w3.org/TR/wsdl.

At the head of the WSDL document is a declaration for the <definitions> element, which contains various namespaces, which make references to SOAP. Next up is the <types> element, which defines each of the data types that the web service expects to receive and return after its completion. The <types> element is written in yet another XML language, XSD (XML Schema Definition Language).

If you want to see a particular definition of a data type, you need to scroll down the screen and expand each node within Internet Explorer.

After the <types> element are various <message>, <port type>, and <binding> elements, which all refer to transmissions between the web service and consumer. The WebMethod message named FixtureService is contained in here, and various SOAP message structures are defined. In short, this file has everything needed to handle communication with your web service. And it was automatically created when you created your .asmx file.

Although you’ve consumed web services by browsing directly to the endpoint (the .asmx file), you haven’t actually tackled how you’d go about including the web service’s functionality within your own program, which is the purpose of the next section.

Web Service Discovery

Perhaps another reason why web services haven’t been as successful as they might have been is that web service discovery has been a rather hit-and-miss affair. If you think back, you’ve created your extravagant rainfall amount cataloguing weather service, now how do you let people know about it? Stick it on your web site and hope the Google spiders will index it sooner rather than later? Stand down at your local shopping center with a placard around your neck? Web service discovery is like the process of locating any item on a search engine. You know roughly what you want to find, you just need to know the URL of where to find it. Web services are the same.

If you are the only person who needs to know about the web service, then it’s a very simple affair; you just add a web reference in Visual Web Developer. When you add the web reference to the web site, it handles not only the process of compiling your web service for you, but also the process of discovering a web service as well. However, you first have to compile the web service. In prior incarnations of ASP.NET, creating a web service was a bit more fiddly than it is in ASP.NET 2.0, and it involved using the command-line prompt. You shouldn’t need to drop down to command prompt, though; instead you can simply use Visual Web Developer’s IntelliSense feature to compile your web services for you.

However, to make it available to a wider range of people, this is inadequate.

447

Chapter 12

Two technologies are used in making web services available. The great thing is that you really don’t need to know too much about either. This is because Visual Web Developer has a feature that makes the discovery of web services very straightforward, the Add Web Reference option. However, before you use it, the next sections take a very brief look at the two technologies underlying web service discovery.

DISCO

DISCO is a colorful name that belies a rather more prosaic abbreviation — discovery. DISCO is a Microsoft technology that is generally used to make web services available on your local machine. To do this you place information about the web service in a .disco document. This is an XML document that contains links to other resources that describe the web service, and can be thought of like an HTML file that contains human-readable documentation or a WSDL file.

Rather than having to worry about creating this yourself, Visual Web Developer takes care of this task for you, when you add a web reference. It creates the .disco file from the .asmx endpoint file and generates a

.DISCOMAP file, both of which are placed in the app_WebReferences folder. These documents can then be used with Visual Web Developer automatically to find your web service.

UDDI

UDDI goes beyond DISCO; it’s like a giant directory of web services, and only four big companies that use web services keep one. The two main ones are Microsoft’s http://uddi.microsoft.com and IBM’s is www-3.ibm.com/services/uddi/. These aren’t just restricted to the companies involved; you can publish your own web service details within these directories. The UDDI directory was intended to work in the same way as a phone directory, with white pages, yellow pages, and green pages. White pages contained the business details, yellow pages contained the classification of the business, and the green pages contained technical information about the web service. Because a lot of web services are created just for the businesses involved and not for general public use, these never took off in the way they were intended to. However, if you create a web service and you do want to market it to the public, or give it away for free, then putting it in a UDDI repository is very simple. Just go to the previously mentioned URLs and follow the registration instructions.

Once again, Visual Web Developer is closely integrated with UDDI, and you can browse different registries when you come to add a web reference to your web site, and add a service to the registry in this way.

Discovering Your Web Service

DISCO and UDDI are both technologies that go on behind the scenes, and though you can make use of both of them, you don’t require any specialist knowledge to do so. In the following Try It Out, you see how you can go about discovering the fixture service that you have just added to your application, by adding a web reference to it.

Try It Out

Adding a Web Reference to Your Application

1.Staying within the WroxUnited web site solution, from Visual Web Developer, select the Web Site Add Web Reference option, and you will see the screen shown in Figure 12-13.

448