GuestBook Using XML Database in ASP.NET

Introduction

Most of the websites uses XML Database for the sections like Guestbook, Comments, and Feedbacks even in many Forums XML Databases are used. To be very frank, when I was learning XML, I created many XML files and integrated it to HTML web pages but when I learnt ASP.Net I thought to integrate it in ASP.Net also. I faced lots of problems like how to create XML files at run time, how to create columns in XML file at run time, how to connect it to ASP.Net so that visitors can input some text in XML file. On that time, there were lots of such questions in my mind. But my friend it is really very-very easy to work with XML files. Let's take a look at some basic points.

Prerequisite

To learn this article, you must have some basic understanding of XML Database.

Creating XML File at run time

To create XML at run time, we must check its existence first and if not finds then will create a new one. To do this we have to integrate all in Page Load event. Let's take a look how it is?

Sub Page_Load(Src As Object, E As EventArgs)

        'Checking the existance of XML database
      strFilePath = Server.MapPath("guestbook.xml")

        'If XML database not exit then it creates a new XML database 
        'using other functions given below
        If Not Page.IsPostBack Then

            'If XML file not exists, create a new one
            If Not File.Exists(strFilePath) Then
                InitializeXMLFile()
            End If
            'If XML database exist then runs it
            PopulateDataSet()
            DisplayData()
        End 
If
End Sub

Above coding will fist check its existence using file name 'guestbook.xml' and if not finds then it will create a new one. Let's take a look how it is?

Sub InitializeXMLFile()
        'Create a new data-set
      myDataSet = New DataSet()

        'Create a new data-table
      Dim myTable As DataTable = myDataSet.Tables.Add("myguestbook")

        'Define column id, it will not be visible on form page
      Dim myDataColumn as DataColumn = myTable.Columns.Add("id", Type.GetType("System.Int32"))
      With myDataColumn
            .AutoIncrement = true
            .AutoIncrementSeed = 1
            .AutoIncrementStep = 1
      End 
With

        'Seting column named id as the primary key
      Dim arrPrimaryKey(1) As DataColumn
      arrPrimaryKey(0) = myDataColumn
      myTable.PrimaryKey = arrPrimaryKey

        'Defining other columns which will be visible on form
      myTable.Columns.Add("datetime", Type.GetType("System.DateTime"))
        myTable.Columns.Add("name", Type.GetType("System.String"))
        myTable.Columns.Add("email", Type.GetType("System.String"))
      myTable.Columns.Add("comments", Type.GetType("System.String"))

        'Writing table structure in XML file which is defined above
      myDataSet.WriteXml(strFilePath, XMLWriteMode.WriteSchema)
End Sub

Above coding will created new XML Database with Data Table named 'myguestbook'. Now we have to populate it for use. Let's take a look how it is?

Sub PopulateDataSet()
      myDataSet = New DataSet()
      myDataSet.ReadXml(strFilePath, XmlReadMode.ReadSchema)
End Sub

Above coding will populated the XML Database file for use as 'Read Only' Property. Now we have to display its data on web page. Let's take a look how it is?

 Sub DisplayData()
      'Bind data to Repeater
      Dim myDataView As DataView = myDataSet.Tables(0).DefaultView

      'Uncomment next line to display the newer messages first
      myDataView.Sort = 
"id DESC"

      myRepeater.DataSource = myDataView
      myRepeater.DataBind()
End Sub

In above coding, we are displaying the data in descending order. Now we have to create web page and connect it to XML file. In web page we should have three controls for date and time, name and email id and a command button to insert data in XML file. Let's take a look to create web page with controls.

<table style="width: 226px" bgcolor="#dcdcdc">
            <tr>
                  <td>Name</td>
                  <td style="width: 292px"><asp:textbox id="txtEmail" runat="server" columns="30"maxlength="30" Width="264px" /></td>
            <td style="width: 134217727px" align="left" valign="top">
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage
="RequiredFieldValidator" ControlToValidate="txtEmail">*</asp:RequiredFieldValidator></td>
            </tr>
            <tr>
                  <td>Email</td>
                  <td style="width: 292px"><asp:textbox id="txtName" runat="server" columns="50"maxlength="50" Width="263px" /></td>
            <td style="width: 134217727px" align="left" valign="top">
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="txtName">*</asp:RequiredFieldValidator><br />
                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="RegularExpressionValidator" ControlToValidate="txtName"
 ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator></td>
            </tr>
            <tr>
                  <td valign="top">Comments</td>
                  <td style="width: 292px"><asp:textbox id="txtComments" runat="server"columns="30" rows="4" textmode="multiline" wrap="true" /></td>
            <td style="width: 134217727px" align="left" valign="top">
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"ErrorMessage="RequiredFieldValidator"ControlToValidate="txtComments">*</asp:RequiredFieldValidator></td>
            </tr>
            <tr>
                  <td colspan="2" align="right"><asp:button id="btnSubmit" text="Submit"onclick="btnSubmit_Click" runat="server" /></td>
            <td align="left" colspan="1" style="width: 134217727px" valign="top">
            </td>
            </tr>
      </table
>

In above coding we have used some validation and regular expressions. Now we only have to call the XML file to insert the data in XML file and to display the data on web page. Let's take a look to display the data on web page from XML file.

<asp:Repeater id="myRepeater" runat="server">
      <HeaderTemplate>
            <table border="0" cellpadding="2" cellspacing="0" width="100%" style="font: 10pt verdana">
      </HeaderTemplate>
      <ItemTemplate>
                <tr width="100%">
                  <td width="100%">
                    <u><b>Date and Time:</b> <%# DataBinder.Eval(Container.DataItem, "datetime")%></u>
                  </td>
                  </tr>
                  <tr>
                  <td>
                    <b>Name:</b> <%#DataBinder.Eval(Container.DataItem, "name")%>
                  </td>
                  </tr>
                  <tr>
                  <td width="100%"> 
                    <b>Comment:</b> <br /><i><%# DataBinder.Eval(Container.DataItem, "comments")%></i>
                  </td>
                  </tr>
                  <tr>
                  <td>
                    <b>Email ID:</b> <a href="mailto:<%#DataBinder.Eval(Container.DataItem, "email")%>?subject=Email ID">
Send Email</a><br><br>
                  </td>
                  </tr>
      </ItemTemplate>
      <FooterTemplate>
            </table>
      </FooterTemplate>
      </asp:Repeater
>


In above coding we have used Repeater control and some templates. Remember in web page we have created a button as follows

<td colspan="2" align="right"><asp:button id="btnSubmit" text="Submit" onclick="btnSubmit_Click"runat="server" />

In above coding we are calling a function named btnSubmit_Click() but still we have not created such functions. This function will insert the data in XML file. Let's take a look at function. 

Sub btnSubmit_Click(ByVal src As ObjectByVal e As EventArgs)
        If txtName.Text = "" Or txtEmail.Text = "" Or txtComments.Text = "" Then
        Else
            PopulateDataSet()
 
            'Add new entry to DataSet
            Dim myDataRow As DataRow = myDataSet.Tables(0).NewRow()
            myDataRow("datetime") = DateTime.Now()
            myDataRow("name") = txtEmail.Text.ToString()
            myDataRow("email") = txtName.Text.ToString()
            myDataRow("comments") = txtComments.Text.ToString()
            myDataSet.Tables(0).Rows.Add(myDataRow)

            'Write to XML
            myDataSet.WriteXml(strFilePath, XmlWriteMode.WriteSchema)

            DisplayData()

            'Clear textboxes
            txtName.Text = ""
            txtEmail.Text = ""
            txtComments.Text = ""
        End 
If
End Sub

Now we have every thing to run this project successfully. Here is some screenshots of my web page.

HAVE A HAPPY CODING!

Up Next
    Ebook Download
    View all
    Learn
    View all