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



About the Author

Sonu Kapoor

Sonu Kapoor is an ASP.NET MVP and MCAD. He is the owner of the popular .net website http://dotnetslackers.com. DotNetSlackers publishs the latest .net news and articles - it contains forums and blogs as well. His blog can be seen at: http://dotnetslackers.com/community/blogs/sonukapoor/

Comments

  • グッチ グッチ 財布 グッチ バッグ コーチ コーチ バッグ コーチ 財布

    Posted by scgchurtis on 07/19/2013 06:00pm

    財布 ブラック Prada 財布 夫であるパチンコ店経営者の西村拓郎氏が COACH 財布 面白ないと退団するかもしれませんね 新作 エキゾティックな甘さが印象的です [url=http://johnpat.com/brand/gucci/]グッチ バッグ[/url] [url=http://johnpat.com/brand/coach/]コーチ セール[/url] コーチ トート プラダ chanel 財布 プラダ バッグ プラダ アウトレット miumiu バッグ chanel 財布 グッチバッグ シャネル 財布 新作 コーチ財布

    Reply
  • Phim chieu rap

    Posted by marfomift on 07/18/2013 01:24pm

    What Are The Best 3 D Blu Ray Movies To Take Home?T-Pain Resuscitates Freaknik For Cartoon MusicalPolitical Movies Tell The True Statement Some Of The Time About PoliticsFour months after Teletoon Canada Inc. announced Cartoon Network and Adult Swim were coming to Canada, іt; has finally come to fruition. Four months after Teletoon Canada Inc. announcedCartoon Network and Adult Swim were coming to Canada, it has finally come to fruition. One can never have enough "Robot Chicken." One can never have enough "Robot Chicken." Will 2012 Be A Tragedy At The Movies? _____________ http://thoitrangbauvn.info/binh-luan-ve-phim-hay/

    Reply
  • Rap phim

    Posted by marfomift on 07/15/2013 04:24am

    This book contains amusing, insightful considerations of films about Venice, New York, the Post Office, art, gangsters and newspapers: "The B picture star Elaine Shepherd quit Hollywood to become a reporter and even wrote an autobiography called Forgive Us Our Press Passes." His wit is as sharp as his knowledge. Yoυ are indisputable to hold a dour way, or at the dramaturgy.Six Out Of 10 Movies Pullulated Via Netflix: StudyThe best love is the kind that аw;аken;ѕ the soul and makes us reach for more; that plants a fire in our hearts and brings peace to οur; minds... That's what you've given me аn;ԁ that's what I hope to give to you forever. Hollywood has produced many good movies that have bееn; huge blockbusters and also have a huge fan following. There are so many movies with touching plots and soothing music that it is quite impossible to list all of them. Top 10 Best Romantic MoviesRomantic movies is one such popular genre that is loved by everyone. The best, most enduring movies are those that capture a piece of universal human experience. Something that everyone has experienced in their own lives. We love to see ourselves reflected on the big screen, either realistically, or as our fantasy selves. And would cou