1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 1.0 Special Edition- P45 pdf

40 260 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 40
Dung lượng 531,12 KB

Nội dung

if (Request.Params["ProductCode"] != null) { cart.AddShoppingCartItem( GetCustomerID(), Request.Params["ProductCode"]); } PopulateShoppingCartList(); UpdateSelectedItemStatus(); } } The ProductCode parameter is optional because the shopping cart can also be displayed by clicking on the shopping cart symbol shown in the navigation bar. If this is the method by which the page is accessed, then we don't want to add any items to the shopping cart. The CustomerID function used here returns the unique ID for the current customer, which is then passed as a parameter to the AddShoppingCartItem function. If the customer has not registered and logged in, the ID returned by the CustomerID function is the current ASP.NET session ID; otherwise it is the current user name: String GetCustomerID() { if (User.Identity.Name != "") { return Context.User.Identity.Name; } else { if (Session["AnonUID"] == null) Session["AnonUID"] = Guid.NewGuid(); return Session["AnonUID"].ToString(); } } The implementation of the AddShoppingCartItem method of the CartDB business object is worth reviewing at this point, because it contains two interesting sections of code: public void AddShoppingCartItem(string customerName, string productCode) { DataSet previousItem = GetShoppingCartItem(customerName, productCode); if (previousItem.Tables[0].Rows.Count > 0) { UpdateShoppingCartItem((int) previousItem.Tables[0].Rows[0]["ShoppingCartID"], ((int)previousItem.Tables[0].Rows[0]["Quantity"]) + 1); } else { IBuyAdventure.ProductsDB products; products = new IBuyAdventure.ProductsDB(m_ConnectionString); DataSet productDetails = products.GetProduct(productCode); String description = (String) productDetails.Tables[0].Rows[0]["ProductDescription"]; String productName = (String) productDetails.Tables[0].Rows[0]["ProductName"]; double unitPrice = (double) productDetails.Tables[0].Rows[0]["UnitPrice"]; String insertStatement = "INSERT INTO ShoppingCarts (ProductCode, " + "ProductName, Description, UnitPrice, CustomerName, " + "Quantity) values ('" + productCode + "', @productName, " + "@description, " + unitPrice + ", '" + customerName + "' , 1)"; SqlConnection myConnection = new SqlConnection(m_ConnectionString); SqlCommand myCommand = new SqlCommand(insertStatement, myConnection); myCommand.Parameters.Add( new SqlParameter("@ProductName", SqlDbType.VarChar, 50)); myCommand.Parameters["@ProductName"].Value = productName ; myCommand.Parameters.Add( new SqlParameter("@description", SqlDbType.VarChar, 255)); myCommand.Parameters["@description"].Value = description; myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close(); } } The first interesting point about the code is that it checks if the item is already in the shopping cart by calling GetShoppingCartItem, and if it does already exist, it simply increases the quantity for that item and updates it in the database using the UpdateShoppingCartItem function. The second interesting point comes about because the ADO.NET code that adds a new cart item uses the SqlCommand class. Since the IBuyAdventure product descriptions can contain single quotes, we need to ensure that any quotes within the description do not conflict with the quotes used to delimit the field. To do this we use the SqlCommand object to execute our query, making use of parameters in our SQL, like @description, to avoid any conflict. The values for the parameters are then specified using the Parameters collections of the SqlCommand object: myCommand.Parameters.Add( new SqlParameter("@description", SqlDbType.VarChar, 255)); Once the SQL statement is built, the command object can be connected, the statement executed, and then disconnected: myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close(); Displaying the Shopping Cart and Changing an Order The shopping cart allows customers to specify a quantity for each product in the cart, and displays the price per item, and total price for the quantity ordered. At any time, a customer can change the order quantity or remove one or more items from the cart by checking the Remove box and clicking Recalculate. An item will also be removed if the customer enters a quantity of zero. To implement this functionality, we have used the asp:Repeater control. Implementing this functionality in straight ASP pages isn't an easy task, and requires significant code. In ASP.NET it is fairly simple. The asp:Repeater control was used as the base for building the shopping cart as it doesn't need to use any of the built-in selection and editing functionality provided by the other list controls such as the asp:DataList and asp:DataGrid. All of the items are always checked and processed during a postback, and the cart contents (the dataset bound to the asp:Repeater control) is always generated during each postback. The asp:Repeater control is also 'lookless' (it only generates the HTML element that we specify using templates), which fits in well with the design our shopping cart page - we don't need a complete table to be generated by the control (the table's start and header rows are part of the static HTML). Data Source/HTML/ASPX for the Shopping Cart The shopping cart data source is provided by the CartDB component, which is bound to the myList asp:repeater control: void PopulateShoppingCartList() { IBuyAdventure.CartDB cart = new IBuyAdventure.CartDB(getConnStr()); DataSet ds = cart.GetShoppingCartItems(GetCustomerID()); MyList.DataSource = ds; MyList.DataBind(); The HTML used to render the shopping cart, including the ItemTemplate rendered for each item in the MyList.DataSource is shown next, although some parts of the HTML page formatting (for example the font settings) have been removed to keep it short and easily readable: <table colspan="8" cellpadding="5" border="0" valign="top"> <tr valign="top"> <td align="center" bgcolor="#800000">Remove</td> <td align="center" bgcolor="#800000">Product Code</td> <td align="center" bgcolor="#800000">Product Name</td> <td align="center" bgcolor="#800000" width="250">Description</td> <td align="center" bgcolor="#800000">Quantity</td> <td align="center" bgcolor="#800000">Unit Price</td> <td align="center" bgcolor="#800000">Unit Total</td> </tr> <asp:Repeater id="MyList" runat="server"> <itemtemplate> <tr> <td align="center" bgcolor="#f7efde"> <asp:checkbox id="Remove" runat="server" /> </td> <td align="center" bgcolor="#f7efde"> <input id="ShoppingCartID" type="hidden" value= '<%#DataBinder.Eval(Container.DataItem,"ShoppingCartID", "{0:g}")%>' runat="server" /> <%#DataBinder.Eval(Container.DataItem, "ProductCode")%> </td> <td align="center" bgcolor="#f7efde"> <%#DataBinder.Eval(Container.DataItem, "ProductName")%> </td> <td align="center" bgcolor="#f7efde"> <%#DataBinder.Eval(Container.DataItem, "Description")%> </td> <td align="center" bgcolor="#f7efde"> <asp:textbox id="Quantity" text='<%#DataBinder.Eval( Container.DataItem, "Quantity", "{0:g}")%>' width="30" runat="server" /> </td> <td align="center" bgcolor="#f7efde"> <asp:label id="UnitPrice" runat="server"> <%#DataBinder.Eval(Container.DataItem, "UnitPrice", "{0:C}")%> </asp:label> </td> <td align="center" bgcolor="#f7efde"> <%# String.Format("{0:C}", (((int)DataBinder.Eval(Container.DataItem, "Quantity")) * ((double) DataBinder.Eval(Container.DataItem, "UnitPrice")) )) %> </td> </tr> </itemtemplate> </asp:Repeater> <tr> <td colspan="6"></td> <td colspan="2" align="right"> Total is <%=String.Format(fTotal.ToString(), "{0:C}") %> </td> </tr> <tr> <td colspan="8" align="right"> <asp:button text="Recalculate" OnClick="Recalculate_Click" runat="server" /> <asp:button text="Go To Checkout" OnClick="Checkout_Click" runat="server" /> </td> </tr> </table> The code shown above is similar to that which we have seen earlier, so it should be easy to follow. The important point to note is that all the fields that need to be available when a postback occurs are marked with the id and runat="server" attributes. When the customer causes a postback by pressing the Recalculate button, the ASP.NET page can access the Remove checkbox control, the database cart ID hidden field control, and the Quantity field control for each list item, and update the database accordingly. For each row in the ShoppingCarts table for this customer, the asp:Repeater control will contain a list item containing these three controls, which can be programmatically accessed: To associate each list item within the asp:Repeater control with a specific database cart item, a hidden field is used to store the unique ID for the entry: <input id="ShoppingCartID" type="hidden" value='<%#DataBinder.Eval( Container.DataItem, "ShoppingCartID", " {0:g}") %>' runat="server"> As discussed earlier, the contents of the shopping cart are always stored in the SQL Server table named ShoppingCarts, and manipulated using the business object named CartDB. To populate the shopping cart with items, the ASP.NET page invokes the PopulateShoppingCartList function. This occurs when the page is loaded for the first time (that is, when Page.PostBack is false), and after each postback that leads to the database being modified - items added, deleted, or changed. To retrieve the cart items and data bind the asp:Repeater control, this function uses the GetShoppingCartItems method of the CartDB object: void PopulateShoppingCartList() { IBuyAdventure.CartDB cart = new IBuyAdventure.CartDB(getConnStr()); DataSet ds = cart.GetShoppingCartItems(GetCustomerID()); MyList.DataSource = ds; MyList.DataBind(); Once the list is bound, the dataset is then enumerated to calculate the total value of the items within the cart: DataTable dt; dt = ds.Tables[0]; int lIndex; double UnitPrice; int Quantity; for ( lIndex =0; lIndex < dt.Rows.Count; lIndex++ ) { [...]... calling the DeletesOrdersForCustomer function provided by the OrdersDB object Summary That's it, your first ASP.NET e-commerce application! In this chapter we have seen how clean and easy it is to write an ecommerce application using ASP.NET The rich serverside control and event model makes ASP.NET development much more like traditional Visual Basic event-based programming, which dramatically reduces... Classes that define the data transmission protocols between ASP.NET Web System.Web.Services.Protocols Services and clients Scott Guthrie's Top Performance Tips With thanks to Scott Guthrie, the inventor of ASP Here are Scott's top tips for maximizing performance of your ASP.NET applications, plus a few things to watch out for In general, ASP.NET pages take longer to respond on the first 'hit' due... server System.Web.Configuration Classes that are used to configure ASP.NET applications System.Web.Hosting Classes for working with application domains, worker requests and interfacing with IIS System.Web.Mail Classes for creating and managing SMTP email messages and attachments System.Web.Security Classes that implement security in ASP.NET applications Web Forms Application Namespaces Classes and interfaces... Remember that '?' means 'anonymous users' Using a specific directory to contain secure items is a simple yet flexible way of implementing security in ASP.NET applications When the ASP.NET runtime determines that an anonymous user is trying to access a page in a secure directory of our application, it knows which page to display because the web.config file located... redirection code is actually implemented by the Login page we have created, and does require some extra work on our part We will see this next Handling Page Return Navigation During Authentication When the ASP.NET runtime determines that a secure item has been accessed, it will redirect the user to our Login page, and include a query string parameter named ReturnURL As the name suggests, this is the page... System.Web.UI.Design.WebControls Classes for extending design-time support for Web Controls Classes for creating HTML server controls that map directly to standard HTML System.Web.UI.HtmlControls elements Classes for creating ASP.NET Web Controls, which provide a consistent and System.Web.UI.WebControls abstracted interface Web Service Application Namespaces System.Web.Services Classes for building and using Web Services Classes... (also called cookie-based security), as introduced in Chapter 14 When a customer hits any of the pages that require authentication, if they haven't already signed in, the page login.aspx is displayed: The ASP.NET runtime knows to display this page if a user is not logged in because all pages that require authentication are located in a directory called SECURE It contains a web.config file, which specifies... with very little code may provide around the same performance as ASP 3.0 pages, more complex pages are actually a lot faster due to the compilation of the code they contain The best cost/benefit for an ASP.NET server is a two-processor machine With ADO.NET data access, a four-processor machine can be beneficial, but is far more costly - two to three thousand dollars will buy a good twin-processor server, . bgcolor="# 800 000 ">Product Code</td> <td align="center" bgcolor="# 800 000 ">Product Name</td> <td align="center" bgcolor="# 800 000 ". width="2 50& quot;>Description</td> <td align="center" bgcolor="# 800 000 ">Quantity</td> <td align="center" bgcolor="# 800 000 ">Unit. (previousItem.Tables [0] .Rows.Count > 0) { UpdateShoppingCartItem((int) previousItem.Tables [0] .Rows [0] ["ShoppingCartID"], ((int)previousItem.Tables [0] .Rows [0] ["Quantity"]) + 1) ;

Ngày đăng: 03/07/2014, 07:20

TỪ KHÓA LIÊN QUAN