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

Beginning ASP.NET 2

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

E-Commerce

Confirmation of the order

Finish

You will also need a breadcrumb next to you to help you keep an eye on where you are in the whole checkout process. As mentioned at the beginning of the chapter, one priority is being able to abort the transaction at any point prior to confirming the purchase.

What you’re not going to do is the stock handling (reducing items and keep a track on stock levels) and also sending a confirmation of order e-mail. The chapter is already big enough as it is and these things are arguably stretched over different disciplines to e-commerce. Having added that caveat, in the next Try It Out, you create the final stages of the e-commerce pipeline.

Try It Out

Checking Out

1.In Solution Explorer in Visual Web Developer, right-click the C:\...\Chapter13 heading at the top and select Add New Item. Add a Web Form called Checkout.aspx and check the Place Code in separate file box to ensure a separate code behind file is created

2.In Design View, from the Toolbox grab a Wizard control and drop it onto the page, as shown in Figure 13-34.

Figure 13-34

509

Chapter 13

3.From the smart tag dialog box select the Add/Remove wizard steps option.

4.In the dialog that appears you are going to add three extra steps. This is so you have five steps, one for login, one for address, one for credit card details, one to confirm the order, and one to finish the transaction. Start by clicking Add (see Figure 13-35) and entering Step 3 next to Title, and then clicking Add and entering Step 4 and lastly clicking Add and entering Step 5.

Figure 13-35

5.Go back and change the Title property in each so that it reads as shown in Figure 13-36.

Figure 13-36

6.Click OK.

510

E-Commerce

7.From the Login section of the Toolbox, drag a Login box into the <asp:Wizard> control, as shown in Figure 13-37.

Figure 13-37

8.Click Design View. Add the following code to the Wizard step for Step 2 (Delivery Address):

<asp:checkbox id=”chkUseProfileAddress” runat=”server” autopostback=”True” text=”Use membership address” OnCheckedChanged=”chkUseProfileAddress_CheckedChanged”></asp:checkbox><br />

<table border=”0”>

<tr><td>Name</td><td><asp:textbox id=”txtName” runat=”server” /></td></tr> <tr><td>Address</td><td><asp:textbox id=”txtAddress” runat=”server” /></td></tr> <tr><td>City</td><td><asp:textbox id=”txtCity” runat=”server” /></td></tr> <tr><td>County</td><td><asp:textbox id=”txtCounty” runat=”server” /></td></tr> <tr><td>Postcode</td><td><asp:textbox id=”txtPostCode” runat=”server” />

</td></tr>

<tr><td>Country</td><td><asp:textbox id=”txtCountry” runat=”server” /></td></tr> </table>

9.Add the following code to the Wizard step for Step 3 (Payment):

<asp:DropDownList id=”lstCardType” runat=”server”> <asp:ListItem>MasterCard</asp:ListItem> <asp:ListItem>Visa</asp:ListItem>

</asp:DropDownList> <br />

Card Number: <asp:Textbox id=”txtNumber” runat=”server”

511

Chapter 13

Text=”0123456789” ReadOnly=”True”/> <br />

Expires:

<asp:textbox id=”txtExpiresMonth” runat=”server” columns=”2” />

/

<asp:textbox id=”txtExpiresYear” runat=”server” columns=”4” />

10.Go back to Design View for Step 4 (Confirmation). Type in the following:

Please confirm the amount you wish to have

deducted from your credit card.

11.Select WroxShoppingCart.ascx and drag it into the Wizard control above the text you have created, as shown in Figure 13-38.

Figure 13-38

12.Click Complete and in Design View for Step 5 (Complete) just type in Thank you for your order.

13.Go to Source View and above the <asp:Wizard> control add the following:

<asp:Label id=”NoCartlabel” runat=”server” visible=”false”> There are no items in your cart. Visit the shop to buy items. </asp:Label>

<div style=”float:right”>

<asp:LoginView ID=”LoginView1” Runat=”server”> <AnonymousTemplate>

<asp:passwordrecovery id=”PasswordRecovery1” runat=”server” />

512

E-Commerce

</AnonymousTemplate>

</asp:LoginView>

</div>

14.Above this code add the following:

<%@ Import Namespace =”System.Data.SqlClient”%>

<%@ Import Namespace =”Wrox.Commerce”%>

15.Save the design.

16.Go to Solution Explorer, select checkout.aspx.vb.

17.Add the following code-behind in place of whatever is already in there.:

Imports System

Imports System.Data.SqlClient

Imports Wrox.Commerce

Partial Class Checkout

Inherits System.Web.UI.Page

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load

If Not Page.IsPostBack Then

If Profile.Cart Is Nothing Then

NoCartlabel.Visible = True

Wizard1.Visible = False

End If

If User.Identity.IsAuthenticated Then

Wizard1.ActiveStepIndex = 1

Else

Wizard1.ActiveStepIndex = 0

End If

End If

End Sub

Sub chkUseProfileAddress_CheckedChanged(ByVal sender As Object, _

ByVal e As System.EventArgs)

fill the delivery address from the profile, but only if it’s empty

we don’t want to overwrite the values

If chkUseProfileAddress.Checked AndAlso txtName.Text.Trim() = “” Then txtName.Text = Profile.Name

txtAddress.Text = Profile.Address txtCity.Text = Profile.City txtCounty.Text = Profile.County txtPostCode.Text = Profile.PostCode txtCountry.Text = Profile.Country

513

Chapter 13

End If

End Sub

Sub Wizard1_FinishButtonClick(ByVal sender As Object, _

ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs)

‘ Insert the order and order lines into the database Dim conn As SqlConnection = Nothing

Dim trans As SqlTransaction = Nothing Dim cmd As SqlCommand

Try

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

)

conn.Open()

trans = conn.BeginTransaction

cmd = New SqlCommand() cmd.Connection = conn cmd.Transaction = trans

‘ set the order details

cmd.CommandText = “INSERT INTO Orders(MemberName, OrderDate, Name, “ & _ “Address, County, PostCode, Country, Total) “ & _

“VALUES (@MemberName, @OrderDate, @Name, “ & _ “@Address, @County, @PostCode, @Country, @Total)”

cmd.Parameters.Add(“@MemberName”, Data.SqlDbType.VarChar, 50) cmd.Parameters.Add(“@OrderDate”, Data.SqlDbType.DateTime) cmd.Parameters.Add(“@Name”, Data.SqlDbType.VarChar, 50) cmd.Parameters.Add(“@Address”, Data.SqlDbType.VarChar, 255) cmd.Parameters.Add(“@County”, Data.SqlDbType.VarChar, 50) cmd.Parameters.Add(“@PostCode”, Data.SqlDbType.VarChar, 15) cmd.Parameters.Add(“@Country”, Data.SqlDbType.VarChar, 50) cmd.Parameters.Add(“@Total”, Data.SqlDbType.Money)

cmd.Parameters(“@MemberName”).Value = User.Identity.Name cmd.Parameters(“@OrderDate”).Value = DateTime.Now() cmd.Parameters(“@Name”).Value = _

CType(Wizard1.FindControl(“txtName”), TextBox).Text cmd.Parameters(“@Address”).Value = _

CType(Wizard1.FindControl(“txtAddress”), TextBox).Text cmd.Parameters(“@County”).Value = _

CType(Wizard1.FindControl(“txtCounty”), TextBox).Text cmd.Parameters(“@PostCode”).Value = _

CType(Wizard1.FindControl(“txtPostCode”), TextBox).Text cmd.Parameters(“@Country”).Value = _

CType(Wizard1.FindControl(“txtCountry”), TextBox).Text cmd.Parameters(“@Total”).Value = Profile.Cart.Total

Dim OrderID As Integer

514

E-Commerce

OrderID = Convert.ToInt32(cmd.ExecuteScalar())

‘ change the query and parameters for the order lines cmd.CommandText = “INSERT INTO OrderLines(OrderID, ProductID, “ & _

“Quantity, Price) “ & _

“VALUES (@OrderID, @ProductID, @Quantity, @Price)” cmd.Parameters.Clear()

cmd.Parameters.Add(“@OrderID”, Data.SqlDbType.Int) cmd.Parameters.Add(“@ProductID”, Data.SqlDbType.Int) cmd.Parameters.Add(“@Quantity”, Data.SqlDbType.Int) cmd.Parameters.Add(“@Price”, Data.SqlDbType.Money)

cmd.Parameters(“@OrderID”).Value = OrderID

For Each item As CartItem In Profile.Cart.Items cmd.Parameters(“@ProductID”).Value = item.ProductID cmd.Parameters(“@Quantity”).Value = item.Quantity cmd.Parameters(“@Price”).Value = item.Price

cmd.ExecuteNonQuery() Next

‘ commit the transaction trans.Commit()

Catch SqlEx As SqlException

some form of error - rollback the transaction

and rethrow the exception

If trans IsNot Nothing Then trans.Rollback()

End If

‘ Log the exception

Tools.log(“An error occurred while creating the order”, SqlEx) Throw New Exception(“An error occurred while creating the order”, _

SqlEx)

Return

Finally

If conn IsNot Nothing Then

conn.Close()

End If

End Try

we will only reach here if the order has been created successfully

so clear the cart

Profile.Cart.Items.Clear()

End Sub

Sub Wizard1_NextButtonClick(ByVal sender As Object, _

515

Chapter 13

ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs)

If e.CurrentStepIndex = 0 Then

Dim l As System.Web.UI.WebControls.Login = _

CType(Wizard1.FindControl(“Login1”), Login)

If Membership.ValidateUser(l.UserName, l.Password) Then FormsAuthentication.SetAuthCookie(l.UserName, l.RememberMeSet) e.Cancel = False

Else

l.InstructionText = “Your login attempt was not successful. “ & _ “Please try again.”

l.InstructionTextStyle.ForeColor = System.Drawing.Color.Red

e.Cancel = True End If

Else

If Not User.Identity.IsAuthenticated Then

e.Cancel = True

Wizard1.ActiveStepIndex = 0

End If

End If

End Sub

Protected Sub Wizard1_ActiveStepChanged(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Wizard1.ActiveStepChanged

If Not User.Identity.IsAuthenticated Then

Wizard1.ActiveStepIndex = 0

End If

End Sub

End Class

18.Open WroxShoppingCartPage.aspx and in Design View, and add a hyperlink to the page. Right-click the link and change the properties as follows:

Property

Value

ID

Checkout

Text

Checkout

NavigateURL

~/Checkout.aspx

516

E-Commerce

19.Add two scarves to your shopping cart and click Checkout. First you supply login details in the fields shown in Figure 13-39.

Figure 13-39

20.Click Next once you’re logged in, and then you either click on your membership address or supply your address details (see Figure 13-40).

Figure 13-40

517

Chapter 13

21.Click Next, and you’ll arrive at the screen shown in Figure 13-41. This is your credit card handler; it doesn’t require any user details.

Figure 13-41

22.Click Next, and on the last page (see Figure 13-42) you see a summary of the details.

Figure 13-42

23.Click Finish to end the checkout.

How It Works

This completes your e-commerce pipeline. You started by creating the five stages of our agreed checkout process using the <asp:wizard> control. The login stage used a Login control, and the delivery address used a checkbox and a series of text boxes to record the details. The payment stage took the credit card details via a drop-down list, which contained the type of credit card, and you had text boxes for the card number and expiration date. You didn’t validate these details in any way. In the confirmation stage you just stuck a copy of the shopping cart control, and the last step simply displayed a short thank you message.

518