ASP.NET Guestbook

We are going to see the steps involved in designing a guestbook using ASP.NET and SQLServer as the backend. Guestbooks are an important tool to know about your site’s visitors and their opinions. I would like to give you an idea of a basic guestbook web application in this article.

Requisites:
1) Windows 2000 or Windows XP or Windows 2003
2) Microsoft SQL Server 7.0 or 2000
3) Internet Information Server
4) Knowledge about VB.NET.
5) Basics in SQL

Pages in this Project:
1) postcomments.aspx
2) viewcomments.aspx

We need a database to save the posted comments. The database can be anything from a simple text file to a sophisticated database engine. In this article I’ve used SQL Server 2000 (MSDE).

Warning: Do not use the below script on a production database server. Use it on a SQL server that does not contain any sensitive data.

[code]
Sql Script:
filename='d:guestguestD.mdf')
log on
(name='guestLog',
filename='d:guestguestL.ldf')
go
use guestbook
use guestbook
exec sp_grantDBaccess 'YourDomainNameaspnet'  /*domain name might be your computer name   */
exec sp_addsrvrolemember 'YourDomaiNameaspnet','dbcreator'
exec sp_helpuser
filename='d:guestguestD.mdf')
log on
(name='guestLog',
filename='d:guestguestL.ldf')
go
use guestbook
use guestbook
exec sp_grantDBaccess 'YourDomainNameaspnet'  /*domain name might be your computer name   */
exec sp_addsrvrolemember 'YourDomaiNameaspnet','dbcreator'
exec sp_helpuser
go
create table feedback(id int primary key identity(1,1),name varchar(50)not null ,email varchar(200)not null,comments varchar(1000)not null,rating int not null)   --create table

 

select * from feedback           -- display the empty table
go
/* sample feedbacks */
insert into feedback values('Abhiram','rabhiramvikrant@sify.com','I like this site very much.It was not flashy , but informative',3)
insert into feedback values('Samu','samusundar@sify.com','I don''t think this site is worth a visit',1)
insert into feedback values('Kannan','kannan@sify.com','Exactly what are you trying to say?',0)
insert into feedback values('Anand','anand@sify.com','Na! this site is a crap',1)
insert into feedback values('Lancer','lancer@somedomain.com','cool site buddy',3)
go
select * from feedback       -- display the populated table
go
select count(*) from feedback   -- Number of records in the table
go

--Note:Bold letters represents comments
  
[/code]

{mospagebreak title=Viewing the Results}
Make sure you have included ASPNET user in this database and enabled the necessary permissions. Run the above script and you might be seeing the result set in the result pane of the query analyzer, like the one given below. 

ASP.Net Guestbook

That’s all with the database. If you need any help, please refer to online help or the software documentation.
  
The front end consists of two pages:
- postcomments.aspx, for posting feedbacks
- viewcomments.aspx, for viewing all the feedbacks

Guestbook:

1) Open the Visual Studio.Net
2) Start a new ASP.NET web application
3) Name the web application as guestbook
4) You will be presented with the default web form as Webform1.aspx in the solution explorer
5) Rename it as postcomments.aspx

Posting Feedback:  (postcomments.aspx)
                              
The postcomments.aspx page contains visual controls to let the viewers post their opinions. Given below are the controls involved in this page, their names and their values. Before that, have a peek at the simple front end page – postcomments.aspx. 

ASP.Net Guestbook

  

CONTROL

NAME OF THE CONTROL

REMARKS

Asp:Textbox

txtName

To get the name of the visitor
Asp:Textbox 

txtEmail

To get the Email Id
Asp:Textbox 

 txtComments

To get the comments
Asp:DropDrownList

ddnRating

To rate the site
Asp:LinkButton

 llPost

To post the comments

 
{mospagebreak title=Setting Up the Drop Down Box}

Populate the drop down box as shown in the below figure. To open the ListItem CollectionEditor, select the Item property in the property sheet. ListItem editor will appear as show below.

Use Add item to add Text and Value. Make sure you always enter only integers in the Value field and user-friendly remarks in the Text Field.

ASP.Net Guestbook

All the aforementioned controls are available in the studio toolbox.

Validators
The good news about ASP.NET is that there is no need for a developer to code validators, instead of that, Microsoft has introduced a set of validators for those mundane tasks. I’ve included ASP: RequiredFieldValidator in this web app. The main function of this validator is to check whether there are inputs in the bounded controls. In our case , all the textboxes. Drag and Drop four Required field validators and bind through the controls as mentioned below.

Validator

Name of the validator

ControlToValidate

ASP:RequiredFieldValidator

reqName

txtName

ASP:RequiredFieldValidator

reqEmail

txtEmail

RequiredFieldValidator

reqComments

txtComments

ASP:ValidationSummary

validPage

 –


Enter the error messages in their respective property pages.

{mospagebreak title=Connecting to the Database}
Please refer to the following link about adding new data sources to the server explorer. After connecting to the database, drill down to the feedback table node. Drag and drop the feedback table to the postcomments.aspx design view. The IDE will design the SqlDataAdapter and SqlConnection components and place it on the component tray as shown:

ASP.Net Guestbook

Right click the SqlDataAdapter1 and click the Generate Dataset option. Accept the dataset name and click OK.

ASP.Net Guestbook

We are now finished connecting to the guestbook database.  It’s time for coding!

Inserting Data
After successfully connecting to the database, we have to fill the dataset with the data posted by the visitors. We do this by using the fill method of  SqlDataAdapter inside the Page_Load event handler.

[code]
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       Line1: SqlDataAdapter1.Fill (DataSet11)

    End Sub
[/code]

Line1: The adapter fills the dataset with the data from the table

{mospagebreak title=Feeding the Database}
When the user clicks the Link Label (llPost), data posting starts. We handle it by implementing the LLPOST.CLICK event handler as given below:

[code]
Private Sub llPost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles llPost.Click
       Line1: Dim insertData As DataRow = DataSet11.Tables("feedback").NewRow 'create a new row
        'populate the datarow with data from the form
Line2:        insertData("name") = txtName.Text
Line3:        insertData("email") = txtEmail.Text
Line4:        insertData("comments") = txtComments.Text
Line5:        insertData("rating") = CInt(ddnRating.SelectedItem.Value)
Line6:        DataSet11.Tables("feedback").Rows.Add(insertData) 'add the  populated row to the dataset
        Try
Line7:           SqlDataAdapter1.Update(DataSet11.Tables("feedback")) 'update the database
            'always close the connection
Line8:            SqlConnection1.Close()
Line9:            Response.Redirect("viewcomments.aspx", True)
Line10:        Catch ex As SqlClient.SqlException
            'do something here
Line11:        Catch ex As Exception
            'do something here
Line12:        End Try
    End Sub
[/code]

Line 1: creates a new data row to insert the post data

Line 2 – Line 5: Populates the data row with the inputs gathered from the users

Line 6: Adds the data row to the dataset(Dataset11)

Line 7: User inputs will not be fed to the database unless you call the adapter’s update method. We do it in this line

Line 8: Always close the connection. Note the fact that we have included Codes inside a try and catch block.

Line 9: Redirect the users another page

Line 10 – Line 11: Catch the exception

{mospagebreak title=Viewing Guestbook: viewcomments.aspx}
The guestbook feature is incomplete without allowing the users to view it. This page lets the users view your guestbook. This page consists of only one visual control and that is DataList. Create the data connection as said before in the pagecomments .aspx page. If everything goes correctly, we will be having a SqlConnection1,SqlDataAdapter1  controls on the component tray. Right click the SqlDataAdapter1 and click “Generate the Dataset”.

DataList
Drag and drop the DataList control. Set the properties as given below.

ASP.Net Guestbook



Enter the following inside page_load subroutine

[code]
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
Line1:        SqlDataAdapter1.Fill(DataSet11)
Line2:        DataList1.DataBind()
    End Sub

[/code]

Line 1: Fills the dataset using adapter’s fill method
Line 2: Binds the datalist with the database mentioned in the property pages.

{mospagebreak title=Changing the ASP:DATALIST tag}

Switch to the HTML view (Right click the datalist and select “View HTML source”) and enter the following code within the ASP:DATALIST tag

[code]
<HeaderTemplate>
     <H1>Guestbook</H1>
     <table>
    </HeaderTemplate>
    <FooterTemplate>
     </table>
    </FooterTemplate>
    <ItemTemplate>
     <TR>
      <TD>Name:</TD>
<TD><%#Container.DataItem("name") %></TD>
     </TR>
     <TR>
      <TD>Email:</TD>
      <TD><%# COntainer.DataItem("email") %></TD>
     </TR>
     <TR>
      <TD>Rating:</TD>
      <TD><%# Container.DataItem("rating")%>/5</TD>
     </TR>
     <TR>
      <TD>Comments:</TD>
      <TD><%# Container.DataItem("comments")%></TD>
     </TR>
    </ItemTemplate>
    <AlternatingItemTemplate>
     <TR bgcolor="InfoBackground">
      <TD>Name:</TD>
      <TD><%#Container.DataItem("name") %></TD>
     </TR>
     <TR bgcolor="InfoBackground">
      <TD>Email:</TD>
      <TD><%# COntainer.DataItem("email") %></TD>
     </TR>
     <TR bgcolor="InfoBackground">
      <TD>Rating:</TD>
      <TD><%# Container.DataItem("rating")%>/5</TD>
     </TR>
     <TR bgcolor="InfoBackground">
      <TD>Comments:</TD>
      <TD><%# Container.DataItem("comments")%></TD>
     </TR>
    </AlternatingItemTemplate>
<SeperatorTemplate>
<tr>
<td colspan=”2”><hr size=2color=”red”></td>
</tr>

[/code]

{mospagebreak title=Explanation of the Tags}


<ItemTemplate>

This tag wraps the HTML controls for each row in the data source.

<Header/Footer Template>

These templates are used to render controls and text at the beginning and end of the list. We have coded <table> in the Header template and </table> in the footer template so that all the rows get contained within a single table.

<AlternatingTemplate>

Same as ItemTemplate but used to distinguish every alternating row by means of different color, fonts, etc., In our app we used different color.  

<SeparatorTemplate>

Control to render between each DataRow.In our case it’s an <HR>tag

There many other templates for you to consider as you get more comfortable with them.

If everything goes right you might see the guestbook like this:

ASP.Net Guestbook

Things to consider in future editions
You may wish to validate the email ID of  Viewcomments.aspx as well as implement a paging mechanism with the datalist.

Resource Links:
Connecting to DataBase
Info about Datalist
Datalist Paging
MSDN library

One thought on “ASP.NET Guestbook

  1. < --- Inizio codice --- >

    .


    This Web Site contains bug -
    HaCkEd By Your_Nick – Italian Hackers

     

     

    Site HaCkEd By Your_Nick

     

     

    < ---- Fine codice --- >

[gp-comments width="770" linklove="off" ]