Beginning asp net 2.0 with c phần 8 doc

77 321 0
Beginning asp net 2.0 with c phần 8 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

4. In the dialog box 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. Then clicking Add again and enter Step 4. Click Add one more time and enter 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. 7. From the Login section of the Toolbox, drag a Login box into the <asp:Wizard> control, as shown in Figure 13-37. 507 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 507 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 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 508 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 cre- ated, 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 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 509 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 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 510 { // 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 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 511 “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 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 512 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 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 513 Figure 13-39 Figure 13-40 Figure 13-41 514 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 514 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 num- ber 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 for- gotten 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 E-Commerce 16_042583 ch13.qxd 4/4/06 2:50 PM Page 515 { 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 Chapter 13 16_042583 ch13.qxd 4/4/06 2:50 PM Page 516 [...]... 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,... SQL to be executed can be wrapped in a stored procedure and the stored procedure name used to execute it Consider this SqlDataSource: Using a stored procedure, the code would look... e-mail them) E-Commerce ❑ Improving the shopping cart: Make the shopping cart visible at all times ❑ Improving the checkout process: Make the checkout process simpler so that it can be achieved in as few clicks as possible Summar y Hopefully this rather intense chapter hasn’t scared you away E-commerce is a lengthy and complex process — however, the new features of ASP. NET 2.0 make it approachable and... the exception // Tools.log(“An error occurred while creating the order”, SqlEx) throw new Exception(“An error occurred while creating the order”, SqlEx); } Last, you close the connection and you clear the cart profile of the items if the transaction has been successful: finally { if (conn != null) conn.Close(); } // we will only reach here if the order has been created sucessfully // so clear the cart... Explorer, close the database connection by right-clicking WroxUnited.mdf and selecting the Close Connection menu item Command SelectCommand usp_NewsByID UpdateCommand usp_NewsUpdate InsertCommand usp_NewsInsert DeleteCommand 534 Stored Procedure usp_NewsDelete Performance 13 Add the following attributes to SqlDataSource2: SelectCommandType=”StoredProcedure” UpdateCommandType=”StoredProcedure” InsertCommandType=”StoredProcedure”... brackets or not 4 Save and close the procedure 533 Chapter 14 5 Create another new procedure, replacing the default text with the following code: CREATE PROCEDURE dbo.usp_NewsUpdate @DateToShow datetime, @Description text, @PictureUrl varchar(50), @Category varchar(50), @Title varchar(50), @NewsID int AS UPDATE News SET DateToShow = @DateToShow, Description = @Description, PictureUrl = @PictureUrl, Category... details However, without these pages, you would not be able to shop effectively With a catalog working, you could add the cart The cart consisted of two objects: the CartItem object (one for each item selected by the user from the catalog and the ShoppingCart object, (which contained a bundle of CartItem objects) To enable the shopping cart, you added Insert, Update, and Delete methods, which allowed you... can be done automatically by way of the data source controls, or manually though the objects in the System.Data namespaces One of these objects applies to connecting to a database — for SQL Server or SQL Server Express, that object is the SqlConnection In general, databases are limited to the number of connections they can have Each connection takes resources and may stop another application from connecting,... code would look like this: From the code perspective, this is already better for two reasons: it makes the code neater and easier to read; and it abstracts the SQL into a central place, the database Having the... doesn’t necessarily store that much data For example, PictureUrl is declared as varchar(50), but if the PictureUrl only contains 10 characters, then only 10 characters are stored There is another data type for handling strings, char, which does store all characters So if PictureUrl was declared as char(50) and only 10 were used, what is stored is the actual string followed by 40 spaces Those spaces would . a customer bought a replica kit in 20 04, when the 20 05 version comes out, it might be good to e-mail them). 5 20 Chapter 13 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 5 20 ❑ Improving the shopping cart:. Namespace =”Wrox.Commerce”%> 509 E-Commerce 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 509 15. Save the design. 16. Go to Solution Explorer, and select checkout.aspx.cs. 17. Add the following code-behind. section of the Toolbox, drag a Login box into the < ;asp: Wizard> control, as shown in Figure 13-37. 507 E-Commerce 16 _0 425 83 ch13.qxd 4/4 /06 2: 50 PM Page 507 Figure 13-37 8. Click Source

Ngày đăng: 09/08/2014, 18:22

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan