1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET Bible 2002 PHẦN 9 ppsx

68 206 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 1 MB

Nội dung

Field Name Data Type TopicID (Primary Key) AutoNumber Name Text The Threads table is a little more complicated, but not much (see Table 30-2). Table 30-2: The Threads table Field Name Data Type ThreadID (Primary Key) AutoNumber Name Text Topic Number The Topic column holds the TopicID of the row in the Topics table with which this thread is associated. The Name column holds the name of the thread. It should have some specific attributes set, as specified in Table 30-3. Table 30-3: The Thread's Name column attributes Attribute Value Required Yes Allow Zero Length No Indexed Yes (No Duplica tes) By setting these attributes, you assure that whenever a new row is added, the Name field is filled in and that it is filled in with a value that is different from any of the other names already in the table. In other words, all threads must have a unique name. The same attributes could have been set for the Topics table's Name field, but because it's the site administrator (and not users) who will be filling that table in, you can probably assume that the administrator will assure that the topics are right. The Messages table has the most columns (see Table 30-4). Table 30-4: The Messages table Field Name Data Type MessageID (Primary Key) AutoNumber Subject Text Message Memo Author Text Posted Date/Time Thread Number As in an e-mail message, the Subject line is used to title and summarize the contents of the message itself. The author of the message will be stored in Chatty as the e-mail address they enter. If your site authenticates its users, then you'll be able to put their username or their chosen handle into the Author field instead. The Posted column is important. It enables you to organize the messages in the right order within a thread. Finally, Thread holds the ThreadID of the row in the Threads table with which this message is associated. Creating the Database Once you've decided to go with a relational database, you're going to have to figure out how you want to organize the information into tables and columns. Chatty has two levels of organization for its messages: § Topics are the highest level and are chosen by the creator of the site. § Threads are essentially subtopics that the user can create. Messages, then, are always posted by the user to a thread, which in turn is under a topic. These storage needs can be accommodated with three tables: Topics, Threads, and Messages. Topics is the highest level, but is also the simplest. All you have to track is the topic's name. Table 30-1 shows the columns and data types. Table 30-1: The Topics table Field Name Data Type TopicID (Primary Key) AutoNumber Name Text The Threads table is a little more complicated, but not much (see Table 30-2). Table 30-2: The Threads table Field Name Data Type ThreadID (Primary Key) AutoNumber Name Text Topic Number The Topic column holds the TopicID of the row in the Topics table with which this thread is associated. The Name column holds the name of the thread. It should have some specific attributes set, as specified in Table 30-3. Table 30-3: The Thread's Name column attributes Attribute Value Required Yes Allow Zero Length No Indexed Yes (No Duplica tes) By setting these attributes, you assure that whenever a new row is added, the Name field is filled in and that it is filled in with a value that is different from any of the other names already in the table. In other words, all threads must have a unique name. The same attributes could have been set for the Topics table's Name field, but because it's the site administrator (and not users) who will be filling that table in, you can probably assume that the administrator will assure that the topics are right. The Messages table has the most columns (see Table 30-4). Table 30-4: The Messages table Field Name Data Type MessageID (Primary Key) AutoNumber Subject Text Message Memo Author Text Posted Date/Time Thread Number As in an e-mail message, the Subject line is used to title and summarize the contents of the message itself. The author of the message will be stored in Chatty as the e-mail address they enter. If your site authenticates its users, then you'll be able to put their username or their chosen handle into the Author field instead. The Posted column is important. It enables you to organize the messages in the right order within a thread. Finally, Thread holds the ThreadID of the row in the Threads table with which this message is associated. Seeding the Database In order to test the pages as you create them, you'll want to put some of your own data in the database to get you started. While you're in Microsoft Access creating the tables, go ahead and add a few topics, one or more threads for each topic and a message or two for each thread. Make sure the foreign keys (like the Topic column in the Thread table and the Thread column in the Message table) refer to the primary keys in rows you've already created in the associated tables. If you decide to use this completed application in your own Web sites, you'll have to use Microsoft Access to enter your topics. I haven't included a page to add or update topics since the discussion topics are usually created once by the Web site administrator and aren't often changed after that. Of course, if you do want easy access to update or add new topics, you can always use the code I've provided here for creating threads as a starting point for a new page that does what you want. Picking a Topic When a user visits Chatty, the first decision they have to make is which topic they want to browse. The Topics.aspx page, shown here, provides that opportunity: <%@ Page Explicit="True" Language="VB" Debug="True" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Page_Load( s As Object, e As EventArgs ) If Not isPostBack Then Dim TopicConnection As OleDbConnection Dim TopicCommand As OleDbCommand TopicConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ "c:\inetpub\wwwroot\Discuss\DiscussDB.mdb") TopicCommand = New OleDbCommand( _ "Select TopicID, Name from Topics", _ TopicConnection ) TopicConnection.Open() TopicDataList.DataSource = _ TopicCommand.ExecuteReader() TopicDataList.DataBind() TopicConnection.Close() End If End Sub Sub SelectTopic(s As Object, _ e As DataListCommandEventArgs) Dim TopicID,TopicName As String TopicName = e.CommandArgument TopicID = _ TopicDataList.DataKeys.Item( _ e.Item.ItemIndex).toString() Response.Redirect("Threads.aspx?TopicID=" & _ TopicID & "&TopicName=" & TopicName) End Sub </Script> <html> <head><title>Chatty Topics</title></head> <body> <font face="arial"> <h1><font color="DarkRed"> Chatty Discussion Forum</font></h1> <font size=5><i>Topics</i></font> <form Runat="Server"> <asp:DataList id="TopicDataList" cellpadding=10 cellspacing=0 gridlines="both" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" DataKeyField="TopicID" OnItemCommand="SelectTopic" Runat="Server"> <ItemTemplate> <asp:LinkButton id="TopicLink" Text='<%# Container.DataItem("Name") %>' CommandArgument='<%# Container.DataItem("Name") %>' Runat="Server"/> </Itemtemplate> </asp:DataList> </font> </form> </body> </html> Retrieving the topics When the page is first retrieved, a connection is made to the Access database, and a command object is created with a Select statement that retrieves the topic information: If Not isPostBack Then Dim TopicConnection As OleDbConnection Dim TopicCommand As OleDbCommand TopicConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ "c:\inetpub\wwwroot\Discuss\DiscussDB.mdb") TopicCommand = New OleDbCommand( _ "Select TopicID, Name from Topics", _ TopicConnection ) TopicConnection.Open() The Command object's ExecuteReader method is called, which executes the Select statement and then returns the results in the form of a DataReader object. This object is immediately assigned to the DataSource property of the TopicDataList control on this page. Calling the DataBind method of that control assures that the topics retrieved will appear there: TopicDataList.DataSource = _ TopicCommand.ExecuteReader() TopicDataList.DataBind() Displaying the topics The DataList control is used to quickly and easily display and format the information retrieved from the database: <asp:DataList id="TopicDataList" cellpadding=10 cellspacing=0 gridlines="both" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" DataKeyField="TopicID" OnItemCommand="SelectTopic" Runat="Server"> <ItemTemplate> <asp:LinkButton id="TopicLink" Text='<%# Container.DataItem("Name") %>' CommandArgument='<%# Container.DataItem("Name") %>' Runat="Server"/> </Itemtemplate> </asp:DataList> Most of the attributes specified for the DataList are concerned with how the data will be formatted. There are two important attributes that are not concerned with formatting: DataKeyField and OnItemCommand. I'll discuss OnItemCommand in the next section. The DataList expects to be associated with a result set, like that retrieved from a Select statement. The DataKeyField attribute identifies the column in the result set that is the key. The ItemTemplate tag is used to identify how individual items in this list should be displayed. In this case, I only want to display one item, the name of the topic. But I want to display it as a link. The LinkButton control makes this easy. The text is set to the value of the Container's "Name" data item. The container, in this case, is the DataList, and because it is bound to the Topics table result set, this will display the name of the topic. The CommandArgument is set to the same value. This assures that the Topic name is passed to the appropriate subroutine when the user clicks a topic. Handling topic selection When the user clicks a topic, the DataList's OnItemCommand attribute tells the control what to do. In this case, it tells it to call the SelectTopic subroutine: Sub SelectTopic(s As Object, _ e As DataListCommandEventArgs) Dim TopicID, TopicName As String TopicName = e.CommandArgument TopicID =__ TopicDataList.DataKeys.Item( _ e.Item.ItemIndex).toString() Response.Redirect("Threads.aspx?TopicID=" & _ TopicID & "&TopicName=" & TopicName) End Sub The topic name was passed as an argument, which comes in through the e object. That's easy enough to retrieve. The topic ID is a little tougher. The topic ID is in the list of DataKeys (because that column was specified as the DataKeyField for the DataList). So I use that list to retrieve the DataKey at the current ItemIndex. With the topic ID and name in hand, I'm ready to pass control on to another page, Threads.aspx. The Threads page is used to display the list of threads within the selected topic. But to do that, it must know which topic was chosen. I pass the topic ID and the topic name as arguments on the URL line. This makes them available to be accessed by name in the Threads page by using Request.QueryString. Picking a Thread Once the user has picked a topic that they're interested in, the Threads page enables them to see all the threads that have been created in that topic. It also provides a link that allows the user to go to a page and create a whole new thread, as show in here: <%@ Page Explicit="True" Language="VB" Debug="True" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Page_Load( s As Object, e As EventArgs ) If Not isPostBack Then Dim ThreadConnection As OleDbConnection Dim ThreadCommand As OleDbCommand ThreadConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ "c:\inetpub\wwwroot\Discuss\DiscussDB.mdb") ThreadCommand = New OleDbCommand( _ "Select ThreadID, Name from Threads " & _ "Where Topic=" & _ Request.QueryString("TopicID"), _ ThreadConnection ) ThreadConnection.Open() ThreadDataList.DataSource = _ ThreadCommand.ExecuteReader() ThreadDataList.DataBind() ThreadConnection.Close() End If End Sub Sub SelectThread( s As Object, _ e As DataListCommandEventArgs ) Dim ThreadID, ThreadName As String ThreadDataList.SelectedIndex = e.Item.ItemIndex ThreadName = e.CommandArgument ThreadID = _ ThreadDataList.DataKeys.Item( _ e.Item.ItemIndex).toString() Response.Redirect("Messages.aspx?TopicID=" & _ Request.QueryString("TopicID") & _ "&TopicName=" & Request.QueryString("TopicName") & _ "&ThreadID=" & ThreadID & _ "&ThreadName=" & ThreadName) End Sub </Script> <html> <head><title>Chatty Threads</title></head> <body> <font face="arial"> <h1><font color="DarkRed"> Chatty Discussion Forum</font></h1> <font size="5"><u> <%=Request.QueryString("TopicName") %> </u> Threads</font> <form Runat="Server"> <asp:DataList id="ThreadDataList" cellpadding=5 cellspacing=0 gridlines="both" Width="100%" DataKeyField="ThreadID" OnItemCommand="SelectThread" Runat="Server"> <ItemTemplate> <font size="2"> <asp:LinkButton id="ThreadLink" Text='<%# Container.DataItem("Name") %>' CommandArgument='<%# Container.DataItem("Name") %>' Runat="Server"/> </font> </Itemtemplate> <FooterTemplate> <font size="2"> <a href="NewThread.aspx?TopicID= <%=Request.QueryString("TopicID") %> &TopicName= <%=Request.QueryString("TopicName")%>"> <i>[ Create a New Thread ]</i></a> </font> </FooterTemplate> </asp:DataList> <br/> <a href="topics.aspx"> Return to list of <b>Topics</b></a> </form> </font> </body> </html> This page is actually very similar to the Topics page. It retrieves a list of threads and displays them in a DataList as LinkButtons, and the user may click any of the thread names to go to the Messages page. Using TopicID as selection criteria There are a few differences between this page and the Topics page. This page uses the TopicID in the query to get only the threads associated with the topic the user requested: ThreadCommand = New OleDbCommand( _ "Select ThreadID, Name from Threads " & _ "Where Topic=" & _ Request.QueryString("TopicID"), _ ThreadConnection ) I do this simply by concatenating the information from the QueryString into my Select statement. I could have, instead, used a parameter and filled in the parame ter with the TopicID. I decided not to in this case because it would have made the code more complicated and wouldn't really add any value. I do use parameters in both the Messages and the NewThread pages, and I'll explain why in a section called "Using parameters" later in this chapter. The Thread DataList Another difference from the Topics page is the DataList: <asp:DataList id="ThreadDataList" cellpadding=5 cellspacing=0 gridlines="both" Width="100%" DataKeyField="ThreadID" OnItemCommand="SelectTopic" Runat="Server"> This list isn't three columns. Instead, it's a single column, which means that each row stretches across the page, allowing for long thread names. More importantly, there's a new tag inside the DataList after the ItemTemplate tag: FooterTemplate. <FooterTemplate> <font size="2"> <a href="NewThread.aspx?TopicID= <%=Request.QueryString("TopicID") %> &TopicName= <%=Request.QueryString("TopicName")%>"> <i>[ Create a New Thread ]</i></a> </font> </FooterTemplate> The footer template appears as the last item in the DataList. This is the perfect spot to provide a link to a page that will allow the user to add their own thread. I pass the TopicID and TopicName to the NewThread page. Selecting a thread When the user clicks one of the threads in the DataList, the SelectThread subroutine is called. Again, this works much the same as the SelectTopic subroutine does in the Topics page. The only real difference is that it passes the thread ID and name to the Messages page as well as the topic ID and name as you can see here: Response.Redirect("Messages.aspx?TopicID=" & _ Request.QueryString("TopicID") & _ "&TopicName=" & Request.QueryString("TopicName") & _ "&ThreadID=" & ThreadID & _ "&ThreadName=" & ThreadName) Browsing Messages The Messages page displays all the messages posted for a particular topic and thread: <%@ Page Explicit="True" Language="VB" Debug="True" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Page_Load( s As Object, e As EventArgs ) If Not isPostBack Then BindData End If End Sub Sub BindData Dim MessageConnection As OleDbConnection Dim MessageCommand As OleDbCommand MessageConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\inetpub\wwwroot\Discuss\DiscussDB.mdb") MessageConnection.Open() [...]... ThreadCommand.Parameters("@TopicID").Value = _ Request.QueryString("TopicID") Try Connection.Open() ThreadResult = ThreadCommand.ExecuteNonQuery Catch excp As System.Data.OleDb.OleDbException If excp.Errors(0).NativeError = -1051213 49 Then Feedback.Text = "*** There " & _ "is already a thread with the name " & _ ThreadText.Text & " Please choose a " & _ "different name and click Post." Else Feedback.Text... with VB.NET's new error-trapping capabilities: Try Connection.Open() ThreadResult = ThreadCommand.ExecuteNonQuery Catch excp As System.Data.OleDb.OleDbException If excp.Errors(0).NativeError = -1051213 49 Then Feedback.Text = "*** There " & _ "is already a thread with the name " & _ ThreadText.Text & " Please choose a " & _ "different name and click Post." Else Feedback.Text... discussion forum is a very practical application It can be used on virtually any Web site where you want to enhance the sense of community In addition, this application has demonstrated a number of important ASP.NET techniques Some of the techniques are creating a hierarchical relationship among tables in a relational database; connecting to and retrieving data from a database using ADO.NET; displaying data... faster in productivity than you have gone before The integration of these tools has become much tighter and thus more efficient than in the past Because this is a book on Web application development with ASP.NET supplemented by VB.NET, you will first be taken on a tour through the VB.NET development environment This will give you the foundation required for you to be a topnotch NET developer Then you will... Identifying number for the database (Primary Key) Autonumber Auto FName First name Text 25 LName Last name Text 20 Address Mailing address Text 25 City City name Text 15 Postal ZIP or postal code Text 9 Province Province or state Text 2 Phone Telephone number Text 8 E_mail Note Internet eText 25 mail address There is a database file located on the companion Web site for this book A further reference . ]</i></a> </font> </FooterTemplate> < /asp: DataList> <br/> <a href="topics.aspx"> Return to list of <b>Topics</b></a>. < ;asp: textbox id="SubjectText" runat="server" columns="50"/></p> <p><font size="2">Message:</font><br /> < ;asp: textbox. Address:</font><br /> < ;asp: textbox id="AuthorText" runat="server" columns="50"/></p> <center> < ;asp: button runat="server"

Ngày đăng: 12/08/2014, 08:23