Creating the Quotations Page


At the conceptual level, the function of the quotations page is actually rather simple. Each time the page is displayed, whether for the first time or on postback, the page has to perform the following tasks:

  1. Read the quotations file and store the contents in an array

  2. Generate a random number

  3. Find the quotation in the file that corresponds to the random number

  4. Display the quotation

All of these tasks must be done when the page is first displayed. As mentioned in Chapter 4, a Page_Load event will be raised when the page starts. Therefore, we ll put all the code that performs these tasks in the Page_Load event handler.

Create the Quotations.aspx page

  1. Create a new page named  RandomQuotes.aspx. Save the page in the directory that contains the  quotations.txt file.

  2. Add the controls listed in the following table, and set their properties as indicated. Use the page shown in Figure 7-1 as a model for the layout.

    Control

    Property Settings

    Label

    ID: labelQuote

    Text: (Empty)

    Label

    ID: labelAuthor

    Text: (Empty)

    Button

    ID: buttonRefresh

    Text: Show Another Quote

As always, you can add whatever headings, graphics, and static text you want. For example, you could specify different Font properties for labelAuthor and labelQuote to distinguish the text displayed in those controls.

By the way, the buttonRefresh button appears here under slightly false pretenses. You re not going to create any code for this button s Click event, but remember that a button click always causes a postback of the page. When the postback happens, the page will run its Page_Load event handler again and thus pick a new quotation. I m having you put the button in there so that you ll be able to post the page, do a round trip, and get a new quotation.

Create the Page_Load event handler

  1. In the  RandomQuotes.aspx file, switch to Design view.

  2. At the top of the Properties window, click the drop-down list box arrow to show the list of objects, and then select Page, as shown in the following illustration.

    click to expand

  • On the Properties window toolbar, click the Events button.

  • Double-click the box for the Load event. The designer switches to Code view and generates a skeleton handler for the Page_Load event.

  • In previous chapters, you double-clicked controls to generate handlers for them. That technique doesn t work for the Page object, so you need to follow these steps to create the handler. For the Page_Load handler specifically (but not for event handlers for other controls), you can also just type in the skeleton code for the handler.

    Finding the Quotations File

    A problem associated with reading the text file is actually finding the file. Of course, you know that the file is in a specific folder, such as C:\WebMatrix\Quotations.txt. It s possible to hard-code a path like that into your program, but hard-coding a path is a bad idea for many reasons for example, you might move your application to another folder later. In addition, if you re using Internet Information Services (IIS) instead of the Web Matrix Web server, either on your own machine or on a hosting site, the quotations file will not be in C:\WebMatrix. Instead, it will be on a path such as C:\inetpub\wwwroot\yourapplication.

    The safest strategy for finding the text file is to determine in code where the current page is and then use that same path as the path to the quotations file. (That s why the text file and the page are saved in the same folder.) You can get the current path of the page using the following code:

    Sub Page_Load(sender As Object, e As EventArgs      Dim path As String     path = Server.MapPath(Request.ApplicationPath) End Sub

    The Request.ApplicationPath method returns the virtual path, which is, practically speaking, the part of the URL that comes between the server name and the page. The Server.MapPath method then converts that relative path to a full path on the server. You ll need this full path when you re reading the file.

    Reading the Quotations File

    Reading a text file is a specific instance of a general task known as reading a stream. A stream is any sequence of bytes coming at you, whether from a communications port, another program, or in our case, a simple file.

    To capture a stream, you need a StreamReader object. Once you ve got this object, you can call its ReadLine method to fetch one line of text at a time from the current stream. To get every line out of the text file, you call the ReadLine method in a loop until all the lines have been read. We ll know we ve reached the end of the file when the ReadLine method fails to return an object.

    What do we do with the lines as we read them? I suggest that we store the lines in a structure called an ArrayList. An ArrayList object is similar to the array we used for slides and captions in Chapter 5 but with the advantage that we don t have to know in advance how many elements the array will include. Instead, we can add elements on the fly. This feature is perfect, because we don t know how many lines we ll read out of the quotations file.

    The basic code for reading the text file looks like this:

    Sub Page_Load(sender As Object, e As EventArgs      Dim path As Strin     path = Server.MapPath(Request.ApplicationP ath     Dim quotesArrayList As ArrayList     quotesArrayList = New ArrayList()          Dim srQuotes As System.IO.StreamReader     srQuotes = New System.IO.StreamReader(path & "\qu otations.txt")     Dim eof As Boolean = False     Dim quoteLine As String     While eof = False         quoteLine = srQuotes.ReadLine()         If quoteLine Is Nothing Then             eof = True         Else             quotesArrayList.Add(quoteLine)         End If     End While     srQuotes.Close() End Sub

    This code might look long, but it s not actually very complicated. It first declares a variable named quotesArrayList as type ArrayList. Remember that you can use any Microsoft .NET Framework class as the data type for a variable. After the variable has been declared, the program creates a new instance of the ArrayList class and assigns it to the variable.

    The program then declares the variable srQuotes as type StreamReader, creates a new instance of the StreamReader object, and assigns the new StreamReader object to the srQuotes variable. (I hope you re seeing the general pattern here: declare variable to type class, and then create an instance of type class and assign it to variable.) When you create an instance of the StreamReader object, you pass it the complete path and file name of the file to be read. We add the extra backslash character (\) because the path we got from the MapPath method doesn t include this character. The StreamReader object (named srQuotes) is now ready to do our bidding with the file.

    The program creates a variable named eof ( end of file ) as a Boolean and immediately sets it to False. We re going to use this variable as a flag. When we detect the end of the file, we ll set it to True.

    Tip 

    You ll see a shortcut in this line: Dim eof As Boolean = False. You can declare a variable and set it to a value all in one statement.

    The program also creates a variable named quoteLine as a string. This variable will hold the individual quotations from the text file as we read them. The program contains a While loop, which will repeat a block of statements while a condition is true. Every statement between While and End While will be executed repeatedly as long as that eof variable remains False.

    Inside the loop, the program calls the srQuotes object s ReadLine method, which returns the next line out of the text file. A line is everything up to the next carriage return/linefeed in the file which is why I insisted that the lines not wrap. The program assigns the line to a string variable named quoteLine, which will contain the quote, the pipe character, and the author. We ll split those up later.

    The program uses the Is Nothing test I explained in Chapter 2 to determine whether anything actually came back from the ReadLine method. If there is no next line, the stream reader has run out of lines in the file, indicating that it has reached the end of the file. The program sets the flag variable eof to True so that the While loop will exit. If the test quoteLine Is Nothing is not true, the ReadLine method has returned a line and the program adds it as a new element to the quotesArrayList object.

    Finally, after the last line has been read and the loop exits, the program closes the srQuotes object. This is very important! You should always close any object that you open. (We opened the StreamReader object when we created the instance of it.) Closing the object releases the object in case another process needs it and releases the memory the object was using.

    After this code runs, the quotesArrayList object is filled with quotation-author strings, one quotation per element. The next step is to select one quotation at random. But before we make a selection, let s take a slight detour to talk about making the process of reading the quotation file more robust.




    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