Writing a Guest Book Application

XML can be used as something more than a means of describing and packaging data. By walking through a fully functional Guest Book application I explain how to combine XML with XSL and ASP.NET to write Web-based applications.

The first impression most developers get after reading about XML is that it sounds great, but that they don't know exactly how it is useful. In this section, I show you how a little XML knowledge combined with ASP.NET and XSL can be used to create a Guest Book application for your Web site.

Guest books are a simple function of most Web sites. Easily broken down into an XML structure by analyzing the type of information you want to record from visitors, XML is very handy when handling information such as the following in a Web site:

  • Visitor's name

  • Visitor's e-mail address

  • Visitor's home page

  • Visitor's country

  • Message

It's also important to record the time and date that the message was left in the guest book. You can take advantage of ASP.NET to get the "real" server time and record this information.

A regular XML document to record time and date could be this:

 <guestbook>   <entry date="03/11/00 00:03:53">     <name>Rick Leinecker</name>     <email>rick@there.now</email>     <homepage>http://www.infinitevision.NET</homepage>     <country>US</country>     <comment>This is the only comment in the Guest Book</comment>   </entry> </guestbook> 

From the example, you can see that I can record all the information under each Entry node in the XML document. This is a simple XML document, and it doesn't really need a document type definition (DTD) to show its structure (or for processing purposes). Guestbook (the document node) can hold many entry nodes, which will eventually make up the entire guest book.

Recording It All

Now that you've seen how I'm going to record the guest book entries in an XML file, it's time to investigate the mechanism that will enable this data to be recorded. Figure 9.5 is a good example of a guest book form where the user inputs information.

Figure 9.5. This Page Enables the User to Add Entry Information to the Guest Book.


The majority of guest books are made of a standard HTML form that posts a CGI script (or in some cases, an ASP.NET page). The example ASP.NET application takes the input from a ASP.NET text box and the controls, and then creates the XML objects on the server.

Follow these steps when you use ASP.NET code to record and store the data by retrieving the information from the user-interface controls:

  1. Create an XmlDocument object.

  2. Load the current XML document (with the existing entries) into the XmlDocument object.

  3. Create an XmlDocumentFragment object.

  4. Populate the XmlDocumentFragment object with the text box data that the user entered.

  5. Append the XmlDocumentFragment to the document.

  6. Save the document.

To retrieve the values from the text box controls, I used the following:

  • Name.Text

  • Email.Text

  • Homepage.Text

  • Country.Text

  • Comments.Text

Listing 9.12 shows the ASP.NET code to save the user data. In using this code on your Web site, you should place checks to change any of the recorded data (filter out profanities, hide or "munge" visitor e-mail addresses, and so on).

Listing 9.12 The C# Code That Saves the User Information to the XML File.


 public void Button1_Click(Object Source, EventArgs e) {     try     {         XmlDocument doc = new XmlDocument();         doc.Load( Request.MapPath( "gbook.xml" ) );         XmlDocumentFragment newVisitor = doc.CreateDocumentFragment();         newVisitor.InnerXml = "<entry date=\"" +             DateTime.Now.Format("mm/dd/yyyy hh:mm tt",               DateTimeFormatInfo.InvariantInfo) + "\">\r\n" +             "\t<name>" + Name.Text + "</name>\r\n" +             "\t<email>" + Email.Text + "</email>\r\n" +             "\t<homepage>" + Homepage.Text + "</homepage>\r\n" +             "\t<country>" + Country.Text + "</country>\r\n" +             "\t<comment>" + "<![CDATA[" + Comments.Text +             "]]></comment>\r\n" +             "</entry>\r\n";         XmlElement root = doc.DocumentElement;         root.AppendChild( newVisitor );         doc.Save( Request.MapPath( "gbook.xml" ) );         Message.Text = "Done!";         Name.Text = "";         Email.Text = "";         Homepage.Text = "";         Country.Text = "";         Comments.Text = "";     }     catch( Exception ex )     {         Message.Text = ex.Message.ToString();     } } 


 Public Sub Button1_Click(ByVal Source As Object, ByVal e As EventArgs)     Try         Dim doc As New XmlDocument()         doc.Load(Request.MapPath("gbook.xml"))         Dim newVisitor As XmlDocumentFragment  = _           doc.CreateDocumentFragment()         newVisitor.InnerXml = "<entry date=\"" + _             DateTime.Now.Format("mm/dd/yyyy hh:mm tt", _               DateTimeFormatInfo.InvariantInfo) + "\">\r\n" + _             "\t<name>" + Name.Text + "</name>\r\n" + _             "\t<email>" + Email.Text + "</email>\r\n" + _             "\t<homepage>" + Homepage.Text + "</homepage>\r\n" + _             "\t<country>" + Country.Text + "</country>\r\n" + _             "\t<comment>" + "<![CDATA[" + Comments.Text + _             "]]></comment>\r\n" + _             "</entry>\r\n"         Dim root As XmlElement = doc.DocumentElement         root.AppendChild(newVisitor)         doc.Save(Request.MapPath("gbook.xml"))         Message.Text = "Done!"         Name.Text = ""         Email.Text = ""         Homepage.Text = ""         Country.Text = ""         Comments.Text = ""     Catch ex As Exception         Message.Text = ex.Message.ToString()     End Sub End Try 

I have now recorded the visitor information and message inside an XML document stored on the Web server.

Displaying the Guest Book Entries

In the future, all Internet browsers will let us view XML and process it using XSL on the client browser. Right now, though, Internet Explorer 5.0 and above are the only browsers that will do this. You have to process the XML on the server and convert its contents to HTML so that visitors can view the guest book.

Using the XslTransform class, I need to transform the XmlDocument class to process the XML file.

When users visit this example application, they first see one main page. For convenience, I have added a button that enables them to go to the page where the guest book can be viewed. I actually could have placed all the view code in this page, but then I would have had that code in two different pages. So, instead, I redirect users who click this button to the view page, as shown in the following code:

 public void Button2_Click(Object Source, EventArgs e) {     Response.Redirect( "WebForm6.aspx" ); } 
 Public Sub Button2_Click(ByVal source As Object, _   ByVal e As EventArgs)     Response.Redirect("WebForm6.aspx") End Sub 

The .aspx code that can be found in the page where users go to view the text book is very simple. It is some simple HTML with one additional line. That additional line makes a call to the LoadAndRender() method, and the load and render do everything necessary to render the guest book to the display. Now this is a perfect example in which code is separated from the actual HTML. This is one of the strong points that ASP.NET brings to the table. The capability to separate code from HTML is something that is long overdue and will be an asset for developers.

 <%@ Page language="c#" Codebehind="WebForm6.cs" AutoEventWireup="false"    Inherits="XmlExamples.WebForm6" %> <html>   <head>     <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">     <meta name="CODE_LANGUAGE" Content="C#">   </head>   <body> <% LoadAndRender(); %>   </body> </html> 

You can see the application displayed in the guest book in Figure 9.6. It loads in the XML document and does an XSLT transform.

Figure 9.6. An XSL Transform Is Used to Display the Guest Book.


The rendering is done in the LoadAndRender() method. This method creates an XmlDocument object, loads the XML data into the XmlDocument object, creates an XslTransform object, loads the XSL file, and then does the transform. One thing you should look at is the XslTransform object's Transform() method. The third argument passed to this method is Response.Output. This causes the transform output to go directly to the HTTP stream if you specify Response.Output as the destination.

 public void LoadAndRender() {     try     {         m_strText = "";         XmlDocument doc = new XmlDocument();         doc.Load( Request.MapPath( "gbook.xml" ) );         XslTransform tr = new XslTransform();         tr.Load( Request.MapPath( "gbook.xsl" ) );         DocumentNavigator nav = new DocumentNavigator( doc );         tr.Transform( nav, null, Response.Output );     }     catch( Exception ex )     {         Response.Write( ex.Message.ToString() );     } } 
 Public Sub LoadAndRender()     Try         m_strText = ""         Dim doc As New XmlDocument()         doc.Load(Request.MapPath("gbook.xml"))         Dim tr As New XslTransform()         tr.Load(Request.MapPath("gbook.xsl"))         Dim nav As New DocumentNavigator(doc)         tr.Transform(nav, null, Response.Output)     Catch ex As Exception         Response.Write( ex.Message.ToString() )     End Try End Sub 

ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
Year: 2003
Pages: 175

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