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

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

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

Chapter 12

This might sound quite complicated, but there really is 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.Create 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, making sure that the Place Code in Separate File box is checked. Also check the Select Master Page box. On the second page, 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.

Figure 12-18

448

Web Services

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

public partial class Consume : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{localhost.FixtureService wsConvert = new localhost.FixtureService();

GridView1.DataSource = wsConvert.Fixtures();

GridView1.DataBind();

}

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

Figure 12-19

How It Works

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:

localhost.FixtureService wsConvert = new localhost.FixtureService();

GridView1.DataSource = wsConvert.Fixtures();

GridView1.DataBind();

First you created a proxy object from localhost.FixtureService called wsConvert. In the previous example, you created a localhost folder under your App_WebReferences folder, which contained the

.wsdl and .disco files.

449

Chapter 12

Next, you bound to the Fixture method of your new wsConvert proxy object, and then you bound to the GridView control. 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.

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 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 at the top of the league, you need to show the two teams underneath them. In the far more likely scenario that Wrox United is at the bottom, 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, 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 top of the page underneath the existing using statements:

using System.Data;

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

3.Remove the HelloWorld() method and add the following code to the WebMethod (note that the SQL string should all be on one line):

[WebMethod]

public DataSet ViewLeague()

{

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

string sqlstring;

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

SqlDataAdapter adapter = new SqlDataAdapter(sqlstring, conn);

SqlDataAdapter adapter2 = new SqlDataAdapter(sqlstring, conn);

DataSet ds = new DataSet();

DataSet ds2 = new DataSet();

450

Web Services

int position=0; int offset;

DataRowCollection rows;

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

for (int i = 0; i< rows.Count; i++)

{

if (rows[i][“Name”].ToString() == “Wrox United”)

{

position = i + 1;

}

}

if (position > 1 && position < rows.Count)

{

offset = position – 2;

}

else if (position == 1)

{

offset = position –1;

}

else

{

offset = position -3;

}

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

ds2.Tables[“ViewLeague”].Columns.Add(“Position”, typeof(int)); rows = ds2.Tables[“ViewLeague”].Rows;

for (int i = 0;i< rows.Count;i++)

{

rows[i][“Position”] = offset + i + 1;

}

return ds2;

}

4.Change the namespace from tempuri.org to wroxunited.net again, to [WebService(Name space:=”http://wroxunited.net/”)].

5.Save this file.

6.You now need to create a page that can use 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.cs:

public partial class LeagueView : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

localhost.LeagueMiniView wsConvert = new localhost.LeagueMiniView(); GridView1.DataSource = wsConvert.ViewLeague(); GridView1.DataBind();

}

}

451

Chapter 12

7.Save the page. Add this control to default.aspx by changing that page’s code as follows.

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

<%@ Register TagPrefix=”wu” 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=”5”></uc1:news>

</asp:Content>

8.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 DataSet ViewLeague()

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

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

452

Web Services

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”;

SqlDataAdapter adapter = new SqlDataAdapter(sqlstring, conn);

SqlDataAdapter adapter2 = new SqlDataAdapter(sqlstring, conn);

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

DataSet ds = new DataSet(); DataSet ds2 = new DataSet(); int position=0;

int offset; DataRowCollection rows;

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 iterated through this table, position by position, until you find an entry that matches “Wrox United”. You save that position into the variable position:

for (int i = 0; i< To rows.Count; i++)

{

if (rows[i][“Name”].ToString() == “Wrox United”)

{

position = i + 1;

}

}

There are 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 2 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:

453

Chapter 12

if (position > 1 && position < rows.Count)

{

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

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 condition with the dataset starting at row 0, with the next three teams:

else if (position == 1)

{

offset = position - 1;

}

Last, you can deduce that if your 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;

}

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 (int i As Integer = 0; i< rows.Count;i++)

{

rows[i][“Position”] = offset + i + 1;

}

return ds2;

}

}

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

454

Web Services

Remote Web Services — PocketPC

Application

This chapter has 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 that 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.

The extra bit of functionality that this Try It Out also includes is the ability to send parameters with the web service. This is just like sending parameter in a method, as you saw in Chapter 8.

To be able to run this Try It Out, you will need a piece of hardware capable of running PocketPC applications. This Try It Out was tested and run on a Dell AXIM PDA that was running PocketPC 2003. While we endeavor to make sure this application will work on all PDAs running PocketPC, due to the diverse nature of the PDA, we can make no such guarantees. If you don’t have a PDA, you could try running it on an emulator instead.

Try It Out

Updating the Scores Web Service

1.Make sure you have a copy of the PocketPC application from c:\BegASPNet2\Chapters\ Begin\Chapter12\PDA.

2.Open the C:\BegASPNet2\Begin\Chapter12\WroxUnited web site.

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

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

using System.Data;

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

5.Add the following web method.

[WebMethod]

public void UpdateGoals(int FixtureID , bool GoalFor , int PlayerID , int GoalTime )

{

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

);

conn.Open();

SqlCommand cmd = new SqlCommand(“usp_UpdateScore”, conn); cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(“@FixtureID”, SqlDbType.Int).Value = FixtureID;

455

Chapter 12

cmd.Parameters.Add(“@GoalFor”, SqlDbType.Bit).Value = GoalFor;

cmd.ExecuteNonQuery();

if (GoalFor)

{

Goal(FixtureID, PlayerID, GoalTime);

}

}

6.Add another web method underneath the previous one:

[WebMethod]

public void Goal(int FixtureID, int PlayerID, int GoalTime )

{

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

conn.Open();

SqlCommand cmd = new SqlCommand(“usp_Goal”, conn); cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(“@FixtureID”, SqlDbType.Int).Value = FixtureID; cmd.Parameters.Add(“@PlayerID”, SqlDbType.Int).Value = PlayerID; cmd.Parameters.Add(“@GoalTime”, SqlDbType.Int).Value = GoalTime;

cmd.ExecuteNonQuery();

}

7.Change the namespace from http//:tempuri.org to http://wroxunited.net, once again in the line at the beginning of the definition of the web service:

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

8.Save this file.

9.Run the PDA application, add a scorer and goal details on the page, and hit the submit button (note that the PDA must have an active Internet connection for this to work). For example, in Figure 12-21, we’ve suggested adding Jerry Johnston at 90 minutes in the Wrox United versus Mellingham fixture.

10.Run the Wrox United site and go to the scorers link, which now shows the updated details where Jerry Johnston has been added to the scorers list, as shown in Figure 12-22.

456

Web Services

Figure 12-21

Figure 12-22

457