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

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

640 Chapter 13 • Creating a Message Board with ADO and XML

Figure 13.60 Continued

txtEmailAddress.Text = Me.CurrentUser.Email End If

Me.ApplyStyles(Me.Controls)

End Sub

Private Sub btnUpdate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnUpdate.Click

If Page.IsValid Then

If txtNewPassword.Text.Trim() <> "" Then

Me.CurrentUser.Password = txtNewPassword.Text

End If

Me.CurrentUser.FirstName = txtFirstName.Text

Me.CurrentUser.LastName = txtLastname.Text

Me.CurrentUser.Email = txtEmailAddress.Text

Me.CurrentUser.Update()

lblMessage.Visible = True End If

End Sub

Updating the user profile is rather easy. First, the Page_Load method checks to make sure there is a valid, logged in user. If not, it redirects the user back to default.aspx. If the user is logged in and the page has not posted back to itself yet, then it sets the values of the text boxes to the existing values of the current user object. Afterward, it applies the styles to the page and exits.

When the Update button is clicked, the btnUpdate_Click method is called. The subroutine first checks to make sure all the validation controls have returned valid results. If not, it exits the subroutine. If they have returned valid results, it first checks to see if the user entered a new password, and if so, sets the current user object’s password to what the user entered. Next, each of the User objects’ fields are set to what the user entered, then the User object is updated to the database. Finally, the message label indicating that the profile was updated successfully is displayed.

www.syngress.com

Creating a Message Board with ADO and XML • Chapter 13

641

Creating Threads and Posts

The last thing to do for registered users is generate a page for them to create new threads and posts. In order to get to this page, let’s take a look at board.aspx and thread.aspx again.We need to add a LinkButton to each one.When clicked, that link button needs to redirect the user to createpost.aspx. See Figures 13.61 and 13.62.

Figure 13.61 LinkButton1_Click Event (Board.aspx)

Private Sub LinkButton1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles LinkButton1.Click Dim boardId As String

boardId = Request.QueryString.Item("boardid") Response.Redirect("createPost.aspx?boardName=" & boardId)

End Sub

Figure 13.62 LinkButton1_Click Event (Thread.aspx)

Private Sub LinkButton1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles LinkButton1.Click Dim boardId As String

Dim threadId As Long

boardId = Request.QueryString.Item("boardId") threadId = CLng(Request.QueryString.Item("threadId"))

Response.Redirect("createPost.aspx?boardName=" & boardId & _ "&threadId=" & threadId.ToString())

End Sub

The function of these buttons is almost the same.The first one redirects the user to createpost.aspx?boardName=[The selected Board], and the second redirects the user to createpost.aspx?boardName=[The selected Board]&threadId=[The selected Thread].The same page handles the creation of new Threads and Posts, so if you are creating a new Post, you just pass in the ThreadID along with the board name. If you are creating a brand new Thread, you just pass in the board

www.syngress.com

642 Chapter 13 • Creating a Message Board with ADO and XML

name. Let’s take a look at createpost.aspx to see what controls are on that page. See Figure 13.63.

Figure 13.63 The Create Post Page

The create post page contains the necessary controls to accept user input and create a new thread and/or post.The other controls on the page are a

ValidationSummary, two RequiredFieldValidators, and a Panel that contains the current Thread information. Obviously, if the user is creating a new Thread and Post, the Thread panel will not be visible, whereas, if the user is creating a new Post inside a Thread, the Thread panel will be visible and display the appropriate Thread subject. Let’s take a look at the code necessary to initialize this form in Figure 13.64.

Figure 13.64 The Code-Behind Initialization (Createpost.aspx.vb)

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'only logged in users are allowed in this page

If Me.IsLoggedIn = False Then

Response.Redirect("default.aspx")

End If

Continued

www.syngress.com

Creating a Message Board with ADO and XML • Chapter 13

643

Figure 13.64 Continued

mBoardName = Request.Item("boardName")

If Request.Item("threadId") Is Nothing Then

mThreadID = 0

Else

mThreadID = CLng(Request.Item("threadId"))

End If

mBoard = New dotBoardObjects.board(mBoardName) lblBoardName.Text = mBoard.Name

If mThreadID = 0 Then

pnlShowThread.Visible = False

Else

pnlShowThread.Visible = True

mThread = mBoard.ChildThread(mThreadID) End If

If Not Me.IsPostBack Then

'put the default values in the thread and board text boxes If mThreadID <> 0 Then

txtThreadSubject.Text = mThread.Subject lblThreadName.Text = mThread.Subject

End If

End If

Me.ApplyStyles(Me.Controls)

End Sub

First, what we do is verify that there is a logged in user. If there isn’t, we redirect the user back to the default page. If the user is valid, we get a reference to the current board and if the ThreadID was passed in, we get a reference to the appropriate Thread as well. Finally, if the page hasn’t posted back to itself and we have a current Thread, we default the text box and label values with the Thread’s

www.syngress.com

644 Chapter 13 • Creating a Message Board with ADO and XML

subject. All that’s left is to take a look at the code that actually creates Posts and Threads, as shown in Figure 13.65.

Figure 13.65 btnCreatePost_Click Code (Createboard.aspx.vb)

Private Sub btnCreatePost_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCreatePost.Click

If Me.IsValid = True Then

If mThreadID <> 0 Then

'we're adding a post to a thread. do nothing here

Else

'we're creating a new thread and adding a post mBoard.CreateThread(txtThreadSubject.Text, Me.CurrentUser) 'let's find that thread. it will be the first one

'in the list

mThread = mBoard.ChildThreads.Item(0) End If

mThread.CreatePost(txtThreadSubject.Text, _ TextBox1.Text, Me.CurrentUser)

'redirect the user to the current thread Response.Redirect("thread.aspx?boardId=" & mBoardName & _

"&threadId=" & mThread.ID.ToString())

End If

End Sub

What happens in this bit of code is that we first check to make sure the page is valid. If not, we do nothing; otherwise, we attempt to create the Thread and/or Post. If the ThreadID is currently “0” (that is, no ThreadID was given to the page), then we create a new Thread and set the private mThread variable to the new Thread (remember that when adding a new Thread, since Threads are ordered by their ThreadID field, new Threads appear at the top of the ThreadList). Lastly, we create a new Post from the current Thread object and redirect the user to the thread.aspx page to view the new and/or updated Thread.

www.syngress.com

Creating a Message Board with ADO and XML • Chapter 13

645

Building the Administrative Interface

Administrators need to do a few things that other people can’t. First, they need the ability to delete anything—boards, threads, and posts.They also need the ability to edit any post, and modify any user’s admin or banned status. Let’s take a look at the useradmin.aspx screen in Figure 13.66.

Figure 13.66 The User Admin Page

This page allows administrators to promote other users to administrator status, and ban problematic users from logging into the site. First, we have a DropDownList control that we will DataBind to a DataSet.There is also a LinkButton that will show the admin panel at the bottom once we’ve selected a user to administer.The two radio button lists will be used to display and set the current admin/banned status of the selected user. Finally, when the user clicks the Modify User button, the current user will be updated with the new banned and admin values the administrator entered. Let’s first take a look at the code necessary to set up the form in Figure 13.67.

www.syngress.com

646 Chapter 13 • Creating a Message Board with ADO and XML

Figure 13.67 The Page_Load Method (Admin.aspx.vb)

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'only logged-in admins can enter this page

If Me.IsLoggedIn = False Then

Response.Redirect("default.aspx")

ElseIf Me.CurrentUser.IsAdmin = False Then

Response.Redirect("default.aspx")

End If

'get the users bound to the drop down list If Not Me.IsPostBack Then

Dim myUsers As DataSet

Dim sql As String

sql = "SELECT UserID, UserName FROM Users"

myUsers = dotBoardObjects.DataControl.GetDataSet(sql) dlUsers.DataTextField = "Username" dlUsers.DataValueField = "UserID"

dlUsers.DataMember = "data" dlUsers.DataSource = myUsers dlUsers.DataBind()

End If

Me.ApplyStyles(Me.Controls)

End Sub

The first thing this method does is guarantee that there is a logged in user, and that the currently logged in user is an administrator. If either of these is not true, it sends the user back to default.aspx. Next, it makes sure the page has not posted back to itself; since there’s no need to DataBind a drop-down list every time the page is executed, as ASP.NET will handle that for us. If the page has not posted back to itself, it builds a SQL statement to retrieve the UserIDs and Usernames from the Users table in the database. It then gets a DataSet from the dotBoardObjects.DataControl class, and dynamically binds the DropDownList to the

DataSet. Finally, it applies the styles to this page and exits.

The next thing we need to do is get the ability to select a user from the drop-down list, and have the page load that user’s information.The click event

www.syngress.com

Creating a Message Board with ADO and XML • Chapter 13

647

handler for the Choose User link handles this. Let’s take a look at the code for it in Figure 13.68.

Figure 13.68 The lnkChooseUser_Click Method (Admin.aspx.vb)

Private Sub lnkChooseUser_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles lnkChooseUser.Click Dim userID As Long

userID = CLng(dlUsers.SelectedItem.Value) Dim myUser As dotBoardObjects.User myUser = New dotBoardObjects.User(userID)

If myUser.IsBanned = True Then rblBanned.Items(1).Selected = True

Else

rblBanned.Items(0).Selected = True End If

If myUser.IsAdmin = True Then rblAdmin.Items(0).Selected = True

Else

rblAdmin.Items(1).Selected = True End If

rblBanned.Visible = True rblAdmin.Visible = True

Panel1.Visible = True

End Sub

This gets the user ID from the DropDownList’s SelectedItem.Value property, and creates a new user object from it. Next, the appropriate radio buttons are selected depending on whether or not the user is banned or is an admin. Finally, the admin panel and the two radio button lists are set to visible so they will appear when the page refreshes. Next, we need to handle when the administrator clicks the Modify User button and update the selected user based on what the administrator entered in. See Figure 13.69 for the code involved.

www.syngress.com

648 Chapter 13 • Creating a Message Board with ADO and XML

Figure 13.69 The btnModify_Click Method (Admin.aspx.vb)

Private Sub btnModify_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnModify.Click Dim userID As Long

userID = CLng(dlUsers.SelectedItem.Value) Dim myUser As dotBoardObjects.User myUser = New dotBoardObjects.User(userID)

'we now have the user, so let's set his admin/banned properties If rblBanned.Items(0).Selected = True Then

'the user is not banned myUser.IsBanned = False

Else

myUser.IsBanned = True End If

If rblAdmin.Items(0).Selected = True Then 'the user is an admin

myUser.IsAdmin = True

Else

myUser.IsAdmin = False End If

myUser.Update() End Sub

Just like before, the first thing we do is get a reference to the selected User object.The next step is to determine which radio buttons were selected, and set the IsAdmin and IsBanned properties accordingly.The last step is to update the selected user by calling its Update method. Now you can promote other users to be administrators or ban them from entering your site again. If a banned user attempts to log on, they will receive an error explaining to that their account was banned.You may be wondering why we don’t just delete the banned user.We don’t do this because the Thread and Post tables are dependent on the User table,

www.syngress.com

Creating a Message Board with ADO and XML • Chapter 13

649

and deleting a User from the User table would not be allowed due to the relationships involved.

The other thing that administrators can do is create and delete boards, delete threads, and delete posts. Let’s start with creating a board.The first step involved in this is adding a new LinkButton to the user area user control.This button will be named “lnkCreateBoard” and will have its text property set to Create New Board. Once clicked, it should redirect the user to createboard.aspx. Let’s take a look at that code in Figure 13.70.

Figure 13.70 The lnkCreateBoard_Click Code (Userarea.ascx.vb)

Private Sub lnkCreateBoard_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles lnkCreateBoard.Click

Response.Redirect("createboard.aspx")

End Sub

Now that we have the administrator going to the create board page, let’s take a look at that page. See Figure 13.71.

Figure 13.71 The Create Board Form

Like all our other pages that accept user input, this page has controls on it for every piece of information we need to perform the task at hand. Also, like the

www.syngress.com