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

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

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

Chapter 13

Figure 13-37

8.Click Source 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”

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

Expires:

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

/

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

508

E-Commerce

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

Please confirm the amount you wish to have

deducted from your credit card.

11.Select ShoppingCart.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), type 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” /> </AnonymousTemplate>

</asp:LoginView>

</div>

14.Above this code, add the following:

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

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

509

Chapter 13

15.Save the design.

16.Go to Solution Explorer, and select checkout.aspx.cs.

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

using System; using System.Data;

using System.Data.SqlClient; using System.Configuration; using Wrox.Commerce;

using System.Web.UI.WebControls; using System.Web.Security;

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

{

void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

if (Profile.Cart == null)

{

NoCartlabel.Visible = true; Wizard1.Visible = false;

}

if (User.Identity.IsAuthenticated)

{

Wizard1.ActiveStepIndex = 1;

}

else

{

Wizard1.ActiveStepIndex = 0;

}

}

}

protected void chkUseProfileAddress_CheckedChanged(object sender , System.EventArgs e )

{

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

//we don’t want to overwrite the values

if (chkUseProfileAddress.Checked && txtName.Text.Trim() == “”)

{

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

}

}

protected void Wizard1_FinishButtonClick( object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)

510

E-Commerce

{

// Insert the order and order lines into the database SqlConnection conn = null;

SqlTransaction trans = null; SqlCommand cmd;

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, SubTotal, Discount, Total) “ +

“VALUES (@MemberName, @OrderDate, @Name, @Address, @County, @PostCode, @Country, @SubTotal, @Discount, @Total)”;

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

cmd.Parameters[“@MemberName”].Value = User.Identity.Name; cmd.Parameters[“@OrderDate”].Value = DateTime.Now; cmd.Parameters[“@Name”].Value =

((TextBox)Wizard1.FindControl(“txtName”)).Text; cmd.Parameters[“@Address”].Value =

((TextBox)Wizard1.FindControl(“txtAddress”)).Text; cmd.Parameters[“@County”].Value =

((TextBox)Wizard1.FindControl(“txtCounty”)).Text; cmd.Parameters[“@PostCode”].Value = ((TextBox)Wizard1.FindControl(“txtPostCode”)).Text;

cmd.Parameters[“@Country”].Value = ((TextBox)Wizard1.FindControl(“txtCountry”)).Text;

cmd.Parameters[“@SubTotal”].Value = Profile.Cart.SubTotal; cmd.Parameters[“@Discount”].Value = Profile.Cart.MemberDiscount; cmd.Parameters[“@Total”].Value = Profile.Cart.Total;

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

// change the query and parameters for the order lines

cmd.CommandText = “INSERT INTO OrderLines(OrderID, ProductID, Quantity, Price) “ +

511

Chapter 13

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

cmd.Parameters[“@OrderID”].Value = OrderID; foreach (CartItem item in Profile.Cart.Items)

{

cmd.Parameters[“@ProductID”].Value = item.ProductID; cmd.Parameters[“@Quantity”].Value = item.Quantity; cmd.Parameters[“@Price”].Value = item.Price;

cmd.ExecuteNonQuery();

}

// commit the transaction trans.Commit();

}

catch (SqlException SqlEx)

{

//some form of error - rollback the transaction

//and rethrow the exception

if (trans != null) trans.Rollback();

CreateOrderErrorLabel.Visible = true;

//Log the exception

//Tools.log(“An error occurred while creating the order”, SqlEx)

throw new Exception(“An error occurred while creating the order”, SqlEx);

}

finally

{

if (conn != null) conn.Close();

}

//we will only reach here if the order has been created sucessfully

//so clear the cart

Profile.Cart.Items.Clear();

}

protected void Wizard1_NextButtonClick( object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)

{

if (e.CurrentStepIndex == 0)

{

System.Web.UI.WebControls.Login l = (Login)Wizard1.FindControl(“Login1”);

if (Membership.ValidateUser(l.UserName, l.Password))

{

512

E-Commerce

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;

}

}

else

{

if (!User.Identity.IsAuthenticated)

{

e.Cancel = true; Wizard1.ActiveStepIndex = 0;

}

}

}

protected void Wizard1_ActiveStepChanged( object sender, System.EventArgs e)

{

if (!User.Identity.IsAuthenticated) Wizard1.ActiveStepIndex = 0;

}

}

18.Open ShoppingCartPage.aspx and in Design View, add a hyperlink to the page. Right-click the link and change the properties as shown in the following table.

Property

Value

ID

Checkout

Text

Checkout

NavigateURL

~/Checkout.aspx

19.Run Wroxshop.aspx, add two scarves to your shopping cart, and click Checkout. Supply login details in the fields shown in Figure 13-39.

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

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.

513

Chapter 13

Figure 13-39

Figure 13-40

Figure 13-41

514

E-Commerce

22.Click Next. 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 the checkout process using the <asp:wizard> control. The login stage used a Login control, and the delivery address used a check box 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 inserted a copy of the shopping cart control, and the last step simply displayed a short thank you message.

You added a control LoginView, which contained your anonymous template:

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

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

</asp:LoginView>

This displayed the password recovery control, which is displayed to aid any user who might have forgotten their password.

It was left to the code-behind to provide the meat of the example. When the page first loads, you check to see if there is anything in the cart. If there isn’t, then you make the Wizard invisible and show the nocartlabel, which informs the user that there is nothing in the cart. The second check is to see if the user identity has been authenticated. This is a test of whether or not they have logged in. If they have logged in already, you jump them past the login stage, or else you have to get them logged in first:

void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

515

Chapter 13

{

if (Profile.Cart == null)

{

NoCartlabel.Visible = true; Wizard1.Visible = false;

}

if (User.Identity.IsAuthenticated)

{

Wizard1.ActiveStepIndex = 1;

}

else

{

Wizard1.ActiveStepIndex = 0;

}

}

}

The next procedure in the code is the code that responds to the check box being altered in Step 2, the delivery address. If this box is checked, you fill the text boxes with the details stored in the user’s profile. Otherwise you leave them empty:

protected void chkUseProfileAddress_CheckedChanged( object sender, System.EventArgs e)

{

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

//we don’t want to overwrite the values

if (chkUseProfileAddress.Checked && (txtName.Text.Trim() == “”))

{

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

}

}

NextButtonClick is used to check whether the user has logged in successfully and can therefore progress to the next step of the Wizard. This step only comes into play if you are actually on the login stage at the time. You check to see if the user has been validated and, if not, you display an appropriate error message informing the user that they aren’t able to log in this time. Otherwise you validate the user:

protected void Wizard1_NextButtonClick( object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)

{

if (e.CurrentStepIndex == 0)

{

System.Web.UI.WebControls.Login l = (Login)Wizard1.FindControl(“Login1”);

if (Membership.ValidateUser(l.UserName, l.Password))

{

FormsAuthentication.SetAuthCookie(l.UserName, l.RememberMeSet);

516

E-Commerce

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;

}

}

else

{

if (!User.Identity.IsAuthenticated)

{

e.Cancel = true; Wizard1.ActiveStepIndex = 0;

}

}

}

FinishButtonClick contains perhaps the longest set of code, but it isn’t as daunting as it looks. This is where you write the user’s order to the database. You have to be able to roll this back if a mistake has occurred. You start by creating a connection string, and you create a transaction. Then you read in all of the details supplied in the checkout process into parameters. There are a lot of them! You have the member name, the delivery address, the credit card details, and the whole shopping cart total:

protected void Wizard1_FinishButtonClick( object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)

{

// Insert the order and order lines into the database SqlConnection conn = null;

SqlTransaction trans = null; SqlCommand cmd;

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, SubTotal, Discount, Total) “ +

“VALUES (@MemberName, @OrderDate, @Name, @Address, @County, @PostCode, @Country, @SubTotal, @Discount, @Total)”;

cmd.Parameters.Add(“@MemberName”, SqlDbType.VarChar, 50); cmd.Parameters.Add(“@OrderDate”, SqlDbType.DateTime);

517