Create Your Own Guestbook In ASP.NET

.

Environment: ASP, .NET

Introduction

Recently, I was working on my Web site and I wanted to implement a guestbook. So, I searched the Web to get the best guestbook for my Web site. But then I thought, “Hey, I am a developer. Why not create my own?” It was very easy to create a guestbook and you can do it, too. In this article, I will show you how you can easily create a guestbook. To understand the article, I assume that you have already knowledge about the basics of ASP.NET programming and XML/XSL skills.

Overview

So, what do we need to create a guestbook? We need two webforms: one to enter the name, e-mail, comments, and so forth; the other is used to display the comments signed in the guestbook. Of course, we can make this in one webform, but to have clean code, I will use two webforms with several codebehind files, which I discuss later. Then we need a database, which holds the information for us. I have used a simple XML file (database) to store the information entered by the user. To visualize the XML, we also use the XSL technique. In summary, we need the following items:

  • Two webforms
  • Codebehind
  • Database
  • XSL

In a guestbook, it is usually fully sufficient to store the name, location, e-mail, Web site, and some comment lines. Of course, you can have more fields to store, but I think these are enough. This data is stored in the XML file. So, according to that, our XML can look something like this:

Guestbook.xml:

01: <?xml version="1.0" encoding="ISO-8859-1"?>
02: <guestbook>
03:   <guest>
04:   <name>Sonu Kapoor</name>
05:   <location>Germany</location>
06:   <email>sonu@codefinger.de</email>
07:   <website>www.codefinger.de</website>
08:   <comment>This guestbook is written by Sonu Kapoor.
09:   I hope you like it. To learn how to create such a
10:   guestbook, read the whole story on my Web site.</comment>
11:   </guest>
12: </guestbook>

The Webforms, Part I: Signing the Guestbook

To sign a guestbook, we allow the user to enter some information. This can be done in a simple webform. In our example, this is the guestbook.aspx file. I use the following fields in the webform; the user can fill them in.

  • Name
  • Location
  • Email
  • Website
  • Comment

The first Webform: guestbook.aspx:

01: <% @Page Language="C#" Debug="true" Src="Guestbook.cs"
                           Inherits="Guestbook" %>
02: <form runat="server">
03: ...
04: ...doing some visualisation stuff
05: ...
06: <ASP:Textbox id="name" size="64" runat="server"/>
07:
08: <asp:RequiredFieldValidator id="nameRequired" runat="server"
                                ControlToValidate="name"
09: ErrorMessage="You must enter a value into textbox1"
                  Display="dynamic">Enter name
10: </asp:RequiredFieldValidator>
11:
12: <ASP:Textbox id="location" size="64" runat="server"/>
13:
14: <asp:RequiredFieldValidator id="locationRequired"
         runat="server" ControlToValidate="location"
15: ErrorMessage="You must enter a value into textbox1"
         Display="dynamic">Enter location
16: </asp:RequiredFieldValidator>
17:
18: <ASP:Textbox id="website" size="64" runat="server"/>
19: <ASP:Textbox id="email" size="64" runat="server"/>
20: <ASP:Textbox id="comment" TextMode="Multiline" columns="50"
         rows="10" wrap="true" runat="server"/>
21:
22: <asp:RequiredFieldValidator id="commentRequired"
         runat="server" ControlToValidate="comment"
23: ErrorMessage="You must enter a value into textbox1"
         Display="dynamic">Enter comment
24: </asp:RequiredFieldValidator>
25:
26: <ASP:Button id="submit" runat="server" Text="Submit"
         OnClick="Save_Comment"/>
27: <ASP:Button id="reset" runat="server" Text="Reset"/>
28: ...
29: ...doing some visualisation stuff
30: ...
31: </script>
32: </form>

To avoid confusing you with unnecessary code, I have removed the visualisation tags, such as table, table header, and so forth from this example. Of course, these are all included in the example download. As we only display a form with some fields and buttons, you don’t see any real programming code. This is all hidden in the codebehind. I assume you already know the technique of codebehind. In line 1 I have set the SRC attribute to let the asp.net file know that we are using the codebehind file Guestbook.cs and I have set also the attribute Inherits with the corresponding classname. This attribute is used to let the file know which class has to be inherited. In lines 6, 12, and 18-20, I have implemented the required textfields. Please remember that if you want to use the same variables in the codebehind, they need to have the same ID in both files and must be declared as public. In lines 8, 14, and 22 I have used the ASP.NET validator controls. These validator controls check whether the user has entered any value in the textfields, without doing a round-trip to the server. This code is executed on the client side.

In line 26, I have implemented a submit button with an OnClick event called Save_Comment. This event is used to store the information entered by the user to the XML file. The function of this event is available in the Guestbook.cs. In line 27n I have only implemented a reset button. This is all; nothing more has to be done in the webform. If you run guestbook.aspx, you should see a webform like this:

By now, you have seen how to display a webform, but you have not yet seen the code that is handling the event in guestbooks.cs.

The Codebehind: guestbook.cs:

01: using System;
02: using System.Web;
03: using System.Web.UI;
04: using System.Web.UI.WebControls;
05: using System.Xml;
06:
07: public class Guestbook : Page
08: {
09:   // Create the required webcontrols with the same name as
      // in the guestbook.aspx file
10:   public TextBox name;
11:   public TextBox location;
12:   public TextBox email;
13:   public TextBox website;
14:   public TextBox comment;
15:
16:   public void Save_Comment(object sender, EventArgs e)
17:   {
18:     // Everything is all right, so let us save the data
        // into the XML file
19:     SaveXMLData();
20:
21:     // Remove the values of the textboxes
22:     name.Text="";
23:     location.Text="";
24:     website.Text="";
25:     email.Text="";
26:     comment.Text="";
27:   }
28: }
29:
30: private void  SaveXMLData()
31: {
32:   // Load the XML file
33:   XmlDocument xmldoc = new XmlDocument();
34:   xmldoc.Load( Server.MapPath("guestbook.xml") );
35:
36:   //Create a new guest element and add it to the root node
37:   XmlElement parentNode = xmldoc.CreateElement("guest");
38:   xmldoc.DocumentElement.PrependChild(parentNode);
39:
40:   // Create the required nodes
41:   XmlElement nameNode     = xmldoc.CreateElement("name");
42:   XmlElement locationNode = xmldoc.CreateElement("location");
43:   XmlElement emailNode    = xmldoc.CreateElement("email");
44:   XmlElement websiteNode  = xmldoc.CreateElement("website");
45:   XmlElement commentNode  = xmldoc.CreateElement("comment");
46:
47:   // retrieve the text
48:   XmlText nameText     = xmldoc.CreateTextNode(name.Text);
49:   XmlText locationText = xmldoc.CreateTextNode(location.Text);
50:   XmlText emailText    = xmldoc.CreateTextNode(email.Text);
51:   XmlText websiteText  = xmldoc.CreateTextNode(website.Text);
52:   XmlText commentText  = xmldoc.CreateTextNode(comment.Text);
53:
54:   // append the nodes to the parentNode without the value
55:   parentNode.AppendChild(nameNode);
56:   parentNode.AppendChild(locationNode);
57:   parentNode.AppendChild(emailNode);
58:   parentNode.AppendChild(websiteNode);
59:   parentNode.AppendChild(commentNode);
60:
61:   // save the value of the fields into the nodes
62:   nameNode.AppendChild(nameText);
63:   locationNode.AppendChild(locationText);
64:   emailNode.AppendChild(emailText);
65:   websiteNode.AppendChild(websiteText);
66:   commentNode.AppendChild(commentText);
67:
68:   // Save to the XML file
69:   xmldoc.Save( Server.MapPath("guestbook.xml") );
70:
71:   // Display the signed guestbook to the user
72:   Response.Redirect("viewguestbook.aspx");
73:   }
74: }

So far, concerning the codebehind file, what really happens here? You won’t believe it, but not much. In lines 1-3, I have implemented the minimal required namespaces that are needed to get access to several functions. In line 7, I have created a new class called Guestbook; please notice this is the class which is inherited by the guestbook.aspx file. Line 10-14 declares five public variables of type type textbox. Please remember also here that these names have to be identical to the textboxes created in guestbook.aspx. In line 16, you can see the event Save_Comment, which is fired by the submit button of the guestbook.aspx file. This event is used to save the data.

The Saving Process

The SaveXMLData() function saves the information for us. Because we are using a XML database to store the information, we use the XmlDocument, XmlElement, and XmlText classes. These classes provide the necessary functions. Lines 33-34 create a new XMLDocument class object and loads the guestbook.xml file. In lines 41-45, the required nodes are created with the CreateElement function. Lines 48-52 retrieve the information the user entered and store them to an object of XmlText. In lines 55-59, I have used the AppendChild function with the main XmlDocument object. This function stores the created nodes without the values. Finally, in lines 62-68, the values are stored in the nodes we just created. In line 69, all changes are saved to the guestbook.xml. Line 72 redirects the page to the viewguestbook.aspx, to display the stored comment.

The Webforms, Part II: Viewing the Guestbook

To view the guestbook, I have created another webform. Take a look at the second webform.

ViewGuestbook.aspx:

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

As you see, I am not doing very much in the webform. I have just called the codebehind file ViewGuestbook.cs. So, please take a look at this file.

The Codebehind: ViewGuestbook.cs:

01: using System;
02: using System.Web;
03: using System.Web.UI;
04: using System.Web.UI.WebControls;
05: using System.Xml;
06: using System.Xml.Xsl;
07: using System.IO;
08:
09: public class ViewGuestbook : Page
10: {
11:   private void Page_Load(object sender, System.EventArgs e)
12:   {
13:     //Load the XML file
14:     XmlDocument doc = new XmlDocument( );
15:     doc.Load( Server.MapPath("guestbook.xml") );
16:
17:     //Load the XSL file
18:     XslTransform xslt = new XslTransform();
19:     xslt.Load( Server.MapPath("guestbook.xsl") );
20:
21:     string xmlQuery="//guestbook";
22:     XmlNodeList nodeList=doc.DocumentElement.SelectNodes(
                    xmlQuery);
23:
24:     MemoryStream ms=new MemoryStream();
25:     xslt.Transform( doc, null, ms);
26:     ms.Seek( 0, SeekOrigin.Begin );
27:
28:     StreamReader sr = new StreamReader(ms);
29:
30:     //Print out the result
31:     Response.Write(sr.ReadToEnd());
32:   }
33: }

I have created this class to display all comments to the user. Lines 1-7 are again used to implement the required namespaces. Because we are using XSL for the visualisation, we have to include the namespace System.Xml.Xsl. Line 9 creates a new class called ViewGuestbook, with a private built-in function called Page_Load. This function is always called when the page loads or when the user performs a refresh. The function again loads guestbook.xml in line 15. The XslTranform class is used to transform the XML elements into HTML. In lines 18-19, I load guestbook.xsl with the help of a XslTransform object. Line 22 creates a new object of class XmlNodeList. With the help of this class, we can select the required nodes. In line 24, I have used the MemoryStream class, which is available via the namespace System.IO. This class is used to create a stream that has memory as a backing store. With the function Transform in line 25, I have assigned the XML data to the memorystream. The Seek function in line 26 sets the current position to zero. In line 28, I have created an object of the class StreamReader. This class is used to read the stream. Line 31 prints then the result with the help of the ReadToEnd() function. This function reads the stream from the current position to the end. If you run viewguestbook.aspx, you should see a webform like this:

XSL:

As already mentioned, we use XSL to transform from XML to HTML. I assume that you already have knowledge about XSLT, so I will only discuss the important things. I have only used an XSL for-each loop to iterate through all the guests. This looks something like this:

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

In the loop, I call the XSL template name, which looks something like this:

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

Conclusion

As you see, it is not very difficult to create a guestbook. You can see the guestbook live on my Web site. I hope to release further versions of the Guestbook with your help. Please send feedback to sonu@codefinger.de.

Downloads


Download demo project – 4 Kb

More by Author

Previous article
Next article

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read