Have a question? ask www.kenlet.com
Home  |  FAQ  |  About  |  Contact  |  View Source   
 
SEARCH:
 
BROWSE:
    My Hood
Edit My Info
View Events
Read Tutorials
Training Modules
View Presentations
Download Tools
Scan News
Get Jobs
Message Forums
School Forums
Member Directory
   
CONTRIBUTE:
    Sign me up!
Post an Event
Submit Tutorials
Upload Tools
Link News
Post Jobs
   
   
Home >  Tutorials >  General ASP.NET >  Guestbook.NET - a beginner tutorial to ASP.NET
Add to MyHood
   Guestbook.NET - a beginner tutorial to ASP.NET   [ printer friendly ]
Stats
  Rating: 4.66 out of 5 by 56 users
  Submitted: 11/23/01
Andrew Ma (ajmaonline@hotmail.com)

 
What?
Learning any technology, in my opinion, is best done by experience. In the following tutorial, I will outline the steps on making a simple guestbook using ASP.NET. By the time you are finished this tutorial, you should have your very own guestbook page ready to go!

For Who?
My target audience are people with some HTML experience and some simple programming knowledge.

Here we go!

Guestbooks are popular on personal webpages. They give a chance for visitors to leave their mark, letting people know they were here, and complimenting/flaming the owner of the webpage. There are many services out there which provide Guestbook pages for people because it cannot be done with raw HTML. Anytime we have webpages which are always changing, there is usually some processing done on the server side. This is where ASP.NET comes in. Using ASP.NET we will produce a guestbook webpage which will use DataSets, XML and Server Controls (don't worry if you don't know what these are right now).

Pre-tutorial steps:
You will need to find a host location for your ASP.NET pages. The web server that will hold your webpages will need the .NET Framework installed (so most of your school provided web space won't work). You can run a copy of .NET framework (or the ASP.NET Premium Edition) on your local desktop.
(Installing ASP.NET Premium Edition will install the necessary files from the .NET framework that will allow you to use .NET and you don't need to install the whole framework)
To get ASP Premium Edition: Download it from the MSDN Site
Or to get free ASP.NET hosting, visit http://www.brinkster.com
To edit ASP.NET pages, you can use any text editor of choice. (I use Visual Studio.NET so I get the colouring).

Let's get started.

Here's an outline of how we will proceed:
- Create basic webpage
- Create a storage location where all the guestbook entries will be stored
- Write code that will make our webpage get the guestbook entries and display them.

First we'll start with a really crappy looking webpage for your guestbook. This is just a standard static page, which doesn't have any functionally (and looks like crap).
<html>
<head><title>Guestbook.NET</title></head>
<body bgcolor=#333399>

<table bgcolor=#eeeeee width=800 align=center><tr><td>

<p style="font-family:Arial;font-size:24pt;" align=center>Guestbook.NET</p>
<p align=center><a href="#PostNew">Post New Entry</a></p>

<table cellspacing="0" border="0" width=100%>
    <tr>
        <td>
            
    <!-- Guestbook entries will go here -->

        </td>
    </tr>
</table>

<hr size=0 />
<a name="PostNew" />
<table>
<tr><td>Name:</td><td><input name="Name" type="text" id="Name" /></td></tr>
<tr><td>E-mail:</td><td><input name="Email" type="text" id="Email" /></td></tr>
<tr><td>Location:</td><td><input name="Location" type="text" id="Location" /></td></tr>
</table>
Message: <textarea name="Message" rows="4" cols="50" id="Message"></textarea><br />
<input type="submit" name="GuestbookPost" value="    Post    "/>

</td></tr></table>

</body>
</html>


Now you create a file like this! (copy and paste) and save it on the webserver (recommended: guestbook.aspx). Make sure you use the .aspx extension so the web server knows it's an ASP.NET page.

Now that we have our basic structure of our webpage. Feel free to change the webpage above to look nicer. We move on to the storage of the guestbook entries.

Storage of guestbook entries can be anywhere: access database, oracle database, text file, SQL database, or XML. Let's use XML for this example. Not everyone has access to an SQL database or such.

We're going to base our guestbook entries on a XML storage that looks like this:
<guestbook>
  <entry name="Andrew Ma" email="ajmaonline@hotmail.com" location="Waterloo" date="11/23/2001 1:46:54 AM">This is my first entry!</entry>
</guestbook>


(If you aren't familiar with XML, don't worry, we're not concentrating on that in this tutorial. Search around the web or ask around the forums for more info on XML).
If you want to read some tutorials about XML in C#, Benjamin Collins wrote a good "Reading XML files" tutorial (Part I & Part II)

Save this file as guestbook.xml in the same directory as you put the guestbook.aspx page in.

This is pretty easy so far, isn't it? Anyways, we're coming to the harder part now. Since we have our webpage and our guestbook entries, how are they going to get combined? Here's where the coding comes in!

Displaying Guestbook entries
First we're going to add some standard ASP.NET tags which are needed to this page to work. These are standard things which are to be done with all ASP.NET pages.
 <%@ Page Language="C#" Debug="true" %>
 <%@ Import Namespace="System.Data" %>
 <%@ Import Namespace="System.Xml" %>

This should be added to the very top of the page.

Please also add <form runat="server"> just before the <!-- Guestbook entries will go here --> comment. And add </form> just after the post button (<input type="submit" name="GuestbookPost" value=" Post " id="GuestbookPost" />).

In ASP.NET, Microsoft has added some new controls and some new markup to show the new controls.
Here we have a DataList control which is the control to show data on a webpage. We're going to use this control to display our guestbook entries.
<asp:DataList ID="Guestbook" Runat="server" Width="100%">
    <ItemTemplate>
    <hr size=0/>
    Name: <%# DataBinder.Eval(Container.DataItem, "name") %><br />
    E-mail: <a href="mailto:<%# DataBinder.Eval(Container.DataItem, "email") %>"><%# DataBinder.Eval(Container.DataItem, "email") %></a><br />
    Location: <%# DataBinder.Eval(Container.DataItem, "location") %><br />
    Date: <%# DataBinder.Eval(Container.DataItem, "date") %><br />
    <i><%# DataBinder.Eval(Container.DataItem, "entry_Text") %></i>
    </ItemTemplate>
</asp:DataList>

Replace the <!-- Guestbook entries will go here --> comment with this ASP.NET tag.
The tag is quite simple. It contains an ItemTemplate tag which is the template to use for each guestbook entry. You notice that in the DataBinder.Eval method calls, the XML attribributes are there (see the XML guestbook storage file above). name, email, location and date are all attributes of an XML guestbook entry. The entry_Text is the keyword for the text inside the XML tag. We're not going to go into Datalists too much here but I hope you get an idea of what it does.

We've now created the control for the webpage to display the guestbook entry but how is it going to get the data? Now we finally get into the C# code (VB can be used too... or any .NET language for that matter).

<script runat="server">
    void Page_Load(Object sender, EventArgs e) {
        BindData();
    }
    
    void BindData() {
        XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("guestbook.xml"));
        DataSet myDataSet = new DataSet();
        myDataSet.ReadXml(myXmlReader);
        myXmlReader.Close();
        
        Guestbook.DataSource = myDataSet.Tables[0];
        Guestbook.DataBind();
    }
</script>


To get an ASP.NET page to run some code, we add a <script runat="server"> tag to specify where the code for this page will be. This <script> tag should go in between the <head> tag at the beginning of the file. We see in the example above there are two methods. Page_Load, you can probably guess, runs when the page is loaded. The BindData method was created here to so all the binding of the guestbook entries to the webpages. (again, see XML tutorials if you really want to know what's going on here.)

After you have this code entered into your webpage, you can load it up and see the guestbook entries loading on your screen! Wow you got yourself an ASP.NET page which pulls data from an XML document!

Posting new Guestbook entries
Now that your webpage is showing the guestbook entires, you're gonna want it to accept new ones so your friends can tell you how cool you are.

Any of you who have created textboxes and buttons in the old HTML way don't see anything wrong with what we have in our current structure, but ASP.NET has also provided some controls for us to use. Please replace all the <input> tages from above with this code:
<form runat="server">
<table>
<tr><td>Name:</td><td><asp:TextBox ID="Name" Runat="server"/></td></tr>
<tr><td>E-mail:</td><td><asp:TextBox ID="Email" Runat="server"/></td></tr>
<tr><td>Location:</td><td><asp:TextBox ID="Location" Runat="server"/></td></tr>
</table>
Message: <asp:TextBox ID="Message" TextMode="MultiLine" Columns=50 Rows=4 Runat="server"/><br />
<asp:Button ID="GuestbookPost" Text="    Post    " OnClick="GuestbookPost_Click" Runat="server"/>
</form>

You notice that all these tags are prefixed with "asp". That's because they're all ASP.NET server controls. They'll allow your webpage users to pass data from the webpage to webserver so it can be added to the XML file. If you want to enforce users to enter data into certain textboxes, read my ASP.NET Validator Controls tutorial.

Notice the GuestbookPost_Click value in the OnClick attribute of asp:Button. This is the method that gets executed when that button is clicked. So we now write code for that button.

void GuestbookPost_Click(Object sender, EventArgs e) {
    // Open an XML document.
    System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
    myXmlDocument.Load(Server.MapPath("guestbook.xml"));
    System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;

    // Create a new XML element and populate its attributes
    System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
    myXmlElement.SetAttribute("name", Server.HtmlEncode(Name.Text));
    myXmlElement.SetAttribute("email", Server.HtmlEncode(Email.Text));
    myXmlElement.SetAttribute("location", Server.HtmlEncode(Location.Text));
    myXmlElement.SetAttribute("date", DateTime.Now.ToString());
    myXmlElement.InnerText = Server.HtmlEncode(Message.Text);
    
    // Insert the new element into the XML tree and save
    myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
    myXmlDocument.Save(Server.MapPath("guestbook.xml"));
    
    // Re-bind data since the data has changed.
    BindData();
}


Place this code in the same <script> tag as your Page_Load function (All methods for an ASP.NET pages will end up there).

What else is there do to now? Nothing! You're done. Simple eh? Welcome to the world of ASP.NET! This tutorial provides you with just a taste of what ASP.NET can do and introduces you to the structure of ASP.NET pages. For more indepth tutorials, check out the other tutorials on Devhood.

Links
Devhood ASP.NET Message Forum - Feel free to ask questions to me or other Devhood members.
http://www.devhood.com - Can't forget to mention this great resource. :-)
http://www.asp.net - Good portal to other ASP.NET resources.
http://www.brinkster.com - Free hosting
guestbook.net - Sample of this guestbook of this tutorial in action.

Tips
  • Don't forget the import namespaces directives at the beginning.
  • Don't forget<form runat="server"> tag and make sure they're around your ASP.NET tags or else some of controls won't work!
  • Don't forget the "runat=server" attribute for your ASP.NET tags. If you don't have them, the webserver won't think to parse them.
    Copyright © 2001 Andrew Ma.

  • Return to Browsing Tutorials

    Email this Tutorial to a Friend

    Rate this Content:  
    low quality  1 2 3 4 5  high quality

    Reader's Comments Post a Comment
     
    I was thinking of something, had some ideas, then my brain exploded....
    Picked up just enough pieces to be able to ask for help...
    What if I want users to input a webpage or an e-mail address as a "Contact" field instead of just an "E-Mail" field? Brain scrambled right now... Loved the gustbook tutorial, BTW. :D
    -- Eddie Gosset, July 10, 2001
     
    Ok, solved my problem, added another field for websites.
    AND I made validations for name, e-mail location and Message as RequiredFields.
    At the end of
    void Page_Load(Object sender, EventArgs e) {
    BindData();
    I added
    Name.Text="";
    So as soon as it posts the entry in the guestbook, it clears name, and since it's a required field, No Double posting! :D
    -- Eddie Gosset, July 11, 2001
     
    It's a very complete tuorial. Very easy to understand and follow. I am looking forward for more of this type of tutorials from you.
    -- Jimmy Wong, November 27, 2001
     
    Download the code sample here.
    Also note: this code sample may not work in those free ASP.NET hosts since writer permission to files are off (so the guestbook won't update.) I'll see if there's a workaround.
    -- Andrew Ma, November 27, 2001
     
    Errata: the </form> just after the post button (<input type="submit" name="GuestbookPost" value=" Post "/>). -- notice that there is removed the no id attribute this time.
    -- Andrew Ma, November 27, 2001
     
    This is my first experience with ASP. I am impressed an excited to learn more. Thanks for making this easy to use tutorial that helped start me out. It is well worth the read.
    -- Andrew Chellinsky, November 30, 2001
     
    Easy to read and follow. Very helpful.
    -- Chris Roberts, December 06, 2001
     
    Agreed. It is excellent. I look forward to more tutorials from the author.
    -- Victor Lin, December 11, 2001
     
    I'm having trouble downloading the ASP.NET beta from the link provided here. Is there anywhere else I might get it from?
    -- Ammon Beckstrom, December 13, 2001
     
    Great work here, look foward to hearing more from you, hope u make more. Got any more good asp links?
    -- Anthony Ortizo, December 14, 2001
     
    Another great tutorial.
    -- Reid Jonasson, January 02, 2002
     
    Great tutorial. Just wondering, how can you delete an entry from the XML? Other than going into the file and removing it?
    -- Anonymous Person, January 03, 2002
     
    One this while working with this guestbook is that I found that if you Refresh the page after a post, it will post twice. Not a big issue, but if instead of BindData(); at the end of GuestbookPost_Click, you can Response.Redirect("/guestbook.aspx"); to ensure that if someone refreshes, it won't post twice, and will erase the fields once a post is successful, as a second indicator the post was valid.
    -- Anonymous Person, January 04, 2002
     
    Waiki, to remove guestbook entries, you'll have to look into the XML DOM support in ASP.NET. A short explanation would be that with the XML DOM stuff, it would load the XML file in as a tree and you would have to node you want to erase and then remove it. It's out the scope of this tutorial (since I didn't plan to write about XML) so it's not covered.
    -- Andrew Ma, January 05, 2002
     
    This tutorial has been helpful, especially for people like me who are just starting to use ASP.NET. Thank you.
    -- Johnny Wu, January 21, 2002
     
    nice tutorial
    -- Roopnath Grandhi, January 31, 2002
     
    This Tutorial is very complete, an excellent introduction to .NET programming (It certainly piqued my interest in .NET)
    -- Matt Billock, February 06, 2002
     
    I liked this tutorial, and it was easy to follow. Plus, it made use of XML (instead of MS Access), which is always worth cool points.
    -- Kurt Mackey, February 10, 2002
     
    Another awesome tutorial.... keep up the good work.
    -- Gabriel Chan, February 16, 2002
     
    I was thoroughly confused by this tutorial, but in a good way. Not only do I want to dig rampantly into learning more about XML, but I want to further extend this into something even more intricate.
    -- Adam Patridge, March 03, 2002
     
    I'm just barely going to start using .NET, thanks for some pointers
    to a beginer
    -- Lloyd Thompson, March 07, 2002
     
    Nice tutorial, very thorough. I like the step-by-step code examples, for those of us less familiar with ASP.NET.
    -- Charles Anderson, April 11, 2002
     
    I am a beginner at ASP.NET and I found this tutorial very informative and helpful. Thank you Andrew.
    -- Luke Walker, April 12, 2002
     
    Good tutorial.
    -- Brian Simoneau, April 15, 2002
     
    Great Tutorial
    -- Kirk Boone, April 23, 2002
     
    Great Tutorial
    -- Kirk Boone, April 23, 2002
     
    Great Tutorial
    -- Kirk Boone, April 23, 2002
     
    Good Tutorial, simple to follow at the beginning, BUT:

    1) page broke when adding the ASP controls to post a new entry
    ASP.NET complained that only one <form runat=server> per page was valid
    Fix: remove <form runat=server> ... </form> from code snippet

    2) permissions error on guestbook.xml when trying to do the first post
    Fix: in explorer: right click guestbook.xml, security tab, add machinename\ASPNET with write permissions so the webserver can write to it.

    Other than that, the tutorial went smoothly.
    -- Alejandro Simon, May 28, 2002
     
    Good ASP Tutorial, look forward to seeing more.
    -- Jon Wright, June 03, 2002
     
    A very good tutorial, it runs through with not too much information so you are not tempted to skip steps and not too little information so you have no idea what you're doing. Great work, very in depth
    -- Kenny Ma, July 05, 2002
     
    aksdjf
    asdkfgj'kas
    lkafsdjf
    aldfkj'asdf
    -- Blah Blah, August 16, 2003
     
    Ive just completed your tutorial on the guestbook, but as you said, it didnt work on a free server [I used brinkster], due to the write permissions being turned off. Ive tried the advice to right click /properties/security tab option, trouble is, I havnt got a security tab - just the general properties show up.
    Any suggestions? i cant justify paying for server space, as i am very new to this...
    -- pen elle, November 11, 2003
     
    pen... if I remember correctly, there is a db folder in Brinkster that you can write to. Try putting the xml file in that folder and then giving it write permissions. There should be Brinkster help files about that folder as well.
    -- Ben Martens, November 15, 2003
     
    While I did find it useful as a beginner ASP.net document, there were certain problems I had with the article. While I have never done any ASP programming before, I have programmed with a wide array of languages in the past and was therefor able to understand most of the code. However, at the same time I think that there are a few lines whose purpose are not really discussed. Controls are being made, as well as Nodes. Yet questions raise in my mind, such as: What is the control doing? What's it's main purpose? Why is there a type of node control being used? Must one use a node? While it does allow one to quickly make their own guestbook, it doesn't really help one in understanding what the lines of code mean. In other words, this tutorial is designed more to teach people to make their own guestbook, rather than get a beginner's look at ASP.
    -- Bill Peabody, May 16, 2005
     
    Basically it went together pretty easily. The flow was a little confusing. It might be nice to have the comeplete working code file available. One of the better beginner tutorials.
    -- David J, September 03, 2006
     
    Guys, i need some serious help.. Thanks for the tutorial.. easy, simple and effective.. Everything works fine EXCEPT for the very last code, that sets the action for the post comment button. The page reads whats on my .xml file but when i try to create a new post.. it gives me an error.

    WHERE EXACTLY AM I SUPPOSED TO PASTE THAT LAST CODE ??

    PLEASE ANSWER ASAP.

    THANX IN ADVANCE.

    TONY.
    -- tony emad, May 25, 2008
     

    Copyright © 2001 DevHood® All Rights Reserved