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

ASP.NET 2.0 Instant Results

.pdf
Скачиваний:
67
Добавлен:
17.08.2013
Размер:
11.03 Mб
Скачать

Customer Support Site

OR F.Answer LIKE ‘%driver%’

)

)

AND

(

(

F.QuestionShort LIKE ‘%failure%’ OR F.QuestionLong LIKE ‘%failure%’ OR F.Answer LIKE ‘%failure%’

)

)

AND

(

(

F.QuestionShort LIKE ‘%Power Printer%’ OR F.QuestionLong LIKE ‘%Power Printer%’ OR F.Answer LIKE ‘%Power Printer%’

)

OR

(

F.QuestionShort LIKE ‘%3D Printer%’ OR F.QuestionLong LIKE ‘%3D Printer%’ OR F.Answer LIKE ‘%3D Printer%’

)

)

When executed by SQL Server, this WHERE clause returns all the frequently asked questions that match the user’s search criteria. Because of the way the code is set up, it doesn’t matter if the short question contains the word driver and the answer contains the word failure, or vice versa. In all cases, this code finds the records the user is looking for.

The WHERE clause is eventually passed to the database through a SQL parameter called @whereClause, where it is appended to a SQL statement and executed with the EXEC command:

CREATE PROCEDURE sprocFaqSelectListBySearchTerm

@whereClause nvarchar(1000)

AS

DECLARE @sqlStatement nvarchar(MAX)

SET @sqlStatement = ‘

SELECT

Id,

QuestionShort,

QuestionLong, Answer

FROM Faq F

WHERE ‘ + @whereClause + ‘

ORDER BY Id DESC’

EXEC(@sqlStatement)

267

Chapter 8

The EXEC command returns the requested FAQ items, just like a regular SELECT statement would have done.

This concludes the discussion of the FAQs page and the entire public section of the Customer Support Site. With the pages in the public ContentFiles folder, users of the Customer Support Site can now easily locate products, downloads for the products they may have purchased, and browse through the collection of frequently asked questions.

The final part of the “Code and Code Explanation” section takes a quick look at the pages in the Management folder that contain the CMS for the Customer Support Site.

The Customer Support Site CMS

Most of the concepts used in the content management system of the support site have been discussed in previous chapters, most notably Chapter 6. However, a few things are worth discussing, so some of the highlights of these pages are briefly discussed in the sections that follow.

Categories.aspx

This page allows you to add new categories to the database. Using the now familiar drop-downs you can drill down in the hierarchy of categories and add a category at each of the three levels. An important thing to notice about this page is the way the validators are used. The page contains three text boxes that enable you to type a new category to be added to the database at each of the three available levels. Each text box also has an <asp:RequiredFieldValidator> control attached to it. Normally, with three validators, you need to fill all three text boxes before the page will validate. However, at any time, only one of the text boxes is required. To enable only one validator control at a time, each validator has a different ValidationGroup attribute. The following code snippet shows the code for the validator that checks the first text box:

<asp:RequiredFieldValidator ID=”reqLevel1” ValidationGroup=”Level1” runat=”server” ControlToValidate=”txtLevel1” Display=”Dynamic”

ErrorMessage=”*” />

Controls that cause the validation to be triggered, like buttons, now also have a ValidationGroup attribute. This way, you can relate postback controls with a specific validation group like this:

<asp:Button ID=”btnAddNewLevel1” runat=”server” Text=”Add New Level 1”

ValidationGroup=”Level1” />

When this button gets clicked, only the controls that share the same ValidationGroup are checked for valid values.

The List Pages

The pages that list the products, downloads, and FAQs are all very similar. They have a GridView that displays the items. An Edit and a Delete button allow you to change existing items and delete them. The RowCommand for each GridView looks at the CommandName of the e argument to determine the action that must be taken using a Select Case statement. Inside each of the Case blocks, the code converts the CommandArgument to an Integer and uses that to retrieve the grid’s DataKey. You may be tempted to move this code to outside the Select Case statement so you only have to write it once. However, when you do so, you’ll run into trouble when you try to sort the GridView. Although sorting is carried out by

268

Customer Support Site

ASP.NET automatically, it still fires the RowCommand when you click one of the column headers to sort the grid. When you do so, the CommandArgument of the e parameter contains the name of the column you’re trying to sort on. Obviously, a column name cannot be converted to an Integer, so the code will crash.

The Create and Update Pages

For each of three content types — Downloads, FAQs, and Products — there is an InsertUpdate page that allows you to create new and change existing items. All three use the FCKeditor that you have seen in previous chapters. The code for the Download and Product pages uses the GetCategoryPath method of the Category class. This method returns the path of a category from a child to the parent record. This method is necessary because the content item in the database only stores the deepest child category. To be able to preselect the drop-downs of the parent levels, you need to know to which parents a category belongs. The stored procedure sprocCategorySelectPath once again uses Common Table Expressions in a similar way you have seen before.

With these pages and their code, you have come to the end of the “Code and Code Explanation” section. By now you should have learned enough to use and understand the inner workings of the Customer Support Site. In the next section, you see how to install the application on a web server.

Setting up the Customer Suppor t Site

Just as with the most of the other chapters in this book, you can choose to install the Customer Support Site manually or by using the supplied installer. The installer ensures a quick and easy installation process, whereas the manual process gives you a bit more flexibility with regard to where the files are placed.

Using the Installer

To install the Customer Support Site so you can run it on your server, follow these steps:

1.Open the folder Chapter 08 - Customer Support\Installer from the CD-ROM that came with this book and double-click setup.exe to start up the installer.

2.In the Setup wizard, accept all the defaults by clicking Next until the application has been installed completely. Click Close to close the installer. The setup procedure has copied all the required files to a folder called CustomerSupport under your default web site.

3.Next, open up the Web.config file in the CustomerSupport folder (by default, located at

C:\Inetpub\wwwroot\CustomerSupport) and locate the <connectionStrings> node. Check that the connection string points to your installation of SQL Server and modify the string if required.

4.Just like you did in Chapter 6, you’ll need to configure the security permissions of the UserFiles folder, so the web site can save the files that are uploaded through the site and the FCKeditor. Refer to that chapter for detailed instructions.

5.Now browse to http://localhost/CustomerSupport. The Customer Support Site should appear and you can browse through the products, downloads, and FAQs lists.

269

Chapter 8

Manual Installation

Although the installer is a very convenient way to set up the Customer Support Site, manual installation isn’t much more difficult. To install the site manually, follow these steps:

1.Open the folder Chapter 08 - Customer Support\Source from the CD-ROM that came with this book.

2.Extract the contents of the file Chapter 08 - Customer Support.zip to a location on your hard drive; for example, C:\Inetpub\wwwroot\. Make sure you extract the files with the option Use Folder Names or something similar to maintain the original folder structure. The exact setting depends on the extraction utility you’re using. You should end up with a folder like C:\Inetpub\ wwwroot\CustomerSupport that in turn contains a number of files and other folders.

3.Start Visual Web Developer, choose File Open Web Site, and browse to the folder that was created in step 2. The site should open and display on the Solution Explorer window.

4.Next, open up the Web.config file from the Solution Explorer and locate the <connection Strings> node. Check that the connection string points to your installation of SQL Server and modify the string if required. Save and close the file.

5.Just like you did in Chapter 6, you’ll need to configure the security permissions of the UserFiles folder, so the web site can save the files that are uploaded through the site and the FCKeditor. Refer to that chapter for detailed instructions.

6.You can now browse to the site by pressing Ctrl+F5. Visual Web Developer will start its internal web server and then the site will be displayed in your default web browser.

Using the Customer Support Site

No matter which of the two installation methods you chose, you should now see the Customer Support Site in your browser. You can use the main menu items like Products and Downloads in the way described at the start of this chapter. You’ll also see the Management menu item, which allows you to manage the content in the system.

To make it easier to explain how the Customer Support Site works, and make it easier for you to explore the Management section, there is no authentication mechanism in place on this web site. This means anyone accessing this web site has full access to the Management section. Naturally, this isn’t something you want, so you should take some steps to protect that area of the site. The easiest way to do this is to configure the application for Membership and Role management by choosing Website ASP.NET Configuration in Visual Web Developer. This opens the Web Site Administration Tool in a browser window. Create at least one user and a ContentManagers role and assign the new user to this role. If you need more information about working with the Web Site Administration Tool, click the “How do I use this tool?” link in the upper-right corner of the window.

The next step is to add the following code to the end of your Web.config file, right after the closing tag of the <system.web> node:

</system.web>

<location path=”Management”> <system.web>

<authorization>

270

Customer Support Site

<allow roles=”ContentManagers” /> <deny users=”*”/>

</authorization>

</system.web>

</location>

This blocks access to the Management folder to all users except those that are assigned to the ContentManagers role.

Another solution is to create an entirely new CMS site that connects to the Customer Support database. This way, you can fully separate the public front end from the protected back-end part of the web site.

If you go to www.wrox.com and find this book’s download page, you’ll discover ways to extend the Customer Support Site to make it even more useful than it already is. It suggests a couple of extensions and guides you through implementing one of those features.

Summar y

In this chapter you were introduced to the Wrox Hardware Customer Support Site, a web site that allows users to find and retrieve information about the products that the Wrox Hardware company sells.

You first got a quick tour of browsing through the system from an end-user’s point of view. You saw how to locate Products and Downloads, and how to search the list of Frequently Asked Questions.

Then you got an overview of the system’s design. You saw that the application is separated in three different layers: one for the presentation, one for the business logic, and one for the data access code. You saw a list of all the classes involved and the methods they support. You also got an explanation of these methods and how the interact together.

In the “Code and Code Explanation” section you got a detailed look at the code inside all these classes and pages. You learned how to deploy ObjectDataSource controls to enforce good n-tier architecture in your application. Using these controls enables you to create well-designed and easy-to-maintain applications without cluttering up your pages with tons of SQL statements or stored procedure names. You also saw how to use the new Common Table Expressions feature in SQL Server, a powerful technique to create recursive code that enables you to retrieve complex, hierarchical data structures from the database.

At the end of the chapter you learned how to install the Customer Support Site with either the supplied installer or by a manual installation process, and got a few tips about securing the Management folder from unauthorized users.

271

9

Wrox WebShop

E-commerce is one of the largest driving forces behind the Internet. Even in the Internet’s earliest days, many sites featured a shop where you could order products and have them shipped to your home. With the advent of server-side techniques, such as ASP and ASP.NET, it has been much easier and cheaper for smaller sites to offer their products and services online. Despite the large diversity in the goods these sites offer, they all have one thing in common. To allow customers to select the products they want to order, they all feature a product catalog and a shopping cart where products are stored during the shopping process. At checkout time, these products are taken from the cart and usually stored in a database so the order can be processed later. The Wrox WebShop is no exception; this chapter shows you how to create a web shop with a shopping cart in ASP.NET 2.0.

The chapter starts off with a quick tour of the WebShop from an end-user’s point of view. It guides you through the process of browsing articles and adding them to a shopping cart, and shows you how the shopping cart is saved in the database as an order. Finally, this chapter also explains how you can manage the product catalog for the WebShop.

Once you have a basic understanding of the functionality in the WebShop you dig into its design, discovering the business and data access layer classes that make up the application.

The section “Code and Code Explanation” puts it all together and explains how the ASPX pages interact with the classes in the business layer.

If you want to set up the WebShop so you can follow along with the explanation, refer to the section “Setting up the WebShop” near the end of this chapter.

Using the WebShop

The user interface of the WebShop consists of two main parts: the public area and the protected Management section. The public site is where your visitors can view and order products, and

the Management section allows you to manage the products in the catalog. The Management section is protected so only users in the Administrator group can access it.

Chapter 9

The next section discusses the public interface of the WebShop, and demonstrates how you can browse the product catalog and order products. The section that follows briefly guides you through the Management section.

Navigating the WebShop

Because it’s more interesting to focus on the functionality of the WebShop, rather than on its look and feel, the design of the shop is pretty simple and straightforward. If you open the homepage of the WebShop by browsing to http://localhost/WebShop (or another location you may have chosen during setup), you’ll see the WebShop’s homepage appear, as shown in Figure 9-1.

Figure 9-1

Besides the logo and the welcome text, you also see the main menu that appears on each page in the site. This main menu contains a few important navigation buttons. The Home button always brings you back to the homepage of the WebShop. The Shop button brings you to the main shopping area where you can browse the product catalog. With the Shopping Cart menu item you can view the contents of your shopping cart, if there is anything to show. The Login button allows you to log in manually. Usually, there is no need to use this button, because the WebShop shows the Login page automatically whenever you try to access a protected page. Once you’re logged in, this button changes to Logout, allowing you sign out again.

If you click the Shop button you’re taken to the Shop area (see Figure 9-2) where you can browse through the product catalog.

On the left you see the available product categories (Mugs, Posters, and T-Shirts), presented as a list of hyperlinks. When you click one of these links, the list of products on the right is updated and displays the products for that category. The categories and the products are all retrieved from the database — you see how that works in the “Code and Code Explanation” section later in this chapter.

To view the details of a product, you can click its image, heading, the little triangle, or the Read More link. The Product Details page appears where you can add the requested article to your shopping cart or return to the main shopping area. If you decide to purchase the item by clicking the Add to Cart button, you’re taken to the Shopping Cart page, which is depicted in Figure 9-3.

274

Wrox WebShop

Figure 9-2

Figure 9-3

275

Chapter 9

If you want to add more products to your cart, click the Continue Shopping button. Otherwise, make your move to the counter by clicking Proceed to Check Out. Because the checkout page is only accessible by authenticated users, you’re taken to Login.aspx first if you’re not logged in. If you’re a new customer, you should sign up to get a new WebShop Customer account. If you made a purchase in the past, simply add your username and password to log in.

The Login page also allows you to retrieve a lost password that is sent to you by e-mail.

Once you successfully create an account and log in, you have to supply your name and shipping address, and then confirm your order. After reviewing the items in your shopping cart, click the Finalize Order button. This saves the order in the database and then redirects you to the Thank You page, where you get instructions about how to make the payment for the order. Further on in the chapter, when the code is discussed, you see a full flowchart of this process in Figure 9-13.

The Wrox WebShop does not have a connection with a payment provider to handle online payments. The diversity in payment providers makes it very hard to demonstrate a “one size fits all” solution here. Usually when you sign a contract with a payment provider, you get detailed documentation and sample code showing you how to access their services. The best place to integrate a payment provider in the WebShop is on the Check Out page. In the current WebShop, that page is responsible for finalizing the order. When connected to a payment service, you still save the order in the database, but mark it as “in progress.” Then you redirect the user to the payment provider’s web site to complete the purchase. You usually need to pass the order ID and the total order amount, and optionally the user’s details. Once the user has either paid for or cancelled the order, the payment provider updates you on the result of the transaction. When the transaction has succeeded, you can update the order in the database and set it to Paid. Otherwise, you can cancel the order or remove it from your database altogether.

Maintaining the WebShop Product Catalog

The WebShop has a small maintenance section that allows you to create new products and delete existing ones. If you’re logged in as an Administrator (you can use a username of Administrator and a password of Admin123#), you can click the Admin menu item to enter the maintenance section. In this section you can choose Add New Product to insert a new product (see Figure 9-4).

You need to provide a title, a description, a category, and a price for the product you want to add. To display the product on the product pages and in the shopping cart, you also need to provide an image for the product. From this image, three thumbnails are created automatically. You see how this works later in the chapter.

From the Product List page you can also delete products from the catalog. It’s not possible to update existing products or to maintain categories. However, with the knowledge you gained in previous chapters, this will be easy to implement.

Now that you know how to use the WebShop as an end-user, it’s time to look at its design.

276