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/

IT Offers

Comments

  • may lanh chat luong cao

    Posted by marfomift on 05/21/2013 05:51am

    The design of an e-commerce website offer up another pair of challenges to website developers and the whole process is a lot more important than an informational site because in order for a small business to survive online, the website should perform and convert sales. By breaking down the website design into different areas, you will end up able to see a better way through to a well-performing e-commerce website.The crucial and determining part is to choose which internet Development Company as there are plenty of competitors out there. The choice becomes tough if the project is a small one. A Web Design Company contains specialists who're good in programming and building web pages. They could draw out the correct solution to a customer. Regular discussions with the e-commerce web style team helps them to truly have a specific view of what each one is to be contained in the web pages.This has opened new opportunities for firms since they are now using social ecommerce to push their sales. Actually, many new entrepreneurs simply did not bother beginning physical shops. Alternatively, they spend money on social ecommerce and reap considerable earnings that have been previously unthinkable.The complete ecommerce solutions are provided all by us at very affordable prices. The companies we include amounts from e-commerce hosting to shopping cart software answer. For more information please visit our e-commerce platform.|From time to time, emails are got by me from clients saying that they've made a decision to proceed from having an online business and they are wondering if I could let them know simply how much their online business will probably be worth. _____________ May lanh

    Reply
  • order Phentermine online

    Posted by wahbeadib on 05/19/2013 09:04pm

    This is done by preparing all of your daily food for you. buy Adipex online buy cheap Phentermine online. Just because you are getting older doesn't mean you will be struck down by a range of illnesses. [url=http://www.buyphentermineonlinemed.com/#854269-order-adipex-online]purchase generic Phentermine Adipex online[/url] Wellness Committee Remaining true to it's traditions, C.

    Reply
  • order Klonopin 0.5mg online

    Posted by theogaphele on 05/19/2013 09:18am

    Order Clonazepam No Rx Cheap Buy Cheap Klonopin Online Cheap - Buy Cheap Clonazepam Online Without a Prescription

    Reply
  • purchase Klonopin 1mg online

    Posted by theogaphele on 05/18/2013 09:33pm

    Buy Cheap Klonopin Online Without Rx Purchase Cheap Clonazepam Without Rx - Clonazepam Cheap

    Reply
  • Thoi trang nam

    Posted by marfomift on 05/18/2013 08:29pm

    One should look into exactly what kinds of payments are sustained by the ecommerce online cart apllication. In today's online world credit cards have actually come to be the most extensively accepted approach of payment. So one needs to be sure that the purchasing cart answer supports charge card payments. It is even important that the purchasing cart, which is picked, accepts repayment in multi-currencies, so about allow the web site to serve consumers around the world. It ought to even have the ability to deliver several repayment alternatives apart from payment using charge card to the client like payment by cheque or payment on delivery.One of the important components for almost any successful business is really a plainly defined exit strategy. Even though it is quite hard to ascertain just what someone else may spend for your business, we encourage you to begin considering the elements we've listed so you've a powerful package to provide when the time comes for you to try the waters with putting your business on the market.Magento extensions may be developed on the Magento platform. Any developer familiar with the working of Magento can form beneficial magento extensions for several types of eCommerce stores, as Magento is definitely an open source technology. Currently there are many effective magento extensions available for purchase and use. And these have not been manufactured by the in-house Magento growth but developers not even remotely linked to the makers of Magento. A couple of the earliest transactions in the international financial system entail profession by barter which is a kind of C2C transaction. Having said that, C2C were virtually non-existent in current times until the development of e-commerce. There are lots of internet sites giving free classifieds, auctions as well as online forums where people may merchandise thanks to online payment systems like paypal, Google check-out where people may send as well as receive money online with ease. eBay's auction site is a terrific example of where individuals may bid or purchase downright daily 24/7 a year. There are also some other auction sites like play.com and also ebid. _____________ Thoi trang nam

    Reply
  • kamagra soft tablets

    Posted by feaggiweeviam on 05/17/2013 06:02pm

    Hi! call: - kamagra jellies from abroad - kamagra tablets cheapest - kamagra gel - kamagra jelly , kamagra tablets cheapest - viagra kamagra ...!!! With kind regards ---------- Кредит в любое время дня и ночи - домашний он-лайн банк - кредит он-лайн - мини кредит

    Reply
  • ihone 4

    Posted by marfomift on 05/17/2013 08:45am

    Protection is the most necessary component for any type of ecommerce site software. A secure cart application normally will have a firewall software, which safeguards it from any sort of intruders. Apart from this the it ought to additionally have an outstanding connectivity. Exceptional connection makes certain that the transactions performed are executed effectively and also efficiently.In recap, anyone may begin an e-commerce as you do not necessarily require a massive capital outlay to get started. Additionally what is additional interesting is that you do not should have the knowledge of html or be a web designed to build your online store. There are lots of business out there that may support with developing your web site and even pre-load it with your favored products, as an example online internet sellers as well as wholesale2b. Just what is even more important is that you may simply choose to make use of decline shipping solution which is the idea of not holding any bodily stock yet just merely industrying the products of companies who are into decline shipping company. Decline shipping is the most convenient and also fastest means to begin selling products online. In short, you primarily try to find a product you wish to offer and make an advert to offer that item. You can easily sell it on eBay, Amazon, Google, Yahoo and even from your personal internet site. When you make a sale, you send the order on to your decline shipper, that in turn sends the product to your customer. The earnings that you make is the distinction in the cost that you charge. I will be conversing even more about decline freight at a later day.| First of all let's address the inquiry of what a buying cart is. Essentially an ecommerce-shopping cart is a collection of scripts that monitor items a site visitor decides on to buy from your web site until they continue to the " check out". A popular false impression is that online buying carts manage the whole financial transaction, however they just actually act as a front end which passes sensitive details like the credit card variety by means of a protected hookup to a payment gateway.Traffic executive - Here the network providers control the road of the traffic through a network. MPLS makes traffic design easier than any other mainstream technology.It ought to work with the repayment technique. There are lots of different repayment gateways, which connect different plans, so one needs to make certain if the purchasing cart that has been picked is compatible with the best repayment method. _____________ Iphone

    Reply
  • order cheap Lexapro online no prescription

    Posted by IceseeSeivend on 05/16/2013 09:09pm

    Buy Cheap Lexapro Pills Purchase Cheap Lexapro No Prescription - Purchase Escitalopram Online Medication

    Reply
  • purchase Venlafaxine online no prescription

    Posted by Encantals on 05/15/2013 11:57pm

    Treatment for either problem in isolation rarely works. Treating anxiety disorder with medications like Xanax has its adverse effects. effexor for energy. There is usually a cause, but causes are too widespread to be characterized. effexor xr for pmdd. effexor Pills Cheap - More Bonuses: [url=http://buyeffexoronlinepills.com#buy-effexor-online-medication]effexor[/url] 2011 effexor buy- Venlafaxine Cheap, effexor buy online. effexor for addiction. Upon more research I am convinced that long term use of these types' of meds can be extremely dangerous, especially for young people. effexor social anxiety reviews

    Reply
  • UK supplier Buy Kamagra

    Posted by Enapaddentafe on 05/15/2013 09:56pm

    Good afternoon! forward: - Cheap Kamagra Oral Jelly UK - usa kamagra supplier - paypal kamagra doara - lowcost kamagra , Kamagra Oral Jelly australia discount sildenafil - Kamagra Oral Jelly visa ...!!! With kind regards ---------- кредит он-лайн - кредит за 2 минуты - кредитная карта - срочно нужны деньги

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds