Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Professional PHẦN 4 ppt

70 399 0
Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Professional PHẦN 4 ppt

Đ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

CHAPTER 5 ■ SEARCHING THE CATALOG 189 9. Add the newly created user control to BalloonShop.master by dragging it from the Solution Explorer and dropping it just below the CategoriesList user control (see Figure 5-4). Figure 5-4. Adding the search box to BalloonShop.master 10. Press F5 to execute the project. The search box should rest nicely in its place. Trying to search for any- thing would generate an error, however, because the Search.aspx page doesn’t exist yet. How It Works: The SearchBox Web User Control The SearchBox user control isn’t very complicated. When the visitor enters a new search string and presses Enter or clicks the Go button, the response is redirected to Search.aspx, which handles the search. Search recognizes the following query string parameters: • Search specifies the search string entered by the visitor. • AllWords specifies whether to do an all-words or an any-words search. You find its value by checking allWordsCheckBox.Checked, which returns True or False. A mighty hacker can, of course, play with the query string and change the value to something else, but our business tier contains code to guard against this kind of potential problem. • PageNumber appears only in case the number of products is larger than the number of products per page (which you saved in web.config). The Page_Load method first uses the Utilities.TieButton method, which configures the text box to “click” the Go! button when the Enter key is pressed. Details about TieButton have been presented prior to this exercise. Page_Load then checks the query string parameters and fills the search box contents accordingly. When the visitor performs a search, the page is reloaded (with a Response.Redirect to the Search.aspx page), so implicitly the Darie-Watson_4681C05.fm Page 189 Monday, September 19, 2005 9:53 AM 190 CHAPTER 5 ■ SEARCHING THE CATALOG search box contents are cleared. If you want to keep the values there (the string of the text box and the status of the check box), you must do this manually. While we’re here, note the check for the IsPostBack property of the page. After the visitor clicks the Go! button to perform a search, the SearchBox control is loaded (Page_Load executes) and the Click event handler executes, which causes a page redirect (to Search.aspx). After the redirect happens, SearchBox is loaded once again in the new page (so Page_Load executes again). This suggests two problems: • A performance problem because the Page_Load method is called twice. • Functionality problem because you actually only want to set the check box and text box values when the control is reloaded in a new page. If their values are rewritten immediately after clicking the Go! button, the user’s input would be ignored (which is bad, of course). To avoid these kind of problems, ASP.NET offers the Page.IsPostBack method, which tells you if Page_Load is executed as a result of a postback, which is true when the method is executed in response to a user clicking the Go! button or pressing Enter and false when the method is executed when the control is loaded for the first time on a new page. The first time Page_Load executes (after the button click), IsPostBack returns true. The second time Page_Load executes (the control is loaded in a fresh page), IsPostBack returns false. You don’t want to fill the contents of the search box from the query string when the page is loaded from a postback event, because it will be filled with data from the previous search. To test this, remove the if statement from Page_Load and try to do some consecutive different searches. Because playing with postback is mostly used to improve performance, we’ll cover it more seriously in the next chapter, where you’ll use this technique in more pages of BalloonShop. However, you needed to use it here to make the search functionality, well, functional. With this new theory in mind, the implementation of Page_Load in SearchBox.ascx.cs starts to make sense: protected void Page_Load(object sender, EventArgs e) { // don't repopulate control on postbacks if (!IsPostBack) { // tie the search text box to the Go button Utilities.TieButton(this.Page, searchTextBox, goButton); // load search box controls' values string allWords = Request.QueryString["AllWords"]; string searchString = Request.QueryString["Search"]; if (allWords != null) allWordsCheckBox.Checked = (allWords.ToUpper() == "TRUE"); if (searchString != null) searchTextBox.Text = searchString; } } Darie-Watson_4681C05.fm Page 190 Monday, September 19, 2005 9:53 AM CHAPTER 5 ■ SEARCHING THE CATALOG 191 Displaying the Search Results Now you’ll create the Web Form that displays the search results. To simplify the work, you’ll reuse the ProductsList user control to display the actual list of products. This control is currently listing products for the main page, for departments, and for categories. Of course, if you want to have the searched products displayed in another format, you need to create another user control. In the following exercise, you’ll create the Search.aspx Web Form and update ProductsList. Exercise: Displaying Search Results 1. Let’s create a new Web Form in the root of the BalloonShop folder. Right-click the BalloonShop root entry in Solution Explorer and select Add New Item. In the Add New Item dialog box, write Search.aspx for the name, make sure the two check boxes are selected and that the language is Visual C#, and click Add. 2. In the dialog box that opens, select the BalloonShop.master Master Page and click OK. 3. Switch Search.aspx to Design View, add two Label controls, and then drag ProductsList.ascx from Solution Explorer to the Content area, as shown in Figure 5-5. Figure 5-5. Creating Search.aspx in Design View Darie-Watson_4681C05.fm Page 191 Monday, September 19, 2005 9:53 AM 192 CHAPTER 5 ■ SEARCHING THE CATALOG 4. Clear the Text property of the Label controls. Set the name of the first label to titleLabel. The second label should be named descriptionLabel. 5. Set the CssClass property of the first Label control to CatalogTitle. Set the CssClass property of the second label to CatalogDescription. The HTML code of the control should be like this, at this moment: <%@ Page Language="C#" MasterPageFile="~/BalloonShop.master" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" Title="Untitled Page" %> <%@ Register Src="UserControls/ProductsList.ascx" TagName= "ProductsList" TagPrefix="uc1" %> <asp:Content ID="Content1" ContentPlaceHolderID= "contentPlaceHolder" Runat="Server"> <asp:Label ID="titleLabel" runat="server" CssClass="CatalogTitle"> </asp:Label><br /> <asp:Label ID="descriptionLabel" runat="server" CssClass= "CatalogDescription"> </asp:Label><br /><br /> <uc1:productslist id="ProductsList1" runat="server"></uc1:productslist> </asp:Content> 6. Go to the code file now and edit Page_Load like this: public partial class Search : System.Web.UI.Page { // Fill the form with data protected void Page_Load(object sender, EventArgs e) { // fill the table contents string searchString = Request.QueryString["Search"]; titleLabel.Text = "Product Search"; descriptionLabel.Text = "You searched for <font color=\"red\">" + searchString + "</font>."; // set the title of the page this.Title = BalloonShopConfiguration.SiteName + " : Product Search : " + searchString; } } 7. Finally, update the code-behind file of ProductsList.ascx to recognize the Search query string parameter and perform a product search in case the parameter is found: private void PopulateControls() { // Retrieve DepartmentID from the query string string departmentId = Request.QueryString["DepartmentID"]; // Retrieve CategoryID from the query string Darie-Watson_4681C05.fm Page 192 Monday, September 19, 2005 9:53 AM CHAPTER 5 ■ SEARCHING THE CATALOG 193 string categoryId = Request.QueryString["CategoryID"]; // Retrieve Page from the query string string page = Request.QueryString["Page"]; if (page == null) page = "1"; // Retrieve Search string from query string string searchString = Request.QueryString["Search"]; // How many pages of products? int howManyPages = 1; // If performing a product search if (searchString != null) { // Retrieve AllWords from query string string allWords = Request.QueryString["AllWords"]; // Perform search list.DataSource = CatalogAccess.Search(searchString, allWords, page, out howManyPages); list.DataBind(); } // If browsing a category else if (categoryId != null) { 8. Press F5 to execute the project. Type love in the search text box to get an output similar to Figure 5-6. Darie-Watson_4681C05.fm Page 193 Monday, September 19, 2005 9:53 AM 194 CHAPTER 5 ■ SEARCHING THE CATALOG Figure 5-6. Searching for love How It Works: Displaying Search Results You’ve now finished implementing the search functionality of the catalog. Although you had quite a bit to write, the code wasn’t that complicated, was it? The single important detail of this exercise was calling the business tier CatalogAccess.Search method to get the search results and display them: // If performing a product search if (searchString != null) { // Retrieve AllWords from query string string allWords = Request.QueryString["AllWords"]; // Perform search list.DataSource = CatalogAccess.Search(searchString, allWords, page, out howManyPages); list.DataBind(); } Darie-Watson_4681C05.fm Page 194 Monday, September 19, 2005 9:53 AM CHAPTER 5 ■ SEARCHING THE CATALOG 195 Make sure to have a closer look at all the code that makes the product searching work. If you understand it correctly, you can easily update the code to make it work best for your particular solutions. Searching Smarter Okay, the search feature is working fine. Do some tests with both all-words and any-words modes to ensure that the search feature really does work. You’ll notice that it’s fast, too. The major problem with the search feature is that it doesn’t recognize similar word forms. If you search for “balloon,” you’ll be shown ten pages of results, but if you search for “balloons,” you’ll get only one matching product. Depending on your client’s requests, this might not be acceptable. The two solutions to this problem are to either search using SOUNDEX or search using SQL Server’s Full Text Search. SOUNDEX is an SQL Server function that allows you to check if two English words sound the same (phonetical searching). SOUNDEX was initially created to find similar person names— SOUNDEX returns the same value for, say, Charlie and Charly. Checking the SOUNDEX results for two strings reveals whether they sound the same or not. As a quick test, run these queries using SQL Server Express Manager: SELECT SOUNDEX('Charly') SELECT SOUNDEX('Charlie') In both cases, the result should be C640. ■Note Using SOUNDEX isn’t exactly the ideal search solution (which is still Full Text Search), because it doesn’t offer features such as matching different verb tenses, plurals, words located in close proximity, and other advanced options. The SOUNDEX value of a string is calculated based on the first portion of that string, and the remaining characters are ignored. For more details about how SOUNDEX works, please do a Google search on “soundex algorithm.” SQL Server has another related function called DIFFERENCE, which returns the phonetical difference between two words. The return value ranges from 0 to 4: 0 indicates little or no similarity, and 4 indicates strong similarity or identical values. See more details about DIFFERENCE and SOUNDEX in SQL Server 2005 Books Online. However, searching smarter equals searching slower. To improve the search functionality using SOUNDEX, you’ll need to change the WordCount function. The SearchCatalog stored procedure doesn’t need to change! (nice one, right?) Unfortunately, in WordCount, when using SOUNDEX you must manually split the phrase into separate words and compare their SOUNDEX value to the SOUNDEX value of the word you’re searching for. This isn’t very fast. In tests, we discovered that the new version of WordCount is about five times slower than the previously presented one. However, if the business has grown large enough and the SQL Darie-Watson_4681C05.fm Page 195 Monday, September 19, 2005 9:53 AM 8213592a117456a340854d18cee57603 196 CHAPTER 5 ■ SEARCHING THE CATALOG Server can’t successfully deal any more with client requests, this is an indication that a commercial version of SQL Server should probably be purchased (which also comes with the advanced Full-Text Search functionality). ■Note The main performance penalty in this version of WordCount isn’t because of the SOUNDEX (or DIFFERENCE) calls, as you might think. Manually splitting the phrase into separate words is what takes a lot of time. The WordCount algorithm solution you applied earlier using the REPLACE function was cool and fast, but it can’t be used any more. After all that, here’s the code for the “smarter” version of WordCount. Check the comments to understand the functionality: CREATE FUNCTION dbo.WordCount (@Word VARCHAR(20), @Phrase VARCHAR(1000)) RETURNS SMALLINT AS BEGIN /* If @Word or @Phrase is NULL, the function returns 0 */ IF @Word IS NULL OR @Phrase IS NULL RETURN 0 /* Calculate and store the SOUNDEX value of the word */ DECLARE @SoundexWord CHAR(4) SELECT @SoundexWord = SOUNDEX(@Word) /* Eliminate bogus characters from phrase */ SELECT @Phrase = REPLACE(@Phrase, ',', ' ') SELECT @Phrase = REPLACE(@Phrase, '.', ' ') SELECT @Phrase = REPLACE(@Phrase, '!', ' ') SELECT @Phrase = REPLACE(@Phrase, '?', ' ') SELECT @Phrase = REPLACE(@Phrase, ';', ' ') SELECT @Phrase = REPLACE(@Phrase, '-', ' ') /* Remove trailing spaces. Necessary because LEN doesn't calculate trailing spaces */ SELECT @Phrase = RTRIM(@Phrase) /* Check every word in the phrase */ DECLARE @NextSpacePos SMALLINT DECLARE @ExtractedWord VARCHAR(20) DECLARE @Matches SMALLINT /* This variable keeps the number of matches */ Darie-Watson_4681C05.fm Page 196 Monday, September 19, 2005 9:53 AM CHAPTER 5 ■ SEARCHING THE CATALOG 197 SELECT @Matches = 0 /* Analyze the phrase word by word */ WHILE LEN(@Phrase)>0 BEGIN SELECT @NextSpacePos = CHARINDEX(' ', @Phrase) IF @NextSpacePos = 0 BEGIN SELECT @ExtractedWord = @Phrase SELECT @Phrase='' END ELSE BEGIN SELECT @ExtractedWord = LEFT(@Phrase, @NextSpacePos-1) SELECT @Phrase = RIGHT(@Phrase, LEN(@Phrase)-@NextSpacePos) END /* If there’s a match */ IF @SoundexWord = SOUNDEX(@ExtractedWord) SELECT @Matches = @Matches + 1 /* To allow for more matches, use DIFFERENCE instead of SOUNDEX: IF DIFFERENCE(@ExtractedWord, @Word) >= 3 SELECT @Matches = @Matches + 1 */ END /* Return the number of occurences of @Word in @Phrase */ RETURN @Matches END Summary In this chapter, you implemented the search functionality of BalloonShop. You learned many useful tricks about SQL Server and C# programming. While implementing the data tier, you learned two ways of counting how many times a substring appears in a longer string while building the WordCount function. You learned how to use that function to implement search results ranking in the SearchCatalog procedure. You also learned how to select only a portion of the entire search results by using a table variable in SQL Server. In the business tier, you added the logic to process the string entered by the visitor and send the words to search for to the presentation tier. The presentation tier nicely displays the search results by reusing the ProductsList controls you wrote in Chapter 4. Darie-Watson_4681C05.fm Page 197 Monday, September 19, 2005 9:53 AM Darie-Watson_4681C05.fm Page 198 Monday, September 19, 2005 9:53 AM [...]... Carefully designing the database; for example, having indexes on the columns used in table joins significantly improves query performance • Writing efficient SQL code (starting from little tricks such as avoiding using the * wildcard, to implementing efficient query logic) and storing that code within stored procedures (which are easier to maintain and run faster than ad-hoc queries) • Using smart data... to the server, which include the query string parameters You’ll see in the exercise how to vary the output page cache based on the query string parameters You can enable output caching for DepartmentsList.ascx by editing the file in HTML View and by adding the following line at the beginning of the file: After adding this directive, ASP.NET. .. id="addToCartLink"> Your form should look like Figure 7-1 in Design View Figure 7-1 The Add to Cart button in Product.aspx 4 Append the following code to the PopulateControls method in Product.aspx.cs: // Create the "Add to Cart" PayPal link string link = "JavaScript: OpenPayPalWindow(\"https://www.paypal.com/cgi-bin/webscr" + "?cmd=_cart" + // open shopping... August 25, 2005 8 :48 AM 216 CHAPTER 7 ■ RECEIVING PAYMENTS USING PAYPAL // Encode link characters to be included in HTML file string encodedLink = Server.HtmlEncode(link); // The the link of the HTML Server Control addToCartLink.HRef = encodedLink; 5 Make sure you replace youremail@yourserver.com in every link with the email address you submitted when you created your PayPal account for all Add to Cart... in Figure 8-3 Also, as you can see, instead of the Edit button, you get Update and Cancel buttons Clicking Update updates the database with the changes, whereas clicking Cancel simply quits edit mode 8213592a11 745 6a 340 854d18cee57603 223 Darie-Watson _46 81C08.fm Page 2 24 Monday, September 19, 2005 9:55 AM 2 24 CHAPTER 8 ■ CATALOG ADMINISTRATION Figure 8-3 Editing department information The administrator... src="Images/ViewCart.gif" border="0"> ■Note You must write the OpenPayPalWindow call on a single line in the HTML source We split it on multiple lines in the code snippet to make it easier to read Darie-Watson _46 81C07.fm Page 215 Thursday, August 25, 2005 8 :48 AM CHAPTER 7 ■ RECEIVING PAYMENTS USING PAYPAL 3 Next, to add the PayPal Add to Cart button in Product.aspx, open Product.aspx and add an HTML Server Control... now Figure 7-2 Integrating the PayPal shopping cart 7 Experiment with the PayPal shopping cart to make sure that it works as advertised Figure 7-3 shows the PayPal shopping cart in action 8213592a11 745 6a 340 854d18cee57603 Darie-Watson _46 81C07.fm Page 217 Thursday, August 25, 2005 8 :48 AM CHAPTER 7 ■ RECEIVING PAYMENTS USING PAYPAL Figure 7-3 The PayPal shopping cart How It Works: PayPal Integration Yes,... This mechanism will be extended in Chapter 12, where you’ll add customer accounts The user interface bit of the login functionality consists of a control named UserInfo that allows the administrator to authenticate himself or herself (see Figure 8-1) Figure 8-1 BalloonShop with a login box After logging in as an administrator, the UserInfo box displays links to the administrative parts of the site The... giving you an HTML code block similar to the one shown previously Click the Developers link at the bottom of the first page and then click PayPal Solutions in the menu on the left to find the button generators You’ll implement the PayPal integration in the next exercise Exercise: Integrating the PayPal Shopping Cart and Custom Checkout 1 Open BalloonShop.master in Source View and add the following... Chapter 9, where you’ll create your own shopping cart In Chapter 10, you’ll implement the Place Order button in the shopping cart, which saves the order into the database and forwards the visitor to a PayPal payment page To call the PayPal payment page (bypassing the PayPal shopping cart), redirect to a link like the following: https://www.paypal.com/xclick/business=youremail@yourserver.com&item_name=Order#1 . Wednesday, August 24 , 20 05 7: 02 AM 821 3592a11 745 6a3 40 8 54d18cee57 603 CHAPTER 6 ■ IMPROVING PERFORMANCE 20 3 The Page.IsPostBack function is your best friend in this instance. IsPostBack indicates whether. contained in the control or page being cached. Darie-Watson _46 81C06.fm Page 20 6 Wednesday, August 24 , 20 05 7: 02 AM CHAPTER 6 ■ IMPROVING PERFORMANCE 20 7 • VaryByCustom: Used to identity custom. ViewState is not maintained, and it’s not popu- lated from the database, either. Darie-Watson _46 81C06.fm Page 20 5 Wednesday, August 24 , 20 05 7: 02 AM 20 6 CHAPTER 6 ■ IMPROVING PERFORMANCE Using Output

Ngày đăng: 09/08/2014, 14:20

Từ khóa liên quan

Mục lục

  • Beginning ASP.NET 2.0 E-Commerce in C# 2005: From Novice to Professional

    • Chapter 6 Improving Performance

    • Chapter 7 Receiving Payments Using PayPal

    • Chapter 8 Catalog Administration

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

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

Tài liệu liên quan