Create Your Own Guestbook In ASP.NET

Tweet

Recently I was working on my Website, and decided I wanted to implement a guestbook. I started to search the Web to find the best guestbook for my Website, but when none turned up, I thought ‘Hey I’m a developer, why not create my own?’

It was very easy to create a guestbook — you can do it too. In this tutorial, I’ll show you how. I’ll assume that you have already knowledge about the basics of ASP.NET programming, that you know the techniques involved in codebehind, and that you have some XML/XSL skills.

Overview

What do we need in order to create a guestbook? We need two Web forms: one in which the user can enter their name, email address, and comment, and another that’s used to display these comments as they’re signed into the guestbook. Of course we can build this functionality into one Web form, but to have a clean code, I’ll use two Web forms with several codebehind files (I’ll discuss these in more detail in a moment).

We’ll also need a database to hold the information entered via the form. I used a simple XML file (a database) to store the information entered by the user. For the visualisation of the XML we’ll use XSL.

So, in summary, we need the following:

  • Two Web forms
  • Codebehind
  • Database
  • XSL

In a guestbook, it’s usually sufficient to store a user’s name, location, email address, Website address, and comment. Of course, you can store more fields, but for our purposes, these are enough. We’ll store this data in the XML file, which will look something like this:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<guestbook>
 <guest>
   <name>Sonu Kapoor</name>
   <location>Germany</location>
   <email>sonu@codefinger.de</email>
   <website>www.codefinger.de</website>
   <comment>This guestbook is written by Sonu Kapoor.  
   I hope you like it. To learn how to create such a guestbook,  
   read the whole story on my website.</comment>
 </guest>
</guestbook>
Signing the Guestbook

We’ll allow the user to ‘sign’ our guestbook by entering some information into a simple Web form — in our example this is the guestbook.aspx file. I use the following fields in the Web form:

  • Name
  • Location
  • Email
  • Website
  • Comment

Here’s the code:

<% @Page Language="C#" Debug="true" Src="Guestbook.cs"  
Inherits="Guestbook" %>
<form runat="server">
...
...doing some visualisation stuff
...
<ASP:Textbox id="name" size="64" runat="server"/>

<asp:RequiredFieldValidator id="nameRequired" runat="server"  
ControlToValidate="name"  
ErrorMessage="You must enter a value into textbox1"  
Display="dynamic">Enter name  
</asp:RequiredFieldValidator>

<ASP:Textbox id="location" size="64" runat="server"/>

<asp:RequiredFieldValidator id="locationRequired" runat="server"  
ControlToValidate="location" ErrorMessage="You must enter  
a value into textbox1" Display="dynamic">
Enter location </asp:RequiredFieldValidator>

<ASP:Textbox id="website" size="64" runat="server"/>
<ASP:Textbox id="email" size="64" runat="server"/>
<ASP:Textbox id="comment" TextMode="Multiline"  
columns="50" rows="10" wrap="true" runat="server"/>

<asp:RequiredFieldValidator id="commentRequired" runat="server"  
ControlToValidate="comment" ErrorMessage="You must enter  
a value into textbox1" Display="dynamic">
Enter comment </asp:RequiredFieldValidator>

<ASP:Button id="submit" runat="server" Text="Submit"  
OnClick="Save_Comment"/>
<ASP:Button id="reset" runat="server" Text="Reset"/>
...
...doing some visualisation stuff
...
</script>
</form>

To avoid confusing you with unnecessary code, I have removed the visualisation tags — including table, table header etc. — from this example (though, of course, these are all included in the downloadable code that’s provided at the end of this tutorial). As we only display a simple form with a few fields and buttons, you can’t see any real programming code in this file. This is because all the functionality is hidden in the codebehind.

In the first line of the code above, I set the SRC attribute to let the ASP.NET file know that we are using the codebehind file Guestbook.cs I’ve also set the attribute Inherits with the corresponding classname. This attribute lets the file know which class to inherit.

Next, I’ve implemented the required text fields. Remember that if you want to use the same variables in the codebehind, they need to have the same ID in both files, and they must be declared as public.

In the next section of the code, I used the ASP.NET validator controls. These controls check whether the user has entered a value into the text field, without doing a round-trip to the server. The code is executed on the client side.

Finally, I implemented a submit button with an OnClick event called Save_Comment. This event is used to store the information entered into the XML file by the user. The function of this event is available in Guestbook.cs. I also implemented a reset button — and that’s it! Nothing more has to be done to the Web form. Now, if you run the guestbook.aspx, you should see a Web form that looks like this:

1061_webform1

Now we know how to display the Web form, but we haven’t seen the code that handles the event in guestbooks.cs. Let’s take a look at that now.

using System;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Xml;  
 
public class Guestbook : Page  
{  
// Create the required webcontrols with the same name as  
in the guestbook.aspx file  
 public TextBox name;  
 public TextBox location;  
 public TextBox email;  
 public TextBox website;  
 public TextBox comment;  
 
 public void Save_Comment(object sender, EventArgs e)  
 {  
  // Everything is all right, so let us save the data  
into the XML file  
  SaveXMLData();  
 
  // Remove the values of the textboxes  
  name.Text="";  
  location.Text="";  
  website.Text="";  
  email.Text="";  
  comment.Text="";  
 }  
}  
 
private void SaveXMLData()  
{  
 // Load the xml file  
 XmlDocument xmldoc = new XmlDocument();  
 xmldoc.Load( Server.MapPath("guestbook.xml") );  
 
 //Create a new guest element and add it to the root node  
 XmlElement parentNode = xmldoc.CreateElement("guest");  
 xmldoc.DocumentElement.PrependChild(parentNode);  
 
 // Create the required nodes  
 XmlElement nameNode = xmldoc.CreateElement("name");  
 XmlElement locationNode = xmldoc.CreateElement("location");  
 XmlElement emailNode = xmldoc.CreateElement("email");  
 XmlElement websiteNode = xmldoc.CreateElement("website");  
 XmlElement commentNode = xmldoc.CreateElement("comment");  
 
 // retrieve the text  
 XmlText nameText = xmldoc.CreateTextNode(name.Text);  
 XmlText locationText = xmldoc.CreateTextNode(location.Text);  
 XmlText emailText = xmldoc.CreateTextNode(email.Text);  
 XmlText websiteText = xmldoc.CreateTextNode(website.Text);  
 XmlText commentText = xmldoc.CreateTextNode(comment.Text);  
 
 // append the nodes to the parentNode without the value  
 parentNode.AppendChild(nameNode);  
 parentNode.AppendChild(locationNode);  
 parentNode.AppendChild(emailNode);  
 parentNode.AppendChild(websiteNode);  
 parentNode.AppendChild(commentNode);  
 
 // save the value of the fields into the nodes  
 nameNode.AppendChild(nameText);  
 locationNode.AppendChild(locationText);  
 emailNode.AppendChild(emailText);  
 websiteNode.AppendChild(websiteText);  
 commentNode.AppendChild(commentText);  
 
 // Save to the XML file  
 xmldoc.Save( Server.MapPath("guestbook.xml") );  
 
 // Display the user the signed guestbook  
 Response.Redirect("viewguestbook.aspx");  
 }  
}

Wow! That’s our codebehind file… but what really happens here? You won’t believe it, but the answer is: "not much"!

First, we implement the minimal required namespaces which we need in order to access several important functions. Then I create a new class called Guestbook:

public class Guestbook : Page

Note that it’s this class that’s inherited by the guestbook.aspx file. Then we declare 5 public variables of type textbox. Remember that here, the names have to be identical to those we used when we created the text boxes in guestbook.aspx. Then, as you can see, we use the Save_Comment event, which is fired by the submit button we included in the guestbookpx file. This event is used to save the data.

The Saving Process

The function SaveXMLData() saves the information for us. As we’re using an XML database to store the information, we use the XmlDocument, XmlElement and XmlText classes, which provide all the functions we need.

Next, we create a new XMLDocument class object and load the guestbook.xml file. The required nodes are created with the function CreateElement, and the information entered by the user is retrieved and stored to an object of XmlText. Next, we store the created nodes without any values, using the function AppendChild in conjunction with the main XmlDocument object.

And finally, the values are stored in the nodes we just created, we save all changes to the guestbook.xml file, and we redirect the page to viewguestbook.aspx, where the stored comment is displayed.

Viewing the Guestbook

To view the guestbook, we must created an another Web form:

<% @Page Language="C#" Debug="true" Src="ViewGuestbook.cs"    
Inherits="ViewGuestbook" %>

As you see, this Web form doesn’t really do all that much. It simply calls the codebehind file, ViewGuestbook.cs. Let’s take a look at this file.

using System;   
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Xml;  
using System.Xml.Xsl;  
using System.IO;  
 
public class ViewGuestbook : Page  
{  
 private void Page_Load(object sender, System.EventArgs e)  
 {  
   //Load the XML file  
   XmlDocument doc = new XmlDocument( );  
   doc.Load( Server.MapPath("guestbook.xml") );  
 
   //Load the XSL file  
   XslTransform xslt = new XslTransform();  
   xslt.Load( Server.MapPath("guestbook.xsl") );  
 
   string xmlQuery="//guestbook";  
   XmlNodeList nodeList=doc.Document  
Element.SelectNodes(xmlQuery);  
 
   MemoryStream ms=new MemoryStream();  
   xslt.Transform( doc, null, ms);  
   ms.Seek( 0, SeekOrigin.Begin );  
 
   StreamReader sr = new StreamReader(ms);  
 
   //Print out the result  
   Response.Write(sr.ReadToEnd());  
 }  
}

I’ve created this class to display all comments submitted through the guestbook to our users. Again, the first thing we do is implement the required namespaces, and, as we’re using XSL for the visualisation, we have to be sure to include the namespace System.Xml.Xsl.

Then we create a new class called ViewGuestbook, with a private inbuilt function called Page_Load. This function is always called when the page loads, or when the user performs a refresh. Here, the function loads the guestbook.xml file, and then the XslTranform class is used to transform the XML elements into HTML before we load the guestbook.xsl with the help of a XslTransform object.

Next, we create a new object of class XmlNodeList, which will allow us to select the required nodes. We then use the class MemoryStream, available via the namespace System.IO, to create a stream that has memory as a backing store, and use the Transform function to assign the xml data to this memory stream. The Seek function sets the current position to zero.

We then create an object of the class StreamReader, which reads the stream, and print the result with the help of the function ReadToEnd(). This function reads the stream from the current position to the end. If you run viewguestbook.aspx, you should see a Web form like this:

1061_webform2

The XSL

As I’ve already mentioned, we use XSL for the transformation of the data from XML to HTML. I’ve assumed that you’re already experienced with XSLT, so I’ll only touch on the important aspects here. I have used an XSL for-each loop to iterate through all the guests in the book, which looks something like this:

<xsl:for-each select="//guest">   
 <xsl:apply-templates select="name"/>    
</xsl:for-each>

And in the loop we call the XSL template name, which looks something like this:

<xsl:template match="name">   
 <xsl:value-of select='.'/>  
</xsl:template>
Conclusion

As you see, it’s not very difficult to create a guestbook. Good luck! And don’t forget to download the example files here.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments