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

ASP.NET 2.0 Instant Results

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

7

Modifying the Wrox

Photo Album

Although the photo album is fairly concise in its scope, it likely does not contain all of the extra features and enhancements that you might want to have. Some possible enhancements to the photo album could include:

Implement paging for the DataList control that displays the images in a grid. This way, the images would be displayed in the same grid-like fashion, but also span across an unlimited number of pages instead of requiring the user to scroll down the page.

Create an email alert feature that allows users to sign up for alerts whenever new images are added to the photo album.

Create a new theme or skin for the website to use in its formatting and color scheme.

Create a slide show feature in JavaScript to show the images one at a time, with a fade effect between images.

Create a feature that would allow website visitors to ask questions or make comments about a particular image on the photo album to the photographer or web site owner.

If you want to take on the last of the above proposed features, creating a way for viewers to ask questions about any image and track feedback, there would be several areas that you would need to modify within the application to accomplish this. This feature would infer that for any images’ detailed view page, there would be an opportunity for the web site viewer to enter text and save the text to the database for all to see. All feedback to such inquiries would be posted near the image for future visitors to observe. This would provide an overall more interactive experience for the user and the photographer alike.

To implement this feature, the following steps would be required:

1.In VWD, open the database explorer by selecting the View | DataBase Explorer menu selection. Find your database under the database connections node of the tree view. If your database is not listed, right-click the data connections node in the tree view, select the add connection option, select the Microsoft SQL Server File option, and browse to the PhotoDB.mdf file in the App_Data folder of the site. This should bring up your connection within the database Explorer window.

Chapter 7

2.Now that you have a valid database tree, expand it to see the Tables node, and drill down to the Photo table. Right-click the Tables folder and select the Add New Table option. The new table can be named Comment, and will serve as the repository for comments made and answered on any of the photos in any collection. The field names and data types to be used in the comment table would be as follows:

Field

DataType

Description

 

 

 

CommentID

Integer

The auto-generated ID for the comment record.

photoID

Integer

The ID of the photo to which this comment applies.

Description

varchar(MAX)

The actual text of the comment or question.

Timestamp

Datetime

The auto-generated insert date and time of the comment.

email

varchar(MAX)

The email address of the user.

3.Save the table by clicking File Save Comment.

4.From Design View, shown in Figure 7-1, select the commentID field, and in the Identity Specification property, set it to Yes. Save the table by clicking File Save Comment.

Figure 7-1

28

Modifying the Wrox Photo Album

5.From this same Design View, select the timestamp field, and set the Default Value property to GetDate() (see Figure 7-2). This will allow the database to record the date and time for the insert at the time it occurs. Save the table by clicking File Save Comment.

Figure 7-2

6.In the Solution Explorer, right click the App_Code\Bll folder and select the Add New Item option. Select a new class, and name it Comment.vb. In the comment.vb class, add the following code:

Imports Microsoft.VisualBasic

Public Class Comment

Private _photoid As Integer

Private _description As String

Private _email As String

Public Sub New(ByVal mPhotoID As String, ByVal mDescription As String, ByVal mEmail As String)

MyBase.New() _photoid = mPhotoID

29

Chapter 7

_description = mDescription _email = mEmail

End Sub

Public ReadOnly Property PhotoID() As Integer

Get

Return _photoid

End Get

End Property

Public ReadOnly Property Description() As String

Get

Return _description

End Get

End Property

Public ReadOnly Property Email() As String

Get

Return _email

End Get

End Property

End Class

7.Open up the PhotoDB.vb class in the App_Code\Dal folder. Add a new function entitled InsertComment. This function will accept a comment class object as a parameter and add the comment to the comment table within the database. Use the following as the code for the

InsertComment function:

Public Shared Function InsertComment(ByVal c As Comment) As Boolean Try

‘Declare the objects for data access Dim conn As New SqlConnection()

Dim cmd As New SqlCommand() ‘set the connection string

conn.ConnectionString = PhotoDB.ConnectionString cmd.Connection = conn

conn.Open()

cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = “add_comment”

‘ Create a SqlParameter for each parameter in the stored proc.

Dim photoid As New SqlParameter(“@photoid”, c.PhotoID)

Dim description As New SqlParameter(“@description”, c.Description) Dim email As New SqlParameter(“@email”, c.Email)

‘add each parameter to the command object cmd.Parameters.Add(photoid) cmd.Parameters.Add(description) cmd.Parameters.Add(email) cmd.ExecuteNonQuery()

Return True

Catch ex As Exception

30

Modifying the Wrox Photo Album

Throw (ex)

End Try

End Function

8.Right click the stored procedures node in the Database Explorer, and select the Add New Stored Procedure option. Then, enter the following for the stored procedure:

CREATE PROCEDURE dbo.add_comment

(

@photoID int,

@description varchar(1000), @email varchar(300)

)

AS

INSERT INTO comment

(photoID, description, email) VALUES (@photoID, @description, @email)

9.In the Solution Explorer, navigate to the root of the site. Open up the Viewphoto.aspx WebForm file, and click the Source View to see the HTML markup within the page. In the Viewphoto.aspx WebForm, add a new SqlDataSource with the following HTML markup in order to display comments with their corresponding images. This will select records from the comment table based on the photoID passed to the page as a querystring variable. The WHERE clause should filter the records based on the photoID.

<asp:SqlDataSource ID=”SqlDataSource2” runat=”server” ConnectionString=”<%$ ConnectionStrings:ConnectionStringComments %>” SelectCommand=”SELECT [description], [timestamp], [email] FROM [comment] WHERE ([photoID] = @photoID)” ProviderName=”System.Data.SqlClient”>

<SelectParameters>

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

</SelectParameters>

</asp:SqlDataSource>

10.Now there are two SqlDataSource controls on the page. The first data source control, named SqlDataSource1, is for displaying the existing image and description, and so on. And the other control, named SqlDataSource2, is for displaying comments made on this particular image. Scroll towards the middle of the page, after the end tag of the DataList ASP.NET data control, and add a new DataList control to the form from the Toolbox. In the Smart Tag dialog for this new DataList, configure it to connect to the new SqlDataSource2 data source, and pull the description, timestamp, and email fields. Format the layout or positions of the HTML and database field inserts to your desire. The end result of a configured data list as described is displayed below:

<br /> <br />

<asp:DataList ID=”DataList2” runat=”server” DataSourceID=”SqlDataSource2”> <ItemTemplate>

<asp:Label ID=”descriptionLabel” runat=”server” Text=’<%# Eval(“description”) %>’>

</asp:Label> - (<i><asp:Label ID=”emailLabel” runat=”server” Text=’<%# Eval(“email”) %>’></asp:Label> on <asp:Label ID=”timestampLabel” runat=”server” Text=’<%# FormatDate(Eval(“timestamp”)) %>’></asp:Label></i>)

31

Chapter 7

<br /> </ItemTemplate>

</asp:DataList>

11.Next, add a few controls to the form to allow other users to insert comments into the system. First, add two TextBox controls, txtEmail and txtDesc, used to capture the user’s email address and comments. Make the txtDesc field’s TextMode=”MultiLine” and set the Height property to 50px, so it extends to several lines. Add a button to the form below these two text boxes, with an OnClick=”AddComment”. This means the button will fire a new procedure when it is clicked. This procedure is called AddComment, which will create a new comment class object, and pass in the photoID, user’s email address, and description to the class constructor. Then, it will pass the new comment class object to the data access class for insertion into the database. See below for the code for both the form fields and the AddComment function:

<br />

<br />Want to comment on this picture?<br />

<asp:TextBox ID=”txtEmail” runat=”server”></asp:TextBox>Your Email Address<br /> <asp:TextBox ID=”txtDesc” runat=”server” Height=”50px” Width=”200px” TextMode=”MultiLine”></asp:TextBox>

Comment<br /><br />

<asp:Button ID=”Button1” runat=”server” Text=”Save” OnClick=”AddComment” /> <br />

<br />

<script runat=”server”>

Protected Sub AddComment(ByVal sender As Object, ByVal e As System.EventArgs)

If txtDesc.Text <> “” And txtEmail.Text <> “” Then

Dim c As New Comment(Request.QueryString(“PhotoID”), txtDesc.Text,

txtEmail.Text)

‘hand off the new comment class object to the data access class to allow for insertion

Dim result As Boolean = DataAccessLayer.InsertComment(c)

‘clear the fields txtEmail.Text = “” txtDesc.Text = “”

‘refresh the data list of comments to show this one Page.DataBind()

End If

End Sub </script>

32

Modifying the Wrox Photo Album

12.Run the project, clicking on the collection of your choice, and one of the photos in the collection. You will see the new comment area at the bottom. Add a comment and your screen would look like Figure 7-3.

Figure 7-3

With this proposed comments feature, you allow interactivity between the website author and the user, making the site even more engaging. It’s a great way to involve the user in the future of the site, and draw them back for more of your great photography!

33

8

Modifying the Customer

Suppor t Site

One possible extension to the Customer Support Site is to allow your users to contact you through a Contact form. That way, your users can ask you questions about your product. These questions and their answers can then be added to the Frequently Asked Questions list on the site.

The first part of this section guides you through the process of creating such a feature. It shows you how to create the form and how to send an email to your support department when a user fills in the form. As a bonus, you’ll also learn how to store the user’s details in a profile so repeating customers don’t have to enter their details over and over. To implement the Contact form, follow these steps:

1.Start by adding a new page called Contact.aspx in the ContentFiles folder. Base this page on the MainMaster.master page.

2.In the MainMenu.ascx control in the Controls folder, add a link to this new page so users can access it.

3.On the Contact page, create a form with text boxes for the user’s name, email address, and their question or remarks. Name these controls txtUserName, txtEmailAddress, and txtComments, respectively. Set the TextMode property of txtComments to MultiLine. Add a button called btnSave with the text of Send Comments.

4.Add a checkbox called chkRememberMe with a descriptive text offering the user to have their details saved for them. Next, add a label called lblStatus that is used to tell the user their message was sent successfully.

5.If you want, you can change the page layout to whatever you see fit. You can use tables and labels to improve the readability of the page.

6.Double click the button in Design View so VWD adds the required code to handle the Click event of the button.

7.Switch to Design View again and double click anywhere on the page. This adds the code to handle the Page_Load event.

Chapter 8

8.Next, open the Web.config file and within the <system.web> element add the following code that adds a few properties to the Profiles for the current site:

<anonymousIdentification enabled=”true” /> <profile>

<properties>

<add name=”Name” allowAnonymous=”true” />

<add name=”EmailAddress” allowAnonymous=”true” /> </properties>

</profile>

9.If you haven’t already done so during setup, configure the application to use a provider that supports the Profile feature. To do so, choose Website ASP.NET Configuration in VWD. In the Web Site Administration Tool, click Provider Configuration and then click Select a Single Provider for all Site Management Data. Make sure AspNetSqlProvider is selected and click the Test link to ensure the provider works correctly.

10.Return to the Web.config file and scroll all the way to the end of the file until you see the <system

.net> node. Change the host attribute of the <network> element to the name of the mail server you are using for sending mail. Depending on your setup, this can be localhost or the SMTP server of your provider.

11.At the top of the page, add an Imports statement for System.Net.Mail and then add the following code in the button’s Click event handler that you added in Step 6:

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles btnSave.Click

Dim subject As String = “Response from the Web Site”

Dim message As String = String.Format(“User {0} with the “ & _

“email address: {1} left the following message “ & ControlChars.CrLf & “{2}”, _ txtUserName.Text, txtEmailAddress.Text, txtComments.Text)

Dim mySmtpClient As SmtpClient = New SmtpClient() Dim myMessage As MailMessage = New MailMessage( _

“You@YourProvider.Com”, “You@YourProvider.Com”, subject, message)

myMessage.IsBodyHtml = False

mySmtpClient.Send(myMessage)

If chkRememberMe.Checked Then

Profile.Name = txtUserName.Text

Profile.EmailAddress = txtEmailAddress.Text

Else

Profile.Name = String.Empty

Profile.EmailAddress = String.Empty

End If

lblStatus.Text = “Your message was sent successfully” End Sub

Be sure to replace You@YourProvider.Com with your email address. This code formats the message body by taking the values from the textboxes and appending it to the string message. Then a new MailMessage is created which is eventually sent by the Send method of the SmtpClient object. At the end of the method, the user’s details are stored in the site’s Profile database if the user chose to save the details.

36