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

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

.pdf
Скачиваний:
75
Добавлен:
16.08.2013
Размер:
20.33 Mб
Скачать

Chapter 12

{

....

}

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/frlrfsystemwebserviceswebmethodattribute memberstopic.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, the Wrox United application doesn’t provide weather forecasting, so you borrowed someone else’s service. What happens, though, if you want to create your own web service?

In the past, creating a web service wasn’t always as easy as it should have 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 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 solution (C:\BegASPNET2\Chapters\Begin\Chapter12) open, go to Solution Explorer and select the top line, which reads C:\... \Chapter12. Right-click it and select Add New Item.

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

438

Web Services

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.cs, as shown in Figure 12-8.

Figure 12-8

439

Chapter 12

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

using System; using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols; using System.Data;

using System.Data.SqlClient; using System.Configuration;

5.Remove the lines from [WebMethod] to } (because this is just a default test web service), and replace it with the following code:

[WebMethod]

public DataSet Fixtures()

{

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“WroxUnited”].ConnectionString );

SqlDataAdapter adapter = new SqlDataAdapter(“SELECT FixtureDate, Opponents, FixtureType, GoalsFor, GoalsAgainst FROM Fixtures ORDER BY FixtureDate”, conn);

DataSet ds = new DataSet();

adapter.Fill(ds, “Fixtures”);

return ds;

}

}

6.Change the namespace attribute at the top of the class to the following:

[WebService(Namespace=”http://wroxunited.net/”)]

7.Save this file.

How It Works

Inside your [WebMethod] declaration, you have a simple functionthat creates a connection using the connection string, and then creates a SqlDataAdapter and passes it the SQL to query the fixtures table:

public DataSet Fixtures()

{

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“WroxUnited”].ConnectionString );

SqlDataAdapter adapter = new SqlDataAdapter(“SELECT FixtureDate, Opponents, FixtureType, GoalsFor, GoalsAgainst FROM Fixtures ORDER BY FixtureDate”, conn);

DataSet ds = new DataSet();

adapter.Fill(ds, “Fixtures”);

return ds;

}

440

Web Services

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 a couple of namespaces. This is 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 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

You’ve created your web service and taken a look at its structure, but you haven’t actually done anything with it yet or tested it. Fortunately you already have tools at your disposal to test the web service. Being able to browse to the endpoint of your service enables you to try the web service out.

Try It Out

Testing the Fixtures Web Service

1.When you created FixtureService.cs and placed it in the App_Code folder, it automatically created an endpoint (.asmx file) for you. Go to Solution Explorer and select Fixture Service.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 the one displayed in Figure 12-10. From here you can test your service. Note that the service doesn’t require any input.

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

441

Chapter 12

Figure 12-10

Figure 12-11

442

Web Services

How It Works

You can see that the test has returned the fixtures and results of Wrox United’s matches within the XML. 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.cs 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, which contains 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 0, 1, or 20 parameters, and defines how many you expect back. It can also specify that when, for example, a web service expects two specific parameters and returns a single

443

Chapter 12

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. 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 commandline prompt. You shouldn’t need to drop down to a 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.

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 brief look at the two technologies underlying web service discovery.

444

Web Services

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. Following the closure of Microsoft’s UDDI registry (formerly at http:// uddi.microsoft.com), the main one is IBM’s www-3.ibm.com/services/uddi/. The registries 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 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 URL 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. More often than not, you’ll probably just want to make use of a web service at a local level, within your application. 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. You will see the screen shown in Figure 12-13.

445

Chapter 12

Figure 12-13

2.From here you can either browse to web services in your local application or on the local machine. You have already created a web service, so click Web Services in This Solution to arrive at the screen displayed in Figure 12-14.

Figure 12-14

3.Only one web service should be in the solution so far, because you’ve only created one. Click the FixtureService link and you should be able to see a view of the web service .asmx file (see Figure 12-15).

446

Web Services

Figure 12-15

4.Click Add Reference. In Solution Explorer, you should see a folder called App_WebReferences, and underneath this folder, another folder, localhost, which contains three files, as shown in Figure 12-16.

Figure 12-16

How It Works

You created the .disco and .wsdl files in this Try It Out automatically. The process of adding a web reference involved selecting a web service (there was only one to select) and adding a reference. The reference then appeared in the App_WebReferences folder. The .wsdl and .disco files were created at the same time. This means can access the web service from within your code. This is the ultimate point of your web service and you’re almost there now.

Adding the Fixture Ser vice to Your

Application

The web service now exists as an object within your code that you can access and query the methods of, just like you would with any normal object. In fact, to your application, for all intents and purposes this is a local object. There is a sleight-of-hand going on here. What .NET Framework has done for you is to create a proxy object. This object acts like the web service and calls the methods on your behalf and actually passes the details to the web service.

447