There are two broad aspects to web service development: creating the web service and consuming the web service. You'll start by creating a simple web service that provides a simulated stock information service. Your web service will expose two methods: Function GetName(stockSymbol As String) as String Function GetPrice (stockSymbol As String) as Float
Begin by creating a new web site named StockPriceWebService. Be sure to click on ASP.NET Web Service in the templates window, as shown in Figure 14-1. Visual Studio 2005 does a lot of the work of setting up your web service, including adding the necessary <WebService> attributes to your class, and creating a template method (HelloWorld) complete with <WebMethod> attributes. For more on attributes, see the note on attributes in Chapter 12. Figure 14-1. Creating a web serviceYou'll add a two dimensional array of stock symbols with their names and fictional prices, as shown in Example 14-1. Example 14-1. Two-dimensional array of stock symbols and pricesDim stocks As String(,) = _ { _ {"MSFT", "Microsoft", "25.22"}, _ {"DELL", "Dell Computers", "42.12"}, _ {"INTC", "Intel", "25.50"}, _ {"YHOO", "Yahoo!", "30.81"}, _ {"GE", "General Electric", "37.51"}, _ {"IBM", "International Business Machine", "91.98"}, _ {"GM", "General Motors", "64.72"}, _ {"F", "Ford Motor Company", "25.05"} _ } You are now ready to create your two web methods. Web methods are exposed to web clients by tagging them with the <WebMethod> attribute. The first method, GetPrice, takes a symbol as a string and returns the price, as shown in Example 14-2. Example 14-2. GetPrice WebMethod<WebMethod( )> _ Public Function GetPrice(ByVal StockSymbol As String) As Double Dim returnValue As Double = 0 For counter As Integer = 0 To stocks.GetLength(0) - 1 If (String.Compare(StockSymbol, stocks(counter, 0), True) = 0) Then returnValue = Convert.ToDouble(stocks(counter, 2)) End If Next Return returnValue End Function
The GetName method is extremely similar, except that instead of returning a price, it returns the name of the stock, as shown in Example 14-3. Example 14-3. GetName WebMethod<WebMethod( )> _ Public Function GetName(ByVal StockSymbol As String) As String Dim returnValue As String = "Symbol not found." For counter As Integer = 0 To stocks.GetLength(0) - 1 If (String.Compare(StockSymbol, stocks(counter, 0), True) = 0) Then returnValue = stocks(counter, 1) End If Next Return returnValue End Function Notice that Visual Studio 2005 created an .asmx page, but it has only one line in it: <%@ WebService Language="vb" CodeBehind="~/App_Code/Service.vb" %> This determines that the code for the web service will be in the code behind (Service.vb) file. The Class attribute created by Visual Studio 2005 ties this .asmx page to the class defined in Service.vb.
|