Home arrow ASP.NET arrow Page 2 - Create Your Own Guestbook In ASP.NET
ASP.NET

Create Your Own Guestbook In ASP.NET


Creating your very own guestbook is easy with help from Sonu. Using ASP.NET with technologies like XML/XSL, you can have your guestbook up in no time. Read more ...

Author Info:
By: Sonu Kapoor
Rating: 4 stars4 stars4 stars4 stars4 stars / 267
May 27, 2003
TABLE OF CONTENTS:
  1. · Create Your Own Guestbook In ASP.NET
  2. · The Article
  3. · Conclusion

print this article
SEARCH DEVARTICLES

Create Your Own Guestbook In ASP.NET - The Article
(Page 2 of 3 )

In a guestbook it is usually fully sufficient to store the name, location, email, website and some lines of comment. 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 guestbook,
10:     read the whole story on my website.</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 the guestbook.aspx file. I use the following fields in the webform which can be filled by the user.

  • Name
  • Location
  • Email
  • Website
  • Comment

The First Webform - guestbook.aspx

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

To avoid confusing you with unnecessary code, I have removed the visualisation tags - like table, table header etc. 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 7, 11, and 15 to 17 I have implemented the required textfields. Please remember that if you want to use the same variables in codebehind, they need to have the same ID in both files and must be declared as public.

In the lines 8, 12, and 19 I have used the ASP.NET validator controls. This validator controls checks whether the user has entered any value in the textfields, without doing any round-trip to the server. This code is executed on the client side. In line 22, I have implemented a submit button with a OnClick event called Save_Comment.

This event is used to store the informations entered by the user to the XML file. The function of this event is available in the Guestbook.cs. In line 23 I have only implemented a reset button. This is all and nothing more has to be done in the webform. If you run the guestbook.aspx, you should see a webform like this:

By now you have seen how to display a webform, but you have not seen the code yet 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: public class Guestbook : Page
07: {
08:  // Create the required webcontrols with the same name as in the guestbook.aspx 09:  //file.
10:   public TextBox name;
11:   public TextBox location;
12:   public TextBox email;
13:   public TextBox website;
14:   public TextBox comment;
15:   public void Save_Comment(object sender, EventArgs e)
16:   {
17:    // Everything is all right, so let us save the data into the XML file
18:    SaveXMLData();
19:    // Remove the values of the textboxes
20:    name.Text="";
21:    location.Text="";
22:    website.Text="";
23:    email.Text="";
24:    comment.Text="";
25:   }
26: }
27: private void SaveXMLData()
28: {
29:   // Load the xml file
30:   XmlDocument xmldoc = new XmlDocument();
31:   xmldoc.Load( Server.MapPath("guestbook.xml") );
32:   //Create a new guest element and add it to the root node
33:   XmlElement parentNode = xmldoc.CreateElement("guest");
34:   xmldoc.DocumentElement.PrependChild(parentNode);
35:   // Create the required nodes
36:   XmlElement nameNode = xmldoc.CreateElement("name");
37:   XmlElement locationNode = xmldoc.CreateElement("location");
38:   XmlElement emailNode = xmldoc.CreateElement("email");
39:   XmlElement websiteNode = xmldoc.CreateElement("website");
40:   XmlElement commentNode = xmldoc.CreateElement("comment");
41:   // retrieve the text
42:   XmlText nameText = xmldoc.CreateTextNode(name.Text);
43:   XmlText locationText = xmldoc.CreateTextNode(location.Text);
44:   XmlText emailText = xmldoc.CreateTextNode(email.Text);
45:   XmlText websiteText = xmldoc.CreateTextNode(website.Text);
46:   XmlText commentText = xmldoc.CreateTextNode(comment.Text);
47:   // append the nodes to the parentNode without the value
48:   parentNode.AppendChild(nameNode);
49:   parentNode.AppendChild(locationNode);
50:   parentNode.AppendChild(emailNode);
51:   parentNode.AppendChild(websiteNode);
52:   parentNode.AppendChild(commentNode);
53:   // save the value of the fields into the nodes
54:   nameNode.AppendChild(nameText);
55:   locationNode.AppendChild(locationText);
56:   emailNode.AppendChild(emailText);
57:   websiteNode.AppendChild(websiteText);
58:   commentNode.AppendChild(commentText);
59:   // Save to the XML file
60:   xmldoc.Save( Server.MapPath("guestbook.xml") );
61:   // Display the user the signed guestbook
62:   Response.Redirect("viewguestbook.aspx");
63:   }
64: }

So far concerning the codebehind file, but what really happens here ?

You won't believe it, but not much. In line 1 to 5, I have implemented the minimal required namespaces which are needed to get access to several functions. In line 6, I have created a new class called Guestbook, please notice this is the class which is inherited by the guestbook.aspx file.

The line 10 to 14, declares 5 public variables of type type textbox, please remember also here, that these names have to be identical with the textboxes created in guestbook.aspx. In line 15, 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 function SaveXMLData() does the saving of the information for us. As we are using a XML database to store the information, we use the XmlDocument, XmlElement and XmlText classes. This classes provides the necassary functions which we need.

The lines 30 and 31 creates a new XMLDocument class object and loads the guestbook.xml file. In lines 36 to 40, the required nodes are created with the function CreateElement. The lines 42 to 46 retrieve the informations entered by the user and store them to an object of XmlText.

In lines 48 to 52, I have used the function AppendChild with the main XmlDocument object. This function stores the created nodes without the values. Finally in lines 54-88 the values are stored in the nodes we just created. In line 60, all changes are saved to the guestbook.xml. Line 62 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 an 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: public class ViewGuestbook : Page
09: {
10:   private void Page_Load(object sender, System.EventArgs e)
11:   {
12:     //Load the XML file
13:     XmlDocument doc = new XmlDocument( );
14:     doc.Load( Server.MapPath("guestbook.xml") );
15:     //Load the XSL file
16:     XslTransform xslt = new XslTransform();
17:     xslt.Load( Server.MapPath("guestbook.xsl") );
18:     string xmlQuery="//guestbook";
19:     XmlNodeList nodeList=doc.DocumentElement.SelectNodes(xmlQuery);
20:     MemoryStream ms=new MemoryStream();
21:     xslt.Transform( doc, null, ms);
22:     ms.Seek( 0, SeekOrigin.Begin );
23:     StreamReader sr = new StreamReader(ms);
24:     //Print out the result
25:     Response.Write(sr.ReadToEnd());
26:   }
27:}

I have created this class to display all comments to the user. Lines 1-7 are again used to implement the required namespaces. As we are using XSL for the visualisation we have to include the namespace System.Xml.Xsl. Line 8 creates 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. The function loads again the guestbook.xml in line 14. The XslTranform class is used to transform the XML elements into HTML. In line 16 to 17, I am loading the guestbook.xsl with the help of a XslTransform object. Line 19 creates a new object of class XmlNodeList.

With the help of this class we can select the required nodes. In line 20, I have used the class MemoryStream, which is avalable 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 21, I have assigned the xml data to the memorystream. The function Seek in line 22, sets the current position to zero. In line 23, I have created an object of the class StreamReader. This class is used to read the stream.

Line 25 then prints the result with the help of the function ReadToEnd(). This function reads the stream from the current position to the end. If you run the viewguestbook.aspx, you should see a webform like this:


XSL

As already mentioned, we use XSL for the transformation 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 a xsl for-each loop to iterate through the all 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 am calling the xsl template name, which looks something like this:

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


blog comments powered by Disqus
ASP.NET ARTICLES

- How Caching Means More Ca-ching, Part 2
- How Caching Means More Ca-ching, Part 1
- Reading a Delimited File Using ASP.Net and V...
- What is .Net and Where is ASP.NET?
- An Object Driven Interface with .Net
- Create Your Own Guestbook In ASP.NET
- HTTP File Download Without User Interaction ...
- Dynamically Using Methods in ASP.NET
- Changing the Page Size Interactively in a Da...
- XML Serialization in ASP.NET
- Using Objects in ASP.NET: Part 1/2
- IE Web Controls in VB.NET
- Class Frameworks in VB .NET
- Cryptographic Objects in C#: Part 1
- Sample Chapter: Pure ASP.Net

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials