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

ASP.NET 2.0 Everyday Apps For Dummies (2006)

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

Chapter 10: Building a Web Forum 367

cmd.Parameters.AddWithValue(“author”, _ txtEmail.Text)

cmd.Parameters.AddWithValue(“lastpostdate”, _ DateTime.Now)

con.Open()

cmd.ExecuteNonQuery()

‘get the thread ID cmd.CommandText = getThreadID Dim threadid As String

threadid = cmd.ExecuteScalar().ToString()

‘insert the message cmd.CommandText = insertMessage cmd.Parameters.Clear()

cmd.Parameters.AddWithValue(“threadid”, _ threadid)

cmd.Parameters.AddWithValue(“author”, _ txtEmail.Text)

cmd.Parameters.AddWithValue(“date”, _ DateTime.Now)

cmd.Parameters.AddWithValue(“message”, _ txtMessage.Text)

cmd.ExecuteNonQuery()

con.Close()

Response.Redirect(“Messages.aspx?topic=” _

+Request.QueryString(“topic”) _

+“&thread=” + threadid)

End Sub

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

Response.Redirect(“Threads.aspx?topic=” _

+ Request.QueryString(“topic”))

End Sub

6

7

8

9

End Class

Building the New Message Page

The last page of the Forum application is the New Message page, which lets the user post a reply to an existing thread. The following sections lay out the details of the .aspx and code-behind files for this page.

368 Part V: Building Community Applications

The NewMessage.aspx page

The .aspx file for the New Message page is shown in Listing 10-15. This page displays the topic name in a FormView control at the top of the page. Then text boxes are used to get the user’s e-mail address and the message text. Note that there is no text box for the subject. That’s because the thread — not the individual messages that make it up — provides the subject.

Listing 10-15: The NewMessage.aspx page

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”NewMessage.aspx.cs” Inherits=”NewMessage”

Title=”Post Reply” %>

<asp:Content ID=”Content1” Runat=”Server” ContentPlaceHolderID=”ContentPlaceHolder1” >

<asp:FormView ID=”FormView1” runat=”server” DataSourceID=”SqlDataSource1”> <ItemTemplate>

<h3>

Reply To Topic: <asp:Label ID=”nameLabel”

runat=”server”

Text=’<%# Bind(“name”) %>’ />

</h3>

</ItemTemplate>

</asp:FormView>

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server”

ConnectionString

=”<%$ ConnectionStrings:ForumConnectionString %>”

SelectCommand=”SELECT [name], [description] FROM [Topics]

WHERE ([topicid] = @topicid)”> <SelectParameters>

<asp:QueryStringParameter

Name=”topicid”

QueryStringField=”topic” Type=”Int32” />

</SelectParameters>

</asp:SqlDataSource>

<asp:FormView ID=”FormView2” runat=”server” DataSourceID=”SqlDataSource2”> <ItemTemplate>

<h3>

Thread:

1

2

3

4

5

6

Chapter 10: Building a Web Forum 369

<asp:Label ID=”subjectLabel”

 

runat=”server”

 

Text=’<%# Bind(“subject”) %>’ />

 

</h3>

 

</ItemTemplate>

 

</asp:FormView>

 

<asp:SqlDataSource ID=”SqlDataSource2”

7

runat=”server”

 

ConnectionString

 

=”<%$ ConnectionStrings:ForumConnectionString

%>”

 

SelectCommand=”SELECT [subject]

 

FROM [Threads]

 

WHERE ([threadid] = @threadid)”>

 

<SelectParameters>

8

<asp:QueryStringParameter

 

Name=”threadid”

 

QueryStringField=”thread”

 

Type=”Int32” />

 

</SelectParameters>

 

</asp:SqlDataSource>

 

<table border=0>

 

<tr><td Width=”125” valign=”top”>

 

Your email address:

 

</td><td width=”300”>

 

<asp:TextBox ID=”txtEmail” runat=”server”

9

Width=”300px” />

 

<asp:RequiredFieldValidator

 

ID=”RequiredFieldValidator1”

 

runat=”Server”

 

ControlToValidate=”txtEmail”

 

ErrorMessage=”Required.” />

 

</td></tr>

 

<tr><td width=”125” valign=”top”>

 

Message:

 

</td><td width=”300”>

 

<asp:TextBox ID=”txtMessage”

10

runat=”server”

 

TextMode=”MultiLine”

 

Width=”300px” Height=”300px”/>

 

<asp:RequiredFieldValidator

 

ID=”RequiredFieldValidator2”

 

runat=”Server”

 

ControlToValidate=”txtMessage”

 

ErrorMessage=”Required.” />

 

</td></tr>

 

 

 

(continued)

370 Part V: Building Community Applications

Listing 10-15 (continued)

</table>

 

<asp:Button ID=”btnPost” runat=”server”

11

OnClick=”btnPost_Click”

 

Text=”Post Reply” /> 

 

<asp:Button ID=”btnCancel” runat=”server”

12

OnClick=”btnCancel_Click”

 

Text=”Cancel” />

 

</asp:Content>

Here’s a closer look at 12 key elements of this file:

1 If you use Visual Basic instead of C#, you’ll need to change the

Language, AutoEventWireup, and CodeFile attributes.

2 The <Content> element provides the content that’s displayed for the page.

3 This FormView control, which is bound to the SqlDataSource1 data source, displays the topic name and description.

4 The SqlDataSource1 data source retrieves the topic information from the Topics table.

5 The value of the topicid parameter is bound to the query string named topic.

6 This FormView control displays the thread subject, which is bound to SqlDataSource2.

7 The SqlDataSource2 data source retrieves the thread subject from the Threads table.

8 The threadid parameter is bound to the thread query string.

9 This text box accepts the user’s e-mail address. A RequiredFieldValidator is used to make sure the user enters an address.

10 This multi-line text box accepts the message. A RequiredFieldValidator is used to make sure the user enters a message.

11 The btnPost button creates the new thread. If you’re working in Visual Basic, you’ll need to omit the OnClick attribute.

12 The btnCancel button cancels the new thread. Again, you’ll need to omit the OnClick attribute if you’re working in Visual Basic.

Chapter 10: Building a Web Forum 371

The code-behind file for the New Message page

Listings 10-16 and 10-17 show the C# and Visual Basic versions of the codebehind file required by the New Message page. These code-behind files contain methods that handle the Click event for the Post Message and Cancel buttons.

Listing 10-16: The code-behind file for the New Message page (C#)

using

System;

 

using

System.Data;

 

using

System.Configuration;

 

using

System.Collections;

 

using

System.Web;

 

using

System.Web.Security;

 

using

System.Web.UI;

 

using

System.Web.UI.WebControls;

 

using

System.Web.UI.WebControls.WebParts;

 

using

System.Web.UI.HtmlControls;

 

using

System.Web.Configuration;

1

using

System.Data.SqlClient;

2

public partial class NewMessage : System.Web.UI.Page

 

{

 

 

protected void btnPost_Click(

3

 

object sender, EventArgs e)

 

{

 

 

 

// set up the data objects

4

 

string cs = WebConfigurationManager

 

 

.ConnectionStrings[“ForumConnectionString”]

 

 

.ConnectionString;

 

 

string insertMessage = “INSERT Messages “

 

 

+ “(threadid, author, date, message) “

 

 

+ “VALUES(@threadid, uthor, @date, @message);”

 

+ “UPDATE Threads “

 

 

+ “SET replies = replies + 1”

 

 

+ “WHERE threadid = @threadid”;

 

 

SqlConnection con = new SqlConnection(cs);

 

 

SqlCommand cmd

 

 

= new SqlCommand(insertMessage, con);

 

 

// get the query strings

5

 

string threadid = Request.QueryString[“thread”];

 

string topicid = Request.QueryString[“topic”];

 

 

// insert the message

6

 

cmd.CommandText = insertMessage;

 

 

 

 

(continued)

372 Part V: Building Community Applications

Listing 10-16 (continued)

cmd.Parameters.Clear();

cmd.Parameters.AddWithValue(“threadid”,

threadid);

cmd.Parameters.AddWithValue(“author”,

txtEmail.Text);

cmd.Parameters.AddWithValue(“date”,

DateTime.Now);

cmd.Parameters.AddWithValue(“message”,

txtMessage.Text);

con.Open();

cmd.ExecuteNonQuery();

con.Close();

Response.Redirect(“Messages.aspx?topic=” + topicid + “&thread=” + threadid);

}

protected void btnCancel_Click( object sender, EventArgs e)

{

Response.Redirect(“Messages.aspx?topic=”

+Request.QueryString[“topic”]

+“&thread=”

+Request.QueryString[“thread”]);

}

}

7

8

The following paragraphs guide you through the most important lines of these listings:

1 This line is required because the code-behind file uses the WebConfigurationManager class to retrieve the databaseconnection string from the web.config file.

2 This line is required so the code-behind file can use ADO.NET classes to access SQL databases.

3 The btnPost_Click method executes when the user clicks the Post Message button. This method writes a row to the Messages table and updates the reply count in the Threads table.

4 These lines set up the ADO.NET database objects used by the btnPost_Click method, one at a time, in a specific sequence:

1.The connection string is retrieved.

2.A string variable is created and initialized with the INSERT and UPDATE statement that writes the new message row and updates the thread reply count.

3.A database connection object is created.

4.A new SqlCommand object is created.

Chapter 10: Building a Web Forum 373

5 These lines retrieve the thread and topic query strings and assign them to local variables named (respectively) threadid and topicid.

6 These lines set up the parameters required by the INSERT and UPDATE statement, open the connection, execute the INSERT and UPDATE commands, and close the connection.

7 This line redirects the user to the Messages.aspx page, which shows the new message added to the end of the thread.

8 This method executes when the user clicks the Cancel button. It simply redirects the user back to the Messages.aspx page.

Listing 10-17: The code-behind file for the New Message page (VB)

Imports System.Web.Configuration

1

Imports System.Data.SqlClient

2

Partial Class NewMessage

 

Inherits System.Web.UI.Page

 

Protected Sub btnPost_Click( _

3

ByVal sender As Object, _

 

ByVal e As System.EventArgs) _

 

Handles btnPost.Click

 

‘set up the data objects

4

Dim cs As String

 

cs = WebConfigurationManager _

 

.ConnectionStrings(“ForumConnectionString”) _

.ConnectionString

 

Dim insertMessage As String

 

insertMessage = “INSERT Messages “ _

 

+“(threadid, author, date, message) “ _

+“VALUES(@threadid, uthor, @date, @message);”

_

+“UPDATE Threads “ _

+“SET replies = replies + 1” _

+“WHERE threadid = @threadid”

Dim con As SqlConnection con = New SqlConnection(cs) Dim cmd As SqlCommand

cmd = New SqlCommand(insertMessage, con)

‘get the query strings

5

Dim threadid As String

 

Dim topicid As String

 

threadid = Request.QueryString(“thread”)

 

topicid = Request.QueryString(“topic”)

 

‘insert the message

6

cmd.CommandText = insertMessage

 

(continued)

374 Part V: Building Community Applications

Listing 10-17 (continued)

cmd.Parameters.Clear() cmd.Parameters.AddWithValue(“threadid”, _

threadid) cmd.Parameters.AddWithValue(“author”, _

txtEmail.Text) cmd.Parameters.AddWithValue(“date”, _

DateTime.Now) cmd.Parameters.AddWithValue(“message”, _

txtMessage.Text)

con.Open()

cmd.ExecuteNonQuery()

con.Close()

Response.Redirect(“Messages.aspx?topic=”

7

+ topicid + “&thread=” + threadid)

 

End Sub

 

Protected Sub btnCancel_Click( _

8

ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles btnCancel.Click

Response.Redirect(“Messages.aspx?topic=” _

+ Request.QueryString(“topic”) _ + “&thread=” _

+ Request.QueryString(“thread”))

End Sub End Class

Chapter 11

Building a Blog Application

In This Chapter

Designing the Blog application

Creating the database for the Blog application

Building the Blog application’s pages

Ablog (short for weblog) is a Web application that lets users create their own Web pages where they can post their thoughts. Other users can visit

the blog, read the blog owner’s posts, and leave comments of their own. These days, blogging is one of the most popular activities — and applications — on the Internet.

There are many Web sites that let you create blogs, and free or inexpensive applications are available to host your own blogs. Still, you may want to create your own blogging application. If so, this chapter is for you. It presents a simple blog application written in ASP.NET 2.0.

The Blog application presented in this chapter requires that users register and log in to create a blog. Each registered user can create as many different blogs as he or she wants. Any visitor can read a blog and post comments without having to register or log in. The application relies on the built-in user registration features of ASP.NET 2.0. (You may want to refer to the

User Authentication application presented in Chapter 3 for further details of how the user-registration and login pages work.)

Designing the Blog Application

Because blogs are so popular on the Web, you can find plenty of examples of blog applications to provide inspiration for your design. The blog application in this chapter is relatively simple. It provides the following features:

Any visitor to the Web site can register to create an account. Once registered, a user can create one or more blogs.

376 Part V: Building Community Applications

When a registered user logs in, a My Blogs page is displayed to list the blogs that user has created. This page includes a link that lets the user create a new post for any of his or her blogs.

Blog posts consist of simple text with no embedded HTML or images.

Unregistered visitors can view blogs and leave comments but can’t create blogs. Comments consist of simple text with no HTML or images.

To keep things simple, this Blog application doesn’t provide for editing the blog title, description, posts, or comments once they’ve been created. In the real blogosphere, those features are desirable to include.

The Home page for the Blog application lists all blogs that have been created on the site. The title displayed for each blog is a link that takes the user to that blog.

When the visitor first displays a blog, the most recently created post is displayed, along with a list of previous posts. The visitor can use this list to display previous posts.

The Blog page also includes links that display comments for the current post and lets the visitor leave a comment.

Designing the User Interface

The Blog application uses a total of seven pages, as shown in Figure 11-1. Two of them are for logging in and registering; two of them are accessible only to registered users who have logged in. The other three are for viewing blogs and leaving comments.

The Blog Home page

The Home page for the Blog application (Default.aspx) is shown in Figure 11-2. As you can see, this page lists the blogs that are available on the site. In this example, two users have created blogs. (In a popular blog site, of course, there would be many more than two blogs to choose from.)

The “Blog-O-Rama” title and the links beneath it are provided by the Master Page, so they’re available throughout the site. They let the user return to the Home page, log in (or log out if the user is already logged in), register a new user account, and go to the My Blogs page. (The My Blogs page, as you’ll soon see, lists the blogs created by the currently logged-in user, lets the user add a new post to one of his or her blogs, and lets the user create a new blog.)