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

Beginning ASP.NET 2

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

Web Services

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 you click “Browse to web services in this solution” to arrive at the screen displayed in Figure 12-14.

Figure 12-14

449

Chapter 12

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).

Figure 12-15

4.Click Add Reference to add this to your project. 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 have 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 appears in the App_WebReferences folder. The .wsdl and .disco files are created at the same time. This means you are able to access the web service from within your code. This is the ultimate point of your web service and you’re almost there now.

450

Web Services

Adding the Fixture Service 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. Once again 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.

This might sound quite complicated, but there really is absolutely no difference between creating this proxy object and creating a normal object. In the next Try It Out, you create a small page in your application that consumes your web service.

Try It Out

Adding the Service to Your Application

1.Start by creating a new Web Form in Visual Web Developer. In Solution Explorer, right-click the top line and select Add New Item. Select Web Form and call it Consume.aspx, as shown in Figure 12-17, and then check the Select Master Page box and select site.master as a master page

Figure 12-17

2.In Design View, add a single grid view tool to your new Web Form as in Figure 12-18.

451

Chapter 12

Figure 12-18

3.Click on the page alongside the new grid, in the blank part of the content are to open Consume.aspx.vb’s Page Load event and add the following code inside:

Partial Class Consume

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Dim wsConvert As New FixtureService

GridView1.DataSource = wsConvert.Fixtures() GridView1.DataBind()

End Sub

End Class

4.Save the page and view it in the browser. It will look like Figure 12-19.

452

Web Services

Figure 12-19

How It Works

At last, here you have it; the GridView control has created a table that has bound to the results and fixture provided by your fixtures web service. Only three lines of code were necessary in your final application to do this:

Dim wsConvert As New FixtureService

GridView1.DataSource = wsConvert.Fixtures()

GridView1.DataBind()

First you created a proxy object from localhost.FixtureService called wsConvert. In the previous example, you saw how you created a localhost folder under your App_WebReferences folder, which contained the .wsdl and .disco files.

Next, you bound to the Fixture method of your new wsConvert proxy object, and then you bound to the GridView control and lo and behold your web service output is rendered in Grid View. You’re now free to style and alter the presentation of the web service in any way you choose.

453

Chapter 12

Putting It All Together

Here’s a quick recap. We’ve separated out each step of creating, testing, discovering, and consuming a web service so far, and we might have created the illusion that there are a lot of separate steps to perform. This isn’t really the case, because we’ve had to abstract out each step to explain what is going on. Now you can put them all together in one large, fluid example, and create a separate user control that you can place in any application.

One common feature of many sports sites is the capability to access league tables and show a little miniaturized view of where your team is in the league, and though the Wrox United league table isn’t huge (containing only eight teams), you can certainly create a web service that will show the team above and below Wrox United in the league. There are two provisos to this of course. One is that in the unlikely event that Wrox United is top of the league, you need to show the two teams underneath them. In the far more likely scenario that Wrox United is bottom, then you should show the two teams above them instead. However, we’ll leap those particular chasms when we get to them.

Try It Out

Creating a League Table Mini View Web Service

1.Go to Solution Explorer, right-click the top line and select Add New Item, and then select the Web Service option. Change the name to LeagueMiniView.asmx and click OK.

2.Add the extra namespaces at the very top of the page underneath the existing Imports statements:

Imports System.Data

Imports System.Data.SqlClient

3.You need to add the following code to the WebMethod (note that the SQL string should all be on one line):

<WebMethod()> _

Public Function ViewLeague() As DataSet

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

)

Dim sqlstring As String

Sqlstring = “SELECT [OpponentID], [Name], [TotalGoalsFor], [TotalGoalsAgainst], [TotalGoalsFor]-[TotalGoalsAgainst] AS [GoalDifference], [Points] FROM [Opponents] Order By [Points] DESC, [GoalDifference] DESC, [TotalGoalsFor] DESC”

Dim adapter As New SqlDataAdapter(sqlstring, conn)

Dim adapter2 As New SqlDataAdapter(sqlstring, conn)

Dim ds As New DataSet

Dim ds2 As New DataSet

Dim position As Integer

Dim offset As Integer

Dim rows As DataRowCollection

adapter.Fill(ds, “ViewLeague”) rows = ds.Tables(“ViewLeague”).Rows

For i As Integer = 0 To rows.Count - 1

454

Web Services

If rows(i)(“Name”).ToString() = “Wrox United” Then position = i + 1

End If

Next

If position > 1 And position < rows.Count Then offset = position - 2

ElseIf position = 1 Then offset = position - 1

Else

offset = position - 3 End If

adapter2.Fill(ds2, offset, 3, “ViewLeague”)

ds2.Tables(“ViewLeague”).Columns.Add(“Position”, GetType(Integer)) rows = ds2.Tables(“ViewLeague”).Rows

For i As Integer = 0 To rows.Count - 1 rows(i)(“Position”) = offset + i + 1

Next

Return ds2

End Function

End Class

4.Change the namespace from tempuri.org to wroxunited.net once again, to

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

5.Save this file.

6.You now need to create a page that can utilize this web service. Create a new web user control called LeagueView.ascx and add a GridView control to it. Double-click the LeagueView web user control in design view and add the following code to LeagueView.ascx.vb:

Partial Class LeagueView

Inherits System.Web.UI.UserControl

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Dim wsConvert As New LeagueMiniView

GridView1.DataSource = wsConvert.ViewLeague()

GridView1.DataBind()

End Sub

End Class

7.Save the page. Now you can add this control to default.aspx by tweaking that page’s code as follows.

<%@ Register TagPrefix=”uc1” TagName=”News” Src=”News.ascx” %>

<%@ Register TagPrefix=”uc1” TagName=”LeagueView” Src=”~/LeagueView.ascx” %> <asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”server”>

<h2>Welcome to the Wrox United Web site.</h2>

<p>We’re a great football team. No really, we are. Don’t take any notice of our past performance. We’re just unlucky.</p>

<uc1:leagueview id=”miniview” runat=”server”></uc1:leagueview> <uc1:news id=”News1” runat=”server” ItemsToShow=”3”></uc1:news>

</asp:Content>

455

Chapter 12

8.Now go to default.aspx and view it (see Figure 12-20).

Figure 12-20

How It Works

Hopefully you will be getting a feel for this now. Although you could make the control a little more unobtrusive, the basic gist is there. Admittedly, it’s a little repetitious, but should make it easier to remember. Once again your web service has returned a dataset. This time the WebMethod has a lot more to do. You start by creating a function that returns your dataset:

Public Function ViewLeague() As DataSet

The first task within the function is to connect to the database. You use the predefined WroxUnited connection string to do this.

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

)

You then create the SQL that is needed to return your Mini-League table. You create two SqlDataAdapters, one to go with each SQL string. You need two, because one is a full table and the other is your mini-view of the same league table. adapter2 contains your new shortened view of the table with only three teams, whereas adapter contains the full table:

Sqlstring = “SELECT [OpponentID], [Name], [TotalGoalsFor], [TotalGoalsAgainst], [TotalGoalsFor]-[TotalGoalsAgainst] AS [GoalDifference], [Points] FROM [Opponents] Order By [Points] DESC, [GoalDifference] DESC, [TotalGoalsFor] DESC”

Dim adapter As New SqlDataAdapter(sqlstring, conn)

Dim adapter2 As New SqlDataAdapter(sqlstring, conn)

456

Web Services

You then create two datasets, and create some variables to help you keep track of where you are in the datasets:

Dim ds As New DataSet

Dim ds2 As New DataSet

Dim position As Integer

Dim offset As Integer

Dim rows As DataRowCollection

Next you fill the first adapter with the results of the first SQL query in sqlstring1, which returns the whole league table in order. You then iterate through this table, position by position, until you find an entry that matches “Wrox United”. You save that position into the variable position:

For i As Integer = 0 To rows.Count - 1

If rows(i)(“Name”).ToString() = “Wrox United” Then position = i + 1

End If

Next

You have to cater for three scenarios here:

The golden scenario: Wrox United is top, and you need to display the second and third place teams.

The doomsday scenario: Wrox United is bottom and you need to display the two teams above them.

The usual scenario: Wrox United is neither top nor bottom, but somewhere in between, in which case you display one team above them and one team below them.

Your first if condition deals with the case where the position isn’t top or bottom of the league. You take two off the position (so if Wrox United is 5, this would be 3). Then you fill the adapter2 with the adapter2 starting at position 3, and the number 3 indicates that there are three teams only. For example:

Adapter2.Fill(name of dataset, position to start in dataset, number of rows, name of query).

So you say if the position isn’t 1 and isn’t last (you obtain the amount for last by counting the number of teams in the league), then you set the offset to the position minus 2 and pass that to the adapter2.Fill method at the end of the if then condition:

If position > 1 And position < rows.Count Then offset = position - 2

Of course if Wrox United has come in fifth, why are you starting with third? Surely that would display third, fourth, and fifth, when actually you intend to display fourth, fifth, and sixth? The answer is that when you filled your adapter, you started at row 0. So the team that came first is 0, the team that came second is 1, and so on. So the preceding line to fill the adapter actually does return only three teams, and will return the teams in fourth, fifth, and sixth.

457

Chapter 12

Your second condition deals with what happens if Wrox United is top? You check to see if the position is 1, you set the offset to 0, (1-1), and then you fill the adapter at the end of the if then condition with the dataset starting at row 0, with the next three teams:

ElseIf position = 1 Then offset = position - 1

Last, you can deduce that if our team isn’t first and also didn’t finish between first and last, then they must be last. You set the offset variable accordingly, and fill your data adapter:

Else

offset = position - 3 End If

adapter2.Fill(ds2, offset, 3, “ViewLeague”)

You then add a new column to your second dataset called Position, and you read in the positions for each team in your mini-table:

rows = ds2.Tables(“ViewLeague”).Rows For i As Integer = 0 To rows.Count - 1

rows(i)(“Position”) = offset + i + 1

Next Return ds2

End Function

End Class

Having created the method that fuels your web service, you then need some way of being able to reference it. Because you have a dataset, you create a user control called leagueview.ascx and then add a GridView control to the user control and bind it to your web service.

The final step is to add a reference to your new user control to the Wrox United front page, so that it is displayed in the appropriate position. It is rather large and cumbersome, so you might choose to style it some more and position it differently. This is left as an exercise for you to complete if you so desire, because any more code would distract from the already large code listings you have created.

Remote Web Services — PocketPC

Application

We’ve stressed that what makes web services so flexible is their capability to work across platforms. However, you’ve had to take that for granted, because not many people will have a Mac or Linux machine in addition to their own PC. There is one platform, though, that will be familiar to quite a few readers, and that is the PocketPC platform that runs on PDAs and other mobile technologies. Because we appreciate not everyone will be able to use the following Try It Out, we will keep it relatively brief, but it demonstrates how your online reporters can supply updates to the Wrox United web site using just a web service with a PocketPC application on their PDA. Because you have already created the application that can submit data, all you need to do in this Try It Out is create a web service that will receive scores from reporters and alter the scores on the Wrox United site accordingly.

458