|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article shows an easy way to create a guestbook built using ASP.NET and XML serialization. The guestbook is a simple last-entry-last log, and the number of entries is limited to 20. When the 21st entry is submitted, the first one in the list is removed. To format the data, I use the
The guestbook should be created as a Web Site project in Visual Studio 2005 or 2008. This is how the guestbook will look when it is ready: The codeThe GuestBookEntry classTo start with, we will create a new class file named using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// The class containing data and funtionality for one
/// guest book entry.
/// </summary>
public class GuestBookEntry
{
public string Message;
public string Name;
public DateTime Date;
/// <summary>
/// Public parameterless constructor needed by XML serialization.
/// </summary>
public GuestBookEntry() {
}
public GuestBookEntry(string message, string name, DateTime date) {
this.Message = message;
this.Name = name;
this.Date = date;
}
public override string ToString() {
return "<b>" + Message + "</b><br>" + "Name: <b>"
+ Name + "</b><br>" + "Date: "+ Date.ToString();
}
}
Note the overriding of the In this implementation, we override The GuestBookHandler classThe second class we are going to create is the The class contains the following code: using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
/// <summary>
/// The GuestBook handler will take care
/// of serializing the GuestBookEntry objects
/// to XML and storing it to the server.
/// </summary>
public class GuestBookHandler
{
private List<GuestBookEntry> entrys = new List<GuestBookEntry>();
private const string fileName = "App_Data\\GuestBook.xml";
private const int maxNumberOfEntries = 20;
private HttpServerUtility server;
public GuestBookHandler(HttpServerUtility serverUtility)
{
server = serverUtility;
Load(); // Read data from XML file.
}
public GuestBookEntry[] Entrys {
get { return entrys.ToArray(); }
}
public void Add(string message, string name, DateTime date)
{
if (entrys.Count >= maxNumberOfEntries) {
entrys.RemoveAt(0); // Remove first entry.
}
// Add new entry.
entrys.Add(new GuestBookEntry(StripHtml(message), StripHtml(name), date));
}
public string StripHtml(string HTML) {
// Removes tags from passed HTML
System.Text.RegularExpressions.Regex objRegEx
= new System.Text.RegularExpressions.Regex("<[^>]*>");
return objRegEx.Replace(HTML, "");
}
public void Save()
{
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer serializerObj = new XmlSerializer(entrys.GetType());
// Create a new file stream to write the serialized object to a file
StreamWriter writeFileStream = new StreamWriter(server.MapPath(fileName));
serializerObj.Serialize(writeFileStream, entrys);
// Cleanup
writeFileStream.Close();
}
private void Load()
{
// Create an instance of the XmlSerializer specifying type and namespace.
XmlSerializer serializer = new XmlSerializer(typeof(List<GuestBookEntry>));
// A FileStream is needed to read the XML document.
FileStream fs = null;
try {
fs = new FileStream(server.MapPath(fileName), FileMode.Open);
}
catch (System.IO.FileNotFoundException) {
return;
// No entrys to load.
}
XmlReader reader = XmlReader.Create(fs);
// Use the Deserialize method to restore the object's state.
entrys = (List<GuestBookEntry>)serializer.Deserialize(reader);
fs.Close();
}
}
Note the use of generic lists in the source code: Generics is a new feature introduced with .NET 2.0, which provides type safety at compile time. Generics letd you create data structures without committing to a specific data type in your code at design time. At compile time, the compiler ensures that the types used with the data structure are consistent with type safety. In other words, generics provides type safety, but without any loss of performance or code bloat. Generics is similar to templates in C++, even though the implementation is very different. The In order to serialize an object, we first create an XML provides the following benefits over standard serialization techniques:
The GuestBook.aspx fileThe GuestBook.aspx file contains the following HTML code: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GuestBook.aspx.cs"
Inherits="GuestBook" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Guestbook</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
Simple Guestbook</h1>
<asp:DataList ID="DataList1" runat="server"
CellPadding="4" ForeColor="#333333" Width="100%">
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#EFF3FB" />
<SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True"
ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:DataList><br />
</div>
Message<br />
<asp:TextBox ID="txtMessage" runat="server" Height="75px" Width="301px" >
</asp:TextBox><br />
<br />
Name<br />
<asp:TextBox ID="txtName" runat="server" Width="138px"></asp:TextBox>
<br />
<br />
<asp:Button ID="butSubmit" runat="server" Text="Submit"
OnClick="butSubmit_Click" />
</form>
</body>
</html>
Note the following code under the <asp:DataList ID="DataList1" runat="server" CellPadding="4" Width="305px">
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
</asp:DataList>
The The code-behind: Guestbook.aspx.csusing System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class GuestBook : System.Web.UI.Page
{
private GuestBookHandler guestBookHandler;
protected void Page_Load(object sender, EventArgs e)
{
guestBookHandler = new GuestBookHandler(this.Server);
BindData();
}
protected void butSubmit_Click(object sender, EventArgs e) {
guestBookHandler.Add(txtMessage.Text, txtName.Text, DateTime.Now);
guestBookHandler.Save();
txtMessage.Text = "";
txtName.Text = "";
// Re-bind data since the data has changed.
BindData();
}
private void BindData() {
DataList1.DataSource = guestBookHandler.Entrys;
DataList1.DataBind();
}
}
ConclusionAs you can see, it is not very difficult to create a guestbook in .NET. This guestbook is a last-entry-last guestbook, and contains the base code for developing your own. With minor changes, this guestbook can be made to a last-entry-first guestbook. All comments and improvement suggestions are welcome.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||