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

ASP.NET 2.0 Instant Results

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

Wrox Photo Album

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:SqlServerConnectionString %>”

SelectCommand=”SELECT [collectionID] AS collectionID, [collection name] AS collection_name, [description] AS description, [number of photos] AS number_of_photos FROM [collection_count]” UpdateCommand=”UPDATE Collection SET description =@description, name =@collection_name where collectionID = @collectionID” DeleteCommand=”DELETE from Collection where collectionID = @collectionID”>

<DeleteParameters>

<asp:Parameter Name=”CollectionID” /> </DeleteParameters>

<UpdateParameters>

<asp:Parameter Name=”description” /> <asp:Parameter Name=”collection_name” />

</UpdateParameters>

</asp:SqlDataSource>

This SqlDataSource control acts as a responsive party for all data interactions for the GridView. Any edits, deletes, selects, and so on, must pass through this control before they can make their way to the database. Although this approach may not be suitable for large-scale enterprise application development, it suffices for the nature of this photo album application.

Editphotos.aspx

The Editphotos.aspx WebForm displays the photos from the web server in a GridView for the purpose of editing or deleting the photos. As with the collection GridView on the Admin page, the GridView control is bound to the SqlDataSource control on the page. The database actions that the grid provides are configured within the HTML markup of the SqlDataSource. The following code displays the SelectCommand, UpdateCommand, and DeleteCommand queries, as well as the parameters for each database command:

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:SqlServerConnectionString %>”

SelectCommand=”SELECT [photoID], [collectionID], [filepath], [name], [description] FROM [photo] WHERE ([collectionID] = @collectionID)”

UpdateCommand=”UPDATE photo SET description = @description, name = @name, filepath = @filepath, collectionID = @collectionID where photoID = @photoID” DeleteCommand=”DELETE From photo where photoID = @photoID”>

<SelectParameters>

<asp:QueryStringParameter Name=”collectionID” QueryStringField=”collectionID” Type=”Int32” />

</SelectParameters>

<UpdateParameters>

<asp:Parameter Name=”collectionID” /> <asp:Parameter Name=”name” /> <asp:Parameter Name=”filepath” /> <asp:Parameter Name=”photoID” /> <asp:Parameter Name=”description” />

</UpdateParameters>

<DeleteParameters>

<asp:Parameter Name=”photoID” /> </DeleteParameters>

</asp:SqlDataSource>

227

Chapter 7

The actual implementation of the grid is shown in the following code, displaying bound field entries for the textual data, and an ImageField bound field for a thumbnail of the image:

<asp:GridView ID=”GridView1” runat=”server” AllowPaging=”True” AllowSorting=”True” AutoGenerateColumns=”False” DataKeyNames=”photoID”

DataSourceID=”SqlDataSource1” CellPadding=”2” CellSpacing=”1” GridLines=”None” PageSize=”4” ShowFooter=”True”>

<PagerSettings Position=”TopAndBottom” /> <Columns >

<asp:BoundField DataField=”photoID” HeaderText=”photoID” InsertVisible=”False” ReadOnly=”True”

SortExpression=”photoID” />

<asp:BoundField DataField=”collectionID” HeaderText=”collectionID” SortExpression=”collectionID” />

<asp:BoundField DataField=”filepath” HeaderText=”filepath” ReadOnly=”True” SortExpression=”filepath” />

<asp:BoundField DataField=”name” HeaderText=”name” SortExpression=”name” > <ItemStyle Width=”100px” />

</asp:BoundField>

<asp:BoundField DataField=”description” HeaderText=”description” SortExpression=”description” >

<ItemStyle Width=”300px” /> </asp:BoundField>

<asp:ImageField DataImageUrlField=”filepath” DataImageUrlFormatString=”~/upload/{0}” NullImageUrl=”~/upload/{0}.jpg” >

<ControlStyle Height=”50px” Width=”50px” /> </asp:ImageField>

<asp:CommandField ShowDeleteButton=”True” ShowEditButton=”True” /> </Columns>

</asp:GridView>

The GridView allows for inline editing of data by clicking the Edit link within a row on the GridView. This automatically provisioned inline row editing is a new ASP.NET 2.0 feature, and saves the developer from creating complex and difficult routines for text boxes and editable areas within a grid.

Secure Area Files

The Secure folder of the Wrox Photo Album contains the administrator area files, including the pages that allow for adding, editing, and deleting photos and collections of photos. As with the public area of the site, most of the business logic is hidden from these pages, and contained in the reusable web user controls held in the Usercontrols folder. See the “User Controls” section for more detailed analysis of the logic contained within the user controls for this section.

The Secure folder is set to deny anonymous access within the ASPNET security database and prevents unauthorized access intrinsically. If a page is requested by the browser within this Secure folder, and the current user has not been authenticated (not logged in), the browser is directed to a login page as a preventative measure. If the user has logged into the application, the Secure folder’s permissions would be satisfied, and the requested page would load normally.

228

Wrox Photo Album

User Controls

Some specific user controls in the site provide all of the navigation and content display for multiple pages. Because web user controls promote a practice of creating and using reusable code, they were made to be applicable within multiple pages of the site, depending on the nature of the controls.

header.ascx

The header user control is used to provide the top area of each page with meaningful content. If anything needs to reside at or near the top of a web page, you should add it to the header control so it is visible through all of the pages.

The following code represents entire header.ascx source:

<%@ Control Language=”VB” AutoEventWireup=”false” CodeFile=”header.ascx.vb” Inherits=”Controls_header” %>

<div style=”text-align: center”> <table><tr>

<td><img src=”../Images/headerlogo.gif” /></td> <td><h1><% Response.Write(Page.Title) %></h1> </td>

</tr></table>

</div>

Notice that the <%Response.Write(Page.Title)%> tags are used to write back to the response stream a title of the web site on the top of each page, which originated from the Web.config file.

footer.ascx

The footer user control is used as the bottom section of the site, for each page that uses the master page. That is, the footer control, among others, is a referenced control within the master page. In this way, it is propagated to all pages in the same exact manner.

The content of the footer control is as follows:

<%@ Control Language=”VB” AutoEventWireup=”false” CodeFile=”footer.ascx.vb” Inherits=”Controls_footer” %>

<a href=”http://wrox.com” target=”_blank”>© 2005 Wrox Press</a>    <a href=”SignIn.aspx” target=”_self”>Login</a>

This excerpt includes a few hyperlinks. One is for the Wrox Press web site, and the other is a link to the Login page for the chat application.

navigation.ascx

The navigation user control is used to provide the reusable menu on each page in the site. The Menu itself is a brand-new ASP.NET 2.0 control that binds to a SiteMapDataSource control, also new in version 2.0 of the .NET Framework. The SiteMapDataSource control is used to bind to an XML file, wherein the site files are listed as entries in the XML file. This is where you can change the data that feeds the menu of the site.

229

Chapter 7

The following excerpt is the HTML markup of the navigation control:

<%@ Control Language=”VB” AutoEventWireup=”false” CodeFile=”navigation.ascx.vb” Inherits=”Controls_navigation” %>

<asp:Menu ID=”Menu1” runat=”server” DataSourceID=”SiteMapDataSource1”

Orientation=”Horizontal”

StaticDisplayLevels=”2”></asp:Menu>

<asp:SiteMapDataSource ID=”SiteMapDataSource1” runat=”server” />

The XML file of the SiteMapDataSource control is shown here:

<?xml version=”1.0” encoding=”utf-8” ?>

<siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0” > <siteMapNode url=”#” title=”” description=”Welcome to PhotoShare!”>

<siteMapNode url=”default.aspx” title=”Photo Albums” /> <siteMapNode url=”about.aspx” title=”About Me” />

<siteMapNode url=”contact.aspx” title=”Contact Me” /> <siteMapNode url=”sitemap.aspx” title=”Site Map” /> <siteMapNode url=”secure/admin.aspx” title=”Admin” />

</siteMapNode>

</siteMap>

To add a page to the menu of the web site, you must simply copy and paste (with the necessary modifications) an entry of the preceding XML file. In this way, the master page (which contains the only reference to the navigation control) provides visibility to the menu of the site on each page.

The next section explains in detail how to install and configure the source files of the Wrox Photo Album and how to deploy the site to a server in a production environment.

Setting up the Project

You can set up the Wrox Photo Album in two ways: hosted web site installation or local developer installation.

Hosted Web Site Installation

If you want to install the Wrox Photo Album as a hosted web site on a computer or server, without customizations or enhancements at all, follow these steps (assuming that the .NET Framework 2.0 is already installed):

1.Open the folder Chapter 06–Wrox Photo Album\Installation Files\ from the CD-ROM that came with this book and double-click the file setup.exe.

2.This process installs the files properly for hosting the web site locally to C:\inetpub\wwwRoot\ PhotoGallery as a file-based web site application. Note, in the Setup wizard, one of the initial screens will require you to confirm the name of the virtual directory where your application will be installed to within IIS. This virtual directory name is important, because it will allow navigation from localhost/your virtual directory name. Try a name like PhotoGallery, which would then allow for browsing to http://localhost/photogallery/.

230

Wrox Photo Album

3.Click Next to install the application, and close the installation program when it completes.

4.Finally, browse to your local web site (in step 2, for example, http://localhost/photo gallery). The Wrox Photo Album application should appear. To test the administration section, click the Admin link and log in with a username of SuperAdmin and a password of password#.

Local Developer Installation

If you would like to open the project in Visual Studio 2005 or Visual Web Developer, perform the following steps (assuming that the .NET Framework 2.0 is already installed, along with either Visual Studio 2005 or VWD):

1.Start by creating a brand-new web site in Visual Web Developer using Visual Basic .NET.

2.Open the folder Chapter 06–Wrox Photo Album Installer\ from the CD-ROM that came with this book and extract the contents of the file PhotoAlbumSource.zip to a folder on your hard drive.

3.Open a Windows Explorer and browse to the folder that contains the unpacked files.

4.Next, arrange both Visual Web Developer (VWD) and the Windows Explorer in such a way that both are visible at the same time.

5.In the Windows Explorer, select all of the folders and files within the codebase and drag the selected folders and files from the explorer window into the Solution Explorer in VWD. If you’re prompted to overwrite files, select Yes. You should end up with a Solution Explorer that contains all of the necessary files for the project to run properly.

6.In the Web.config file, modify the EmailTo and EmailFrom values in the appSettings section to reflect the administration e-mail accounts to be used for sending and receiving e-mail, should you decide to use this feature (see the following code). Also, uncomment the entry you would like to use for the theme of the web site: either OpenBook or UltraClean. This can be changed back at any time, should you change your mind. These settings will require changing to your needed e-mail settings even if you performed the installation of the application via the install files.

<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0”> <appSettings>

<add key=”EmailFrom” value=”admin@myphotoalbum.com” /> <add key=”EmailTo” value=”admin@myphotoalbum.Com” /> <!--

<add key=”CurrentTheme” value=”openbook” /> -->

<add key=”CurrentTheme” value=”ultraclean” />

</appSettings>

7.In the Web.config file, modify the smtp value in the mailSettings section (as shown in the following code) to reflect the e-mail SMTP outbound mail server name to be used for sending and receiving e-mail, should you decide to use this feature:

</connectionStrings>

<system.net>

<mailSettings>

<smtp deliveryMethod=”Network”>

231

Chapter 7

<network host=”smtp.YourMailServerName.com” port=”25” /> </smtp>

</mailSettings>

</system.net>

<system.web>

8.Press F5 to run the application in the development environment.

If you want to see an example of how to extend the functionality of the Wrox Photo Album, head to www.wrox.com and find this book’s download page.

Summar y

In this chapter you learned about some of the more useful controls and tools in the ASP.NET 2.0 environment, such as themes, navigation controls, security controls, the SQL Server Express database tools, and the use of master pages in authoring a consistent web site look and feel. The reading was gauged to lead you to an understanding of how each of these new and exciting features provides the rapid development everyone’s been waiting for in Visual Studio 2005.

In the code explanation section you studied the different techniques in handling images on a web server, in regards to storing and delivering images to a user. You also saw how the classes and pages that comprise the Wrox Photo Album work, and how they communicate with each other.

232

8

Customer Suppor t Site

No matter how well your products might work, how stable the hardware you sell is, or how happy your customers are about your company and your products, your users are likely to have a need for more information about your products and services sooner or later. They may want to look up the specifications of a product, find the latest drivers to make the product work with a more recent version of their operation system, or find out handy tips about cleaning and maintaining it.

The Customer Support Site presented in this chapter is a web site that allows users to quickly find information about the products or services that your company might be selling. Although this chapter is based on a fictitious hardware-selling company called Wrox Hardware, the principles you learn in this chapter can be applied to many other sites that use a hierarchical content model.

Because this is a book about ASP.NET, this chapter focuses on a lot of the new features of ASP.NET 2.0. However, when Microsoft released the .NET Framework version 2.0 with ASP.NET 2.0, it not only released developer’s tools like Visual Studio and Visual Web Developer Express Edition, it also released a new version of its relational database management system called SQL Server 2005. This new version of SQL Server tightly integrates with the .NET 2.0 Framework and Visual Web Developer and has a long list of new features and improvements. Because many web applications make use of a database, it’s important to understand the capabilities of the database engine in use. Therefore, in this chapter you get a good look at one of the new features of SQL Server called Common Table Expressions. You see more of this when the data access layer and stored procedures are discussed.

Using the Customer Suppor t Site

The Customer Support Site presented in this chapter is the support home for the fictitious hardwareselling company called Wrox Hardware. This company sells hardware from popular best-selling manufacturers such as BNH (Brand New Hardware), Eccentric Hardware Makers, and Rocks Hardware. To minimize the costs for the support department, most of the company’s support system is web-based. With the Customer Support Site, users can browse the product catalog with the Product Locator to look for products and their specifications. This is useful if you want to find out if your brand-new hand-held scanner uses AAA or simple AA batteries, for example. The Product Locator uses drop-downs (see Figure 8-1) to allow users to drill down in a hierarchy of categories to locate the product they want to find out more about.

Chapter 8

Figure 8-1

In addition to the Product Locator, the site also has a Downloads section. With a drill-down mechanism similar to the one in the Product Locator, users can quickly locate files related to their product. These downloads range from general files such as the warranty document for all BNH products to driver files for a specific product.

The third section of the public site, shown in Figure 8-2, is a searchable list of Frequently Asked Questions (FAQs). These questions are not categorized as the products and downloads are but they are searchable with a small search engine that supports Boolean logic, using AND and OR expressions.

The Customer Support Site also has a CMS that can be used by content managers to manage the products, downloads, and FAQs in the back-end database of the web site.

In the next section, you get a good look at the design of the Customer Support Site. You see the classes that make up the business and data access layer of the web site and you learn how the database and its stored procedures and user-defined functions are designed.

The section that follows digs much deeper into the site and shows you how each of the individual parts are developed and how they interact together.

Toward the end of the chapter, you see how to install the Customer Support Site on your own server using the supplied installer or by manually installing the necessary files.

234

Customer Support Site

Figure 8-2

Design of the Customer Suppor t Site

Just like many of the other applications in this book, the Customer Support Site is based on a three-tier architecture. The presentation layer consists of the ASPX pages and ASCX user controls located in the root and a few subfolders of the site.

Both the business layer and the data access layer are stored in the special App_Code folder. To make it easier to locate code in the right layer, the business code is stored in a subfolder called BusinessLogic, and the data access code is hosted in the DataAccess folder. Common configuration properties, used by the other layers, are stored in a file called AppConfiguration.vb directly in the App_Code folder.

Most of the data access is performed with <asp:ObjectDataSource> controls in the .aspx pages that talk to the classes (through their public methods) in the business layer, which in turn forwards the calls to methods in the data access layer. In other pages, such as the InsertUpdate pages in the Management section, the code in the code-behind file instantiates instances of the classes from the business layer directly, without an additional data source control.

The next section shows you each of the classes in the business layer and explains how and where they are used. In the section that follows, you discern the design of the data access layer and the database.

235

Chapter 8

The Business Layer

The business layer of the Customer Support Site contains five classes, each of which is used to display categorized information on the web site. For each of the site’s main sections, Products, Downloads, and FAQs, you’ll find an associated class in the files named after the classes they contain. So, you’ll find the Product class in the file Product.vb, and so on. In addition to these three classes are two others, called Category and ContentBase. The Category class is used to manage the available categories in the database and get information about them.

The ContentBase class is the parent class of Product and Download, and is discussed next.

The ContentBase Class

A Product and a Download have a lot in common. They both have a title and a description to display the item on the site. They also have an ID to uniquely identify each item. And finally, both are linked to a category in the database. When you start designing these classes, your first attempt may be to code the Product class and then duplicate the shared code in the Download class. However, this design has a few drawbacks. First, you need to copy and paste the code from the Product file into the Download file, which results in a lot of superfluous work. But more importantly, when you need to make changes to the code — for example, because you want to rename Category to CategoryId — you now have to make these changes at two locations!

To overcome this problem, the ContentBase class is introduced. This class exposes the properties and methods that the Product and Download (and future web content items) have in common. This class serves as a base class that other classes can inherit from. The child classes then automatically get all the public members from the base class. Figure 8-3 shows the ContentBase class and the two child classes that inherit from it.

Figure 8-3

In addition to the inherited members, the child classes implement their own properties and methods. You see what those are later when the respective classes are discussed.

236