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

Beginning ASP.NET 2

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

Web Services

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.

Try It Out

Updating the Scores Web Service

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

2.Next, 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 very top of the page underneath the existing Imports statements:

Imports System.Data

Imports System.Data.SqlClient

5.Add the following web method.

<WebMethod()> _

Public Sub UpdateGoals(ByVal FixtureID As Integer, ByVal GoalFor As Boolean, _ ByVal PlayerID As Integer, ByVal GoalTime As Integer)

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

)

conn.Open()

Dim cmd As New SqlCommand(“usp_UpdateScore”, conn) cmd.CommandType = CommandType.StoredProcedure

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

cmd.ExecuteNonQuery()

If GoalFor Then

Goal(FixtureID, PlayerID, GoalTime)

End If

End Sub

6.Next add another web method underneath the previous one:

<WebMethod()> _

Public Sub Goal(ByVal FixtureID As Integer, ByVal PlayerID As Integer, _ ByVal GoalTime As Integer)

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

)

conn.Open()

459

Chapter 12

Dim cmd As 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()

End Sub

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

Figure 12-21

460

Web Services

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.

Figure 12-22

How It Works

In this Try It Out you have created two web methods as part of your web service. Which web method you use depends on whether Wrox United scored the goal or whether the goal was scored by an opponent. If Wrox United scored a goal then you need to update the goal, the player who scored it, and the time it was scored. If the opposition scored it then you only need to use two of the parameters to update the score in the database. To use the web service you start by calling the UpdateScore method first and then you detect whether it is a Wrox United goal, and only if it is a Wrox United goal do you update the Goal method as well.

The UpdateGoals web method updates which side scored the goal and the Score method takes four parameters, shown in bold in the following code:

Public Sub UpdateGoals(ByVal FixtureID As Integer, ByVal GoalFor As Boolean, _ ByVal PlayerID As Integer, ByVal GoalTime As Integer)

The web method creates a connection and a command, and sets the command type as stored procedure (stored procedures are discussed in Chapter 14):

461

Chapter 12

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

)

conn.Open()

Dim cmd As New SqlCommand(“usp_UpdateScore”, conn) cmd.CommandType = CommandType.StoredProcedure

You pass the parameters of the FixtureID and the whether the goal was for or against us and execute the query.

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

cmd.ExecuteNonQuery()

If the goal was for us, then you call the Goal web method with the FixtureID, the PlayerID, and the

GoalTime:

If GoalFor Then

Goal(FixtureID, PlayerID, GoalTime)

End If

The Goal web method updates the Wrox United goals and the Score method only takes three parameters, shown in bold here:

Public Sub Goal(ByVal FixtureID As Integer, ByVal PlayerID As Integer, _ ByVal GoalTime As Integer)

These three parameters are the fixture number, the number of the player, and the timing of the goal. In the PDA application, you selected the FixtureID from a selection of possible fixtures (for example, Wrox United versus Ponsonby Athletic) rather than selecting FixtureID 27 from a DropDownList control, and you selected the name of the player from a DropDownList control along with checkbox indicating if it was a goal for or against Wrox United. In the text box you typed the time of the goal. These are passed to your web method.

The web method is very similar to the previous one in that it you create a connection and call a stored procedure, which will update the Wrox United database. It passes the three parameters and executes the query:

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

)

conn.Open()

Dim cmd As 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()

462

Web Services

Much of the work is done behind the scenes with the PocketPC application; however, as long as the Wrox United application makes the information available in a standard way (as we have done here), then any application — whether a Windows application, a web application, or a PDA application — can use it via an Internet connection.

Web Service Security

This chapter’s introduction mentioned that one of the reasons that web services’ lack of adoption in some quarters may be due to the ease, or rather lack of ease, with which they can be secured. If you create a web service, and you do want to market it, then you need to be able to control and regulate access to the web service.

While certainly possible in ASP.NET 1.x, it wasn’t the easiest of tasks and this is one area that has definitely been improved in ASP.NET 2.0. Also, as you’ve seen, the web service request and response is sent as XML documents (in other words pure text), so if you’re not sending via SSL, then anyone is able to intercept and steal the code. A couple of new facilities in ASP.NET 2.0 help you deal with this.

Encryption and Message-Based Security

Encryption is the process of scrambling the text containing your web service so that only the intended reader is able to decrypt it with the aid of a key. Message-based security has been introduced in web services.

Message-based security allows you to hand your encrypted messages to anyone, and they won’t be able to decrypt the encrypted data. If your message is modified you will be able to detect that straightaway because the signature attached to the message will be invalid and you can throw those messages away. It works by encrypting the message at both request and response level and is defined in the web services WSSecurity specification (a relatively new W3 specification detailing how to handle web services security).

Authentication and Access Controls for Services

Authentication is the process of checking to see if a particular user is who they claim to be. This is done usually by the common user ID/password entry. One way to secure a web service is to force anyone who attempts to use a service to have to supply credentials first. They have to supply a user ID and password, and if they don’t they are refused access to the web service.

You can find more details at http://msdn.microsoft.com/library/ default.asp?url=/library/en-us/rsprog/htm/rsp_prog_soapapi_dev_6ne8.asp.

Using both of these facilities is beyond the scope of this book; they are mentioned here because previously people would have disregarded web services for transferring sensitive and confidential information, but that no longer needs to be the case.

463

Chapter 12

Summar y

Web services are a massive subject that could command a whole book quite easily in their own right. We have been necessarily curt in our treatment of them to give you an idea of how they might be accessed and used within your own applications. As you saw at the beginning of this chapter a web service is simply a functionality that can be remotely called over the web. However, the distinct advantage they enjoyed over other similar methods is that all information was sent and returned in the form of XML documents (and therefore text). Specifically, this chapter covered the following topics:

The process of using a web service, which can be broken down into creating a web service, making the web service available for discovery, and ultimately consuming the web service.

A lot of new technologies introduced in this chapter (fortunately Visual Web Developer handles them smoothly for us), including SOAP, which is a framework for exchanging messages and is used in the transmission of web services. A SOAP document is transmitted as part of the

HTTP data. DISCO and UDDI are used to make the web service available so that people can see and use it.

Last, you’ve seen the idea of a proxy object within your code, which takes the place of the web service and allows you to access the different methods of the web service as though it were on the same PC.

Although all of these technologies each has a role to play, they have been very much hidden from us. The files and objects are created automatically for us, and the bottom line is that if you create a method or object, basically all you need to do is start a <WebMethod> with a few extra configuration details, and the rest is done for you.

The next chapter deals with e-commerce by showing you how to set up a shopping cart and how to shop for merchandise on Wrox United’s web site.

Exercises

1.What is the role of SOAP in web services?

2.Create a web service that retrieves a Wrox United score wherever they’ve scored more than one goal.

3.Create a page that consumes the third-party weather forecast for Birmingham, United Kingdom. (Hint: You will also need to discover this service first.)

464

13

E-Commerce

This is the first version of this book that’s ever dared to talk about e-commerce. This isn’t because we’ve forgotten to, or because we think it’s unimportant, but mainly because this is the first version of ASP.NET where it hasn’t been too complicated to even think about. I must admit it’s the one area as a developer that even I (or any developer) will tread carefully. The reason is simple — money. When you’re handling other people’s money, you really must make every effort to ensure that nothing can go wrong. If not, you, or the company you work for, could be held responsible and personally liable for every penny lost or stolen.

If you’re not frightened off by that rather stern introduction, then I must hasten to add that there has never been a better time for building e-commerce functionality into your applications. By e-commerce I’m using an all-embracing term, because e-commerce covers a multitude of features; in fact, it extends over the entire process of buying and selling an item on the Web. If you consider what happens when you visit a site such as Amazon, with an intention to purchase something, there are several stages. First is the product catalog that displays the list of items from which you want to make a purchase. Once you’ve chosen an item, it is moved into your shopping cart. You can choose to continue shopping and add more items, and once you’ve finished, you check out. After you check out, your order has to be processed. These kinds of questions have to be answered when order processing: Is your item in stock? How long will it take to order if it isn’t? Where should it be delivered? Next comes the bit we all hate, getting the credit card out and supplying details, checking that the number is valid, and the dates. The whole transaction should be secure. Then at last a summary and maybe an e-mail summarizing the details of the sale. ASP.NET 2.0 introduces a terrific range of features to help you build a workable e-commerce solution for any web site.

Of course it isn’t possible to fully model every step of this process in just one chapter, and as with web services entire books are devoted to this subject. Also, it just isn’t practical to set up a credit card–handling facility for the sake of testing one chapter. However, with the new features that ASP.NET 2.0 brings you can create a product catalog, a shopping cart, and a checkout system, you can update the stock details and product catalog, get users to enter their details, and see how you would handle real credit card details. This should give you a strong overview of how you can add the capability to buy and sell items from your web site, and although it is something to be wary of

Chapter 13

and treated very seriously, it isn’t something to be scared of adding, because ASP.NET 2.0 makes it simpler than ever before.

This chapter looks at the following:

The typical process involved in an e-commerce transaction

Creating a product catalog

Creating a shopping cart and remembering which items you have in it

Completing an e-commerce transaction and checkout

What you’d need to do to process the order

The considerations involved in credit card–handling

Conducting secure transactions

The E-Commerce Pipeline

The once-common term pipeline is used to describe the whole e-commerce process, from browsing for particular products all the way through to having the product or products in your hand. Although the term has fallen out of the common vernacular slightly, it’s one that we use here because it accurately reflects what is going on. Although different businesses may have different variations on the pipeline, it remains fundamentally similar for most web sites. A typical e-commerce pipeline might look like Figure 13-1.

Browse the

 

 

Add an Item

 

 

Checkout

 

 

Process the

 

 

Take the Credit

 

 

Confirm

 

 

 

 

 

 

 

 

 

 

Product Catalog

 

 

to the cart

 

 

 

 

 

Order

 

 

Card Details

 

 

Purchase & Send

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 13-1

It’s referred to as a pipeline because the next stage is dependent on the last and you have to pass the details through each stage. So like water flowing from a reservoir, through the pipes, to your faucet, here it’s the same with the product. You select a product, you add that product to the shopping cart,

you check out with that selected product, you get a total price for the product you want to purchase, you pay for the product, you get confirmation of that purchase, and then hopefully, all being well, the product is sent to you. At any stage of the pipeline, you must be able to halt the transaction, with the minimum of hassle. The only moment the transaction becomes irrevocable is when you hit “Confirm Purchase.” Even then, you should be able to return the product to the shop if you ordered the wrong one, or you just plain don’t like it. However, we’re not going to go to quite to that extreme level of detail; you should get the idea.

The Wrox United web site already has a fully formed pipeline, and what you’re going to do in this chapter is rebuild the pipeline from the ground up, step by step, right from the initial design, and learn about the decisions that need to be made as it is built. You should see that e-commerce isn’t just about

466

E-Commerce

programming a solution, but it’s about design, layout, and taking into account the customer’s needs and requirements. This chapter spends a lot of time away from the programming “factory floor” talking about these needs, too.

The Product Catalog

This chapter starts at the beginning with the Product catalog. Catalog is the commonly accepted term for an online version of a store’s brochure. It is the one rare occasion where jargon hasn’t gotten involved to complicate matters, because the word describes perfectly what it does. Every e-commerce site depends upon its catalog; it’s the place from which customers will pick and choose which items to buy, and place them in the shopping cart. Wrox United is no different in this respect.

The Structure of the Catalog

The first question should be, “What are we going to sell?” The Wrox United team, like most franchises, has its own range of branded items, and you want to make all of them available on the web site for the public to buy. The current Wrox United product range looks like this:

Scarf (plain edition or stripey edition)

Car Sticker

Lucky Mascot

Large Flag (for at the match)

Fan Club Membership

Replica Kit (Home and Away)

Small Flag (for the car)

Mouse pad

Hat

Bug

Already you can see that there might be different categories of items that you might need to differentiate between in your catalog, such as a Home Replica Kit and an Away Replica Kit. However, the product range is small, boasting just ten different items, so you can make the decision not to subdivide the catalog into different categories, because you should be able to display the details on just one page, and treat them all as individual items.

The Design of the Catalog

Having sorted out what you’re going to sell, the next question is, “What should our customers want to see when they come to purchase an item?” Because there are only ten items on display, you’ll do your best to make sure that all of the items are displayed together on one page. That means cramming in a lot on just one page, so you can use a grid to lay them out and try to get away with not adding too much to the page.

467

Chapter 13

For the Wrox United products, perhaps the absolute minimum you could offer is as follows:

Product image

Product title

Price

Behind the scenes you’ll also need to make sure that you can uniquely identify each product you offer, so you’ll need a Product ID as well. When customers come to examine a product, they’ll probably want to know a little more about it, such as Product Description, but you can deal with this on a separate page dedicated to the item.

In addition to this, you could also consider a wider set of attributes that you might want listed for each product, such as how many products are currently in stock, how long they will take to deliver, the release date of the product, customer reviews/testimonials to how wonderful/appalling the product is, and even a cross-linking reference that mentions which other items customers had purchased when they purchased this item.

For Wrox United, this is all complete overkill; there are only so many things you can say about a flag. However, you should be able to see that what you will require in the database will be specific to your particular business. For Wrox United, it’s easy to settle on the aforementioned five fields (Image, Title, Price, Description, and for behind the scenes, the unique Product ID). Normally, the first stage would be to build or alter the database to add these categories, but all of them are already contained within the Products table of the database, so you don’t need to add anything else to it. You’ve got a structure of the catalog and you’ve got a design, and a database that supports it, so you can proceed straight to the next stage and implement it.

Implementation of the Catalog

The product catalog actually breaks down into two pages: one is like an index of all the products in your catalog and the second is the page that shows particular details about the item. In this Try It Out you start by building the product catalog.

Try It Out

Building an Index Page for the Catalog

1.Open Visual Web Developer and open the C:\BegASPNET\Chapters\Begin\Chapter13 web site. Open the blank wroxshop.aspx page.

2.First you’ll add some controls. Drag a SqlDataSource control from the Data menu of the Toolbox into Design View of the page, and click the Common Tasks Menu that appears (see Figure 13-2).

3.Click Configure Data Source from the Tasks panel that appears, and then click New Connection in the dialog that appears. Select WroxUnitedConnectionString (which is already automatically configured, as indeed connection strings are for all databases found within the App_Data folder), as shown in Figure 13-3.

468