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

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

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

Chapter 12

How It Works

In this Try It Out, you 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 void UpdateGoals(int FixtureID, bool GoalFor, _ int PlayerID, int GoalTime)

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

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

conn.Open();

SqlCommand cmd = 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)

{

Goal(FixtureID, PlayerID, GoalTime);

}

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

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

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

458

Web Services

This 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:

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();

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 was 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 lack of ease with which they can be secured. If you create a web service, and you 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 was 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 usually done by the common user ID and 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.

459

Chapter 12

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 people would have previously disregarded web services for transferring sensitive and confidential information, but that no longer needs to be the case.

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.

A proxy object within your code 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 each of these technologies has a role to play, they have been 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 whenever 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.)

460

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 very 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. After you choose an item, it is moved into your shopping cart. You can continue shopping and add more items, and when you finish, 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 you get a summary and maybe an e-mail containing the details of the sale. ASP.NET 2.0 introduces a terrific range of controls 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 isn’t practical to set up a credit card–handling facility for the sake of testing one chapter. However, with the new components that ASP.NET 2.0 brings, you can create a product catalog, a shopping cart, and a checkout system; 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 and treated very seriously, it isn’t something to be scared of adding, because ASP.NET 2.0 makes it simpler than ever before.

Chapter 13

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

462

E-Commerce

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 striped edition)

Car Sticker

Lucky Mascot

Large Flag (for 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 10 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 10 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.

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

Product image

Product title

Price

463

Chapter 13

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 a 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 and testimonials regarding how wonderful or appalling the product is, and even a cross-linking reference that mentions which other items customers 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:\BegASPNET2\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 the Design View of the page, and click the smart tasks panel that appears (see Figure 13-2).

3.Click Configure Data Source from the Tasks panel, and select WroxUnitedConnectionString (which is already automatically configured, as indeed connection strings are for all databases within the App_Data folder), as shown in Figure 13-3.

4.Click Next and then from the Configure the Select Statement dialog box that appears, select the Products table and all of the fields contained within it, as shown in Figure 13-4.

5.Click Next. Test the query to make sure it retrieves the data and then click Finish, which takes you back to Design View.

6.Now you need to add a second control to your page. From the Data menu of the Toolbox, select the DataList control. Click the smart tag dialog box that appears. From the Choose Data Source drop-down list, select SqlDataSource1, as shown in Figure 13-5.

464

E-Commerce

Figure 13-2

Figure 13-3

465

Chapter 13

Figure 13-4

Figure 13-5

466

E-Commerce

7.Click the smart tag dialog box above the DataList control and select Edit Templates. (Chapter 7 looked at the process of editing an ItemTemplate if you need a quick reminder.) Figure 13-6 shows your default layout.

Figure 13-6

8.This ensuing layout needs a bit of refining to be suitable for displaying a catalog. First delete all of the explanatory text, such as Name and Description, using the Backspace key. Also, you don’t need to display all of the items from the Products table — in fact, you only need a picture of the item, its price, and its name on the catalog page, as agreed on in the design. Delete the Product ID and Description and move the Picture URL to the top. You can drag and drop the Label controls to order them correctly, as shown in Figure 13-7.

Figure 13-7

9.Delete the PictureURL label, because you want to display an image here rather than a label. Select ImageButton from the menu and drag it across to where the PictureURLLabel was. A red cross and the smart tag dialog box with the legend Edit Data Bindings should appear (see Figure 13-8). (You saw in Chapter 7 how to do this, but it delved directly into the code, whereas here you’re using the wizard.)

Figure 13-8

10.Select Edit Data bindings and then select the Custom binding radio button. Amend the Code expression box so that it reads as follows:

Eval (“PictureURL”,”ProductImages\\thumb_{0}”)

Figure 13-9 shows how everything should look.

467