ASP.NET at Work: Building 10 Enterprise Projects PHẦN 7 potx

64 237 0
ASP.NET at Work: Building 10 Enterprise Projects PHẦN 7 potx

Đ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

Creating _SmallCart.ascx The _SmallCart user control displays the product name, quantity, and total price of the products that the user has decided to purchase. In the _ProductsList user control that you created earlier, I highlighted the code in bold that passes the ProductID and the AddToCart action in the query string. The code-behind for the _SmallCart user control checks the query string, and if the AddToCart action exists, it calls a method to update the ShoppingCart table in the database, return a new SQLDataReader object contain- ing this user’s cart data, and binds that data to the DataList control. This user control uses the FooterTemplate item to display a Check Out image. Once the online store is completed, the _SmallCart user control is displayed on each page the user views up until the point of checking out. When the user decides he or she is done shopping, he or she can click the Check Out image, which passes the CheckOut action in the query string and redirects to the CheckOut.aspx page. Listing 6.26 is the complete HTML code for the _SmallCart user control. <%@ Control Language=”vb” AutoEventWireup=”false” _ Codebehind=”_SmallCart.ascx.vb” _ Inherits=”project06.C_SmallCart” _ TargetSchema=”http://schemas.microsoft.com/intellisense/ie5”%> <asp:DataList id=”DataList1” runat=”server” BackColor=”LemonChiffon” BorderColor=”DarkGreen” BorderWidth=”1px” BorderStyle=”Groove”> <HeaderTemplate> <IMG src=”images/carttop.gif”> </HeaderTemplate> <FooterTemplate> <a href=”checkout.aspx?Action=CheckOut”> <IMG src=”images/cartbottom.gif”> </a> </FooterTemplate> <ItemTemplate> <TABLE border=”0”> <TR> <TD class=”SmallCart” width=”5”> <%# DataBinder.Eval(Container.DataItem, “Quantity”)%> </TD> <TD class=”SmallCart” align=”left” width=”120”> <%# DataBinder.Eval(Container.DataItem, “ProductName”)%> </TD> <TD class=”SmallCart” align=”right” width=”45”> <%# DataBinder.Eval(Container.DataItem, “TotalDue”, “{0:c}”) %> </TD> </TR> </TABLE> </ItemTemplate> </asp:DataList> Listing 6.26 Code for _SmallCart.ascx user control Building the Online Store Application 367 The code that updates the ShoppingCart table in the database is encapsulated in the Page_Load event. When a user clicks an item in the _ProductsList user control, three items are passed in the query string: Action, CategoryID, and ProductID. When a user clicks the Add To Cart image, the query string will look something like this: ProductList.aspx?productID=55&CategoryID=6&selection=3&Action=AddToCart The Page_Load event reads the Action parameter in the query string, and if the Action parameter is AddToCart, then the UpdateCartQuantity method is called from a new instance of the ShoppingCart class. Once the item is added to the cart, the GetCart method is called, and the DataSource property of the DataList control is set to the SQL- DataReader object that the method returns. Then the DataBind method is called, and the shopping cart display is updated. Listing 6.27 is the code-behind for the _SmallCart user control. Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ Declare a new instance of the ShoppingCart class Dim s As Proj06Web.ShoppingCart = _ New Proj06Web.ShoppingCart() ‘ ‘ No matter what, we need a shopping cartID Dim cartID As String = s.GetCartID() If Request.Params(“Action”) = “AddToCart” Then ‘ ‘ Need to get the query string and add the ‘ items to the page Dim strCat = Request.Params(“CategoryID”) Dim strProd = Request.Params(“ProductID”) ‘ ‘ When the page loads on the small cart, ‘ the quantity ‘ is always 1, since this only gets called from the AddToCart ‘ image on the ProductsList page s.UpdateCartQuantity(CInt(strProd), 1, cartID, False) End If ‘ ‘ Load Products list into the DataList control ‘ Calls stored proc sp_Shopping_Cart If cartID <> “” Then With DataList1 .DataSource = s.GetCart(cartID) .DataBind() End With End If End Sub Listing 6.27 _SmallCart.ascx.vb code 368 Project 6 Figure 6.7 _SmallCart user control. Figure 6.7 displays an example of the _SmallCart user control once a few items are added to it. Creating _BigCart.ascx The _BigCart.ascx user control is displayed to the shopper during the checkout process. This user control is a little more complicated than the previous user controls you have created, mainly because it includes a Checkbox control that the user can click to indicate the removal of an item from the shopping cart and a Textbox control that the user can use to change the quantity of the items being purchased. The design of the user control is not the hard part; it is the actual code-behind that is a little more com- plex than the data-binding process that occurs during the Page_Load event in the pre- vious controls that we created. Listing 6.28 is the partial HTML code for the _BigCart user control. The listing is quite long, so I thought it better to just display the data-binding code, which is really the important part. To give you an idea of what the grid looks like at design time, Fig- ure 6.8 shows you the complete grid in the IDE. When we explore the code-behind, you will see the code that handles the events for the buttons on the user control. There is also a Label control on the form that will output any error information back to the user if an error occurs during the update process the cart goes through when an item is deleted or a quantity is changed. Figure 6.8 _BigCart.ascx at design time. Building the Online Store Application 369 <asp:datagrid id=”DataGrid1” Height=”118px” AutoGenerateColumns=”False” runat=”server” CssClass=”checkout” Width=”615px” DataKeyField=”Quantity”> <Columns> <asp:TemplateColumn HeaderText=”Remove”> <ItemTemplate> <asp:CheckBox id=”Delete” runat=”server” /> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText=”Quantity”> <ItemTemplate> <asp:TextBox id=Quantity runat=”server” Text=’<%# DataBinder.Eval(Container.DataItem, “Quantity”)%>’ width=”40px” Columns=”4”> </asp:TextBox> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn> <ItemTemplate> <asp:Label id=ProductID runat=”server” Text=’<%# DataBinder.Eval(Container.DataItem, “ProductID”)%>’ Visible=”False” Width=”298px”> </asp:Label> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn DataField=”ProductName” HeaderText=”Product Name”> </asp:BoundColumn> <asp:BoundColumn DataField=”QuantityPerUnit” HeaderText=”Qty Per Unit”> </asp:BoundColumn> <asp:BoundColumn DataField=”UnitPrice” HeaderText=”Unit Price” DataFormatString=”{0:c}”> </asp:BoundColumn> <asp:BoundColumn DataField=”TotalDue” HeaderText=”Total Due” DataFormatString=”{0:c}”> </asp:BoundColumn> </Columns> </asp:datagrid></TD> Listing 6.28 _BigCart.ascx code 370 Project 6 The code-behind for the _BigCart user control is a little more complicated due to the fact that we are allowing the user to modify each row in the grid. Once the user chooses to either delete an item or modify the quantity, he or she clicks the Update Cart button, and the ShoppingCart table in the database is updated. If you were to write this code in ASP, it could be a little more complicated, but since the DataGrid control has some additional functionality to make processes like this possible, the code you need to write is simple. We will break down the code-behind for this user control by each event that occurs, since the code is quite lengthy and deserves proper explaining. Listing 6.29 is the code for the Page_Load event. Like each Page_Load event up until now, this is straightforward data binding. A new instance of the ShoppingCart class is created, and if there is data in the ShoppingCart table, then the SQLDataReader that is returned is bound to the DataGrid grid control by setting the DataSource property and calling the DataBind method. Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then Dim CartID As String = _ Request.Cookies(“CartID”).Value.ToString() ‘ ‘ If the CartID is not empty, then fill the DataGrid with ‘ the current cart data in the database If CartID <> “” Then Dim s As Proj06Web.ShoppingCart = _ New Proj06Web.ShoppingCart() ‘ Call the GetCart method and bind the ‘ results to the DataGrid DataGrid1.DataSource = _ s.GetCart(CartID) DataGrid1.DataBind() ‘ Display the Total Order Amount in the label Label1.Text = “Total Order Amount: “ _ & FormatNumber(s.GetCartSum(CartID), 2) End If End If End Sub Listing 6.29 Page_Load event for the _BigCart.ascx The UpdateButton control on the form handles updating the ShoppingCart table with any changes that the user makes to the items displayed in the grid. There are three items for each row in the grid that are important to this method: the ProductID field, the Delete check box, and the Quantity text box. In order to determine if the user has either selected the Delete check box or modified the value in the Quantity text box, you need to iterate through the collection of rows in the grid and use the FindControl method of Items collection in the grid. Using the FindControl method for each row, Building the Online Store Application 371 compare the value of the original quantity in the textbox to the current quantity. This is accomplished by setting the DataKeyField property equal to the item in the grid that you want to key on. In Listing 6.28, you defined the DataKeyField for the DataGrid control with the following code: <asp:datagrid id=”DataGrid1” Height=”118px” AutoGenerateColumns=”False” runat=”server” CssClass=”checkout” Width=”615px” DataKeyField=”Quantity”> Because the DataGrid control has a DataKeyField property, you are saved the addi- tional work of creating hidden fields or otherwise figuring out how to keep track of values that have changed. This means that the actual data-access code that updates or deletes items from the cart only occurs if the user is requesting it. To determine if the user is requesting to remove a product from the shopping cart, the checked property of the Checkbox control is examined. If the property is True, then the RemoveFromCart method is called, the ProductID for that row is passed, and the item is removed. Listing 6.30 is the complete code for the UpdateButton_Click event. Private Sub UpdateButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles UpdateButton.Click ‘ ‘ Make sure the ErrorMessage label is not visible ErrorMessage.Visible = False ‘ Dim CartID As String = _ Request.Cookies(“CartID”).Value.ToString Dim s As Proj06Web.ShoppingCart = _ New Proj06Web.ShoppingCart() Dim Looper As Long Dim strMsg As String Try ‘ Loop thru the collection of items in the DataGrid ‘ For Looper = 0 To DataGrid1.Items.Count - 1 ‘ Declare a variable for each type of control ‘ that you need to evaluate ‘ Dim DeletedCheckbox As CheckBox Dim UpdatedQty As TextBox Dim ProductID As Label ‘ Set the controls that need to be evaluated to each type that ‘ is in the DataGrid using the FindControl method ProductID = DataGrid1.Items(Looper).FindControl(“ProductID”) DeletedCheckbox = DataGrid1.Items(Looper).FindControl(“Delete”) UpdatedQty = DataGrid1.Items(Looper).FindControl(“Quantity”) ‘ Listing 6.30 UpdateButton_Click event handler 372 Project 6 TEAMFLY Team-Fly ® ‘ Make sure the value in the textbox is a number ‘ before updating the qty If IsNumeric(UpdatedQty.Text) And CInt(UpdatedQty.Text) > 0 Then If Convert.ToInt32(UpdatedQty.Text) <> _ Convert.ToInt32(DataGrid1.DataKeys(Looper)) Then ‘ Call the UpdateCartQuantity method if the number in the ‘ Quantity Texbox control is different than the original value s.UpdateCartQuantity(CInt(ProductID.Text), _ CInt(UpdatedQty.Text), CartID, True) End If End If ‘ If the user put a 0 in the Qty box, then make it a Delete If DeletedCheckbox.Checked = True _ Or CInt(UpdatedQty.Text) = 0 Then ‘ Call the RemoveFromCart method to delete the Cart Item s.RemoveFromCart(CInt(ProductID.Text), CartID) End If Next Catch ex1 As Exception ‘ If an error occurs, make the ErrorMessage label visible ‘ and fill it with the error string With ErrorMessage .Visible = True .Text = ex1.Message.ToString End With Finally ‘ No matter what, the cart needs to be filled with the current cart ‘ data, even if an error occured With DataGrid1 .DataSource = s.GetCart(Request.Cookies(“CartID”).Value.ToString) .DataBind() End With ‘ Display the Total Order Amount in the Label control Label1.Text = “Total Order Amount: “ & _ FormatNumber(s.GetCartSum(CartID), 2) End Try End Sub Listing 6.30 UpdateButton_Click event handler (continued) Creating _CustomerDetailsAdd.ascx The _CustomerDetails user control is a basic data entry form that enables users to add or update their personal information. This user control introduces validation controls that notify users if they have not entered the correct data in the data entry fields. Building the Online Store Application 373 Listing 6.31 is a partial listing of the _CustomerDetails user control demonstrating the different types of validation controls in use. The RequiredFieldValidator control is straightforward. Once you add this control to your form, you specify a control to validate and an error message. The RegularExpressionValidator control is more complex and gives you complete control over the type of data that is entered into the control you want to validate. Like the RequiredFieldValidator control, you must set the ControlToValidate property to a valid control on your form. The difference is in how you validate the expression. The .NET Framework has an extensive regular-expression syntax that can be used in many different scenarios, one of them being data validation. By using the regular-expression syntax, you can define how data should look in the control. We are using regular- expression syntax to define an email address that validates the EmailTextBox control. When you add a RegularExpressionValidator control to a form, the properties dialog box gives you several options for predefined expressions, such as phone numbers for different locales, email addresses, and URLs. Most of the bases are covered with the predefined offerings, but if something does not match your needs, you can customize the property as you see fit. The third type of validation control on the user control is the CompareValidator con- trol. This control is perfectly suited for the password data entry fields. In order to make sure that the user re-enters the password in the Password2 text box, add the Com- pareValidator to the form, and set the ControlToValidate property to Password2 and the ControlToCompare property to the Password1 text box. The control will automati- cally check that both fields are the same before the data is submitted to the server for processing. <TD>Company Name:</TD> <TD><asp:textbox id=”Company” Width=”208px” runat=”server”> </asp:textbox></TD> <TD><asp:requiredfieldvalidator id=”RequiredFieldValidator1” runat=”server” ControlToValidate=”Company” ErrorMessage=”Company name required”> </asp:requiredfieldvalidator></TD> <TD>Email Address:</TD> <TD><asp:textbox id=”Email” Width=”208px” runat=”server”> </asp:textbox></TD> <TD> <asp:RegularExpressionValidator id=”RegularExpressionValidator1” runat=”server” ErrorMessage=”Invalid email address” ControlToValidate=”Email” ValidationExpression=”\w+([-+.]\w+)*@\w+([ ]\w+)*\.\w+([ ]\w+)*”> </asp:RegularExpressionValidator></TD> <TD>Re-Enter Password:</TD> <TD><asp:textbox id=”Password2” Width=”208px” runat=”server”> </asp:textbox></TD> Listing 6.31 Partial _CustomerDetailsAdd.ascx HTML 374 Project 6 Building the Online Store Application 375 <TD><asp:comparevalidator id=”CompareValidator1” runat=”server” ControlToValidate=”Password2” ErrorMessage=”Passwords do not match” ControlToCompare=”Password1”> </asp:comparevalidator></TD> Listing 6.31 Partial _CustomerDetailsAdd.ascx HTML (continued) The code-behind for the _CustomerDetailsAdd user control is contained in two events: the Page_Load event and the SaveButton_Click event. The SaveButton_Click event does the basic reading of the data in the text box controls and passes them to the AddEditCustomer method in the Customers class. This either adds new customer information or updates an existing customer’s profile. If a cookie containing the Cus- tomerID exists on the computer, then the method assumes that the user has already logged in and is attempting to update his or her profile information. If this is the case, then the AddNew Boolean value that tells the method in the class to call the Update stored procedure is set to False, ensuring that the existing data is updated and a new record is not added. If the CustomerID cookie does not exist, then the AddNew Boolean value is set to True, and the AddEditCustomer method uses the appropriate stored procedure to add a new record to the Customers table. The Page_Load event only runs if the CustomerID cookie exists on the computer. The event checks for the cookie, and if a CustomerID exists, then the user has either already logged in on this session or in a previous session. If this is the case, then the GetCustomerInfo method in the Customers class is called, and the SQLDataReader object that is returned is used to populate the controls on the page with the customer’s data. The only way the user can get to this screen is after a login attempt, so no matter what, you are guaranteed that a cookie containing the CustomerID will either exist or not exist—there is no way an order can get lost in the process of the user attempting a login or updating profile information. Listing 6.32 is the complete listing for the _Cus- tomerDetailsAdd.ascx.vb class. Private Sub SaveButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles SaveButton.Click ‘ make sure the page is valid and ‘ save the data to the database Dim c As Proj06Web.Customers = _ New Proj06Web.Customers() ‘ Set a true/false switch to determine if this ‘ is an update or an add new Dim CustID As String = _ Request.Cookies(“CustomerID”).Value.ToString ‘ Dim AddNew As Boolean If CustID = “” Then Listing 6.32 _CustomerDetailsAdd.ascx.vb AddNew = True Else AddNew = False End If ‘ If c.AddEditCustomer(Email.Text.ToString.Trim, _ Password1.Text.ToString.Trim, Company.Text.ToString.Trim, _ Contact.Text.ToString.Trim, Title.Text.ToString.Trim, _ Address.Text.ToString.Trim, City.Text.ToString.Trim, _ State.Text.ToString.Trim, PostalCode.Text.ToString.Trim, _ Country.Text.ToString.Trim, Phone.Text.ToString.Trim, _ Fax.Text.ToString.Trim, AddNew) Then ‘ ‘ Save the CustomerID as the cookie context.Response.Cookies(“CustomerID”).Value = _ Email.Text.ToString ‘ ‘ Go to the page that allows the user to verify their details Response.Redirect(“verify.aspx?CustomerID=” & _ Email.Text.ToString) End If End Sub Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim CustID As String = _ Request.Cookies(“CustomerID”).Value.ToString If CustID <> “” Then ‘ a customerID value exisits as a cookie, so the user needs ‘ to update their existing profile, and not add a new profile. Dim c As Proj06Web.Customers = _ New Proj06Web.Customers() ‘ Get the customer details, and fill the textboxes Dim rdr As SqlDataReader = _ c.GetCustomerInfo(CustID) ‘ call the Read method of the SQLDataReader object ‘ to retrieve the fields While rdr.Read Company.Text = Convert.ToString(rdr(“CompanyName”)) Contact.Text = Convert.ToString(rdr(“ContactName”)) Address.Text = Convert.ToString(rdr(“Address”)) City.Text = Convert.ToString(rdr(“City”)) State.Text = Convert.ToString(rdr(“Region”)) PostalCode.Text = Convert.ToString(rdr(“PostalCode”)) Country.Text = Convert.ToString(rdr(“Country”)) Phone.Text = Convert.ToString(rdr(“Phone”)) Fax.Text = Convert.ToString(rdr(“Fax”)) Listing 6.32 _CustomerDetailsAdd.ascx.vb (continued) 376 Project 6 [...]... later If you want to see the system operational, be sure to visit the Web site at www teamworknetwork.com I intend to keep this site running as a public-development project that you can discuss at the book’s Web site: www.10projectswithasp.net We’ll add new features as time goes on to make this site useful for everyone 391 392 Project 7 THE PROBLEM Online collaboration requires a variety of components... build Most applications have to have a user authentication method of some sort In this application, you’ll be building a structure that allows members (the term for users in this application) to be added to any number of teams Data in the project, file sharing, and discussion forum systems will all be related to the teams created by members The team leader can add and remove members at will When a member... faster than you can manually in ASP.NET Teamwork Network: The Infrastructure Building the Retrieval Stored Procedures The next set of stored procedures to build retrieve information Most of them are used in combination with ASP.NET Repeater controls, so we have to do some extra formatting in the stored procedure to save ourselves work in the Repeater control Again, let the database do the extra work, and... databases will allow you to use multiple fields together as a primary key to a table Creating the Stored Procedures This database makes heavier use of stored procedures to handle several complicated tasks directly on the server instead of retrieving lots of data to be processed manually For the features covered in this project, you will be building a total of 10 stored procedures: sp_CheckForDuplicateEMail... validation error CREATE PROCEDURE dbo.sp_CheckForDuplicateEmail @Email varchar (100 ) AS SELECT COUNT(*) As DuplicateCount FROM tblMembers WHERE Lower(Email) = Lower(@Email) Listing 7. 1 sp_CheckForDuplicateEmail The next stored procedure does basically the same thing, but with the username selected by a potential member The code for sp_CheckForDuplicateUserName is shown in Listing 7. 2 Teamwork Network: The Infrastructure... it easy to implement new features without major redesign or modification to existing code In Project 7, you’ll begin building the Team Network system, an application that will provide project tracking, file sharing, and discussion forums 389 PROJECT 7 Teamwork Network: The Infrastructure One of the more interesting aspects of the Internet is how it has made virtual corporations a reality Instead of... shown in Listing 7. 6 This stored procedure returns all the member information already formatted for display by the Repeater control We concatenate the last and first names into a new field, return a Yes or No for whether the profile is public (this routine doesn’t need to worry about team membership), and a URL that points to the member-profile viewer We’ll populate this into the repeater, and if the... These objects all build on what you did in Project 3, with a few minor changes along the way CREATE PROCEDURE dbo.sp_RetrieveTeamsByMember @MemberID int AS SELECT * FROM tblTeams WHERE fkLeaderID = @MemberID ORDER BY Name Listing 7 .10 sp_RetrieveTeamsByMember Building the Business Objects The next thing we’ll be doing is building the objects that manipulate each type of data in the system As in Project... inherit from it for each entity We have made a few minor changes to the Database and BaseServices classes to make them a bit more flexible for the type of work we need to do in this section 401 Project 7 Creating the Database Class The AtWorkUtilities.Database class code is shown in Listing 7. 11 The one change to this class is that the GetDataReader method has an optional parameter to skip the initial Read()... Design the database tables 2 Create the stored procedures used in the application 3 Build the business objects 4 Build the application’s Web pages ✄ You Will Need ✔ Windows 2000 ✔ Internet Information Server 5.0 with NET Framework installed ✔ Visual Studio NET ✔ SQL Server 2000 or 7. 0 ✔ SQL Server client utilities, including SQL Server Enterprise Manager and Query Analyzer Team-Fly® Teamwork Network: The . DataKeyField=”Quantity”> <Columns> < ;asp: TemplateColumn HeaderText=”Remove”> <ItemTemplate> < ;asp: CheckBox id=”Delete” runat=”server” /> </ItemTemplate> < /asp: TemplateColumn> < ;asp: TemplateColumn. _BigCart.ascx at design time. Building the Online Store Application 369 < ;asp: datagrid id=”DataGrid1” Height=”118px” AutoGenerateColumns=”False” runat=”server” CssClass=”checkout” Width=”615px” DataKeyField=”Quantity”> <Columns> < ;asp: TemplateColumn. Columns=”4”> < /asp: TextBox> </ItemTemplate> < /asp: TemplateColumn> < ;asp: TemplateColumn> <ItemTemplate> < ;asp: Label id=ProductID runat=”server” Text=’<%# DataBinder.Eval(Container.DataItem, “ProductID”)%>’ Visible=”False”

Ngày đăng: 12/08/2014, 08:23

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