In this tutorial, we see how to develop a simple comments section. This comments section is going to be a similar one to what we usually see in our day to day experience. Here we use TinyMCE editor to enable Html Comments. And also catpcha is enabled (with the help of reCaptcha of Google). The basic outline would be – Users provide their general details like name and email, and also they can provide Html Comment (using TinyMCE), and finally they should enter the text showed in the captcha for validating robots. Then we take the Html string, encode it using HtmlEncode(), store it in database. Finally we retrieve the encoded string from the database, we then decode it and display it in the page as Comment.
NOTE :-
- TinyMCE Download – Click Here (zip file)
- TinyMCE Examples & Documentation – Click Here
- reCaptcha Download – Click Here (zip file)
- reCaptcha Dcumentation – Click Here
================================================================================================
Database Design
Create a sample ‘CommentsDB’ database in VS 2010, which holds the info about comments written by users.
================================================================================================
- Open VS 2010 -> View -> Server Explorer
- Right Click ‘Data Connections’ node -> Add new SQL Server Database
- Select a Server (from DropDownList) -> Prefer Windows Authentication -> Give a Name to the new database, here we use ‘CommentsDB’.
The database has been created, now we create a table.
- Expand ‘CommentsDB’ in the Server Explorer -> Right Click ‘Tables’ folder -> Select ‘Add New Table’.
Give the details of the table fields as shown below –
Save (press CTRL + SHFT + S) the table, it asks to give a table name; in this case we use ‘CommentsTable’.
Save the Database – This completes the Database design. Now lets create a website – ‘CommentsSection’, in which we code according to our requirement.
================================================================================================
CommentsSection Website
Create a sample ‘CommentsSection’ website in VS 2010.
================================================================================================
- Open Vs 2010 –> File –> New –> Website.
- select –> C#
- Select ‘Asp.Net Empty Website’ –> name – ‘CommentsSection’.
================================================================================================
Custom Classes
These classes hold the basic operation with Database, along with generic information of a Comment.
================================================================================================
- Right Click ‘CommentsSection’ in Solution explorer of VS 2010.
- Select ‘Add Asp.Net Folder…’ –> App_code.
- Add two classes (Right Click App_Code folder in Solution Explorer –> Add New Item –> Class), namely Comment.cs and CommentsDB.cs
- Comment class holds the generic information of a particular comment.
- CommentDB class holds the code for database connectivity i.e., to get comments from the database and also to insert new comments to the database.
================================================================================================
Comment.cs
This class hold the definition of an individual comment.
================================================================================================
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Comment { public string name { get; set; } public string email { get; set; } public string comment { get; set; } }
================================================================================================
CommentsDB.cs
This class hold the code for database interactivity.
================================================================================================
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Web.UI; public class CommentsDB { public string ConnectionString { get; set; } public List<Comment> GetComments() { using (SqlConnection conn = new SqlConnection(ConnectionString)) { try { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select * from CommentsTable"; cmd.Connection.Open(); List<Comment> comments = new List<Comment>(); SqlDataReader sdr = cmd.ExecuteReader(); while (sdr.Read()) { Comment c = new Comment(); c.name = HttpContext.Current.Server.HtmlDecode(sdr["name"].ToString()); c.email = HttpContext.Current.Server.HtmlDecode(sdr["email"].ToString()); c.comment = HttpContext.Current.Server.HtmlDecode(sdr["comment"].ToString()); comments.Add(c); } sdr.Close(); cmd.Dispose(); conn.Close(); return comments; } catch (Exception ex) { return null; } } } public string StoreComment(Comment c) { using (SqlConnection conn = new SqlConnection(ConnectionString)) { try { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Insert into CommentsTable(name,email,comment) Values(@name,@email,@comment)"; cmd.Parameters.AddWithValue("@name", c.name); cmd.Parameters.AddWithValue("@email", c.email); cmd.Parameters.AddWithValue("@comment", c.comment); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Dispose(); conn.Close(); return "Comment submitted Successfully!!!"; } catch (Exception ex) { return ex.Message.ToString(); } } } }
================================================================================================
reCaptcha
reCaptcha is used to prevent robots entering comments in the comment section.
================================================================================================
- Download reCaptcha – Click Here (zip file)
- Unzip the files.
- Now, Right Click the ‘CommentsSection’ Website in the Server Explorer of VS 2010.
- select ‘Add Reference’.
- Navigate to the location where the unzipped files are stored and then select ‘Recaptcha.dll’.
- click ok.
- This will create a reference of the recaptcha dll in the bin folder of the website.
To implement recaptcha in the website – We need to request for private and public keys –
- Navigate to the link – https://www.google.com/recaptcha/admin/create
- Enter domain name and then access the public and private keys.
Once the keys are generated, we can use reCaptcha in the following way –
At the top of the aspx page, insert this:
<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>
Then insert the reCAPTCHA control inside of the <form runat="server"> tag:
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" PublicKey="your_public_key" PrivateKey="your_private_key" />
We need to substitute yur public and private key into PublicKey and PrivateKey respectively.
================================================================================================
TinyMCE Html Editor
TinyMce is a clientside script which converts the normal TextAreas to html Editors.
================================================================================================
- Download TinyMCE – Click Here (zip file)
- Unzip the files.
- Copy paste the extracted folder ‘TinyMCE’ into the root directory of the website.
That’s it, now we can use the TinyMCE client side scripts in our application with the help of <script> tag.
================================================================================================
Folder Structure
The complete Solution Explorer structure of ‘CommentsSection’ website.
================================================================================================
================================================================================================
web.config
Incorporate requestValidationMode (in case .net 4.0 is used) to enable Textbox accepting Html input.
================================================================================================
For more details on requestvalidationMode – http://www.intstrings.com/ramivemula/asp-net/jumpstart-4-validaterequest-in-asp-net/
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> <httpRuntime requestValidationMode="2.0"/> </system.web> </configuration>
================================================================================================
Default.aspx
Create a Webform – named Default.aspx. This page holds the UI to insert and retrieve comments from the database using classes from the App_Code folder.
================================================================================================
- Right Click ‘CommentsSection’ website in the Solution Explorer of VS 2010.
- Select ‘Add New Item’.
- Select C# – select Webform’ – name Default.aspx.
- Uncheck both the checkboxes – so that we don’t use Mater Page and codebehind model.
<%@ Page Language="C#" ValidateRequest="false" %> <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> CommentsDB cdb = new CommentsDB(); protected void Page_Load(object sender, EventArgs e) { DisplayComments(); } protected void btnComment_Click(object sender, EventArgs e) { if (Page.IsValid) { Comment c = new Comment(); c.name = Server.HtmlEncode(txtName.Text); c.email = Server.HtmlEncode(txtEmail.Text); c.comment = Server.HtmlEncode(txtComment.Text); lblMessage.Text = cdb.StoreComment(c); DisplayComments(); } } protected void DisplayComments() { cdb.ConnectionString = "Data Source=RAMILU-PC\\SQLEXPRESS;Initial Catalog=CommentsDB;" + "Integrated Security=True;Pooling=False"; List<Comment> lstComments = cdb.GetComments(); if (lstComments.Count != 0) { rptrComments.DataSource = lstComments; rptrComments.DataBind(); lblCommentsTitle.Text = "Comments :- "; } else { lblCommentsTitle.Text = "No comments till Date!!!"; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode: "textareas", theme: "advanced", plugins: "inlinepopups,insertdatetime,preview,advimage,advlink", // Theme options theme_advanced_buttons1: "bold,italic,underline,strikethrough,|" + ",formatselect,fontselect,fontsizeselect", theme_advanced_buttons2: "bullist,numlist,|,undo,redo,|,link,unlink,anchor,image,code,|" + ",insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3: "", theme_advanced_buttons4: "", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_resizing: false, // Example content CSS (should be your site CSS) content_css: "css/content.css", // Drop lists for link/image/media/template dialogs template_external_list_url: "lists/template_list.js", external_link_list_url: "lists/link_list.js", external_image_list_url: "lists/image_list.js", media_external_list_url: "lists/media_list.js", // Style formats style_formats: [ { title: 'Bold text', inline: 'b' }, { title: 'Red text', inline: 'span', styles: { color: '#ff0000'} }, { title: 'Red header', block: 'h1', styles: { color: '#ff0000'} }, { title: 'Example 1', inline: 'span', classes: 'example1' }, { title: 'Example 2', inline: 'span', classes: 'example2' }, { title: 'Table styles' }, { title: 'Table row 1', selector: 'tr', classes: 'tablerow1' } ] }); function Call() { tinyMCE.triggerSave(false, true); return Page_ClientValidate(); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblCommentsTitle" runat="server" Text="Comments :- "></asp:Label> <br /> <asp:Panel ID="Panel1" runat="server" Width="500px" > <asp:Repeater ID="rptrComments" runat="server"> <ItemTemplate> <div style="background-color:#FFFF66"> <%#Eval("name")%> Says... <%#Eval("comment")%> </div> </ItemTemplate> <AlternatingItemTemplate> <div style="background-color:#CCFF33"> <%#Eval("name")%> Says... <%#Eval("comment")%> </div> </AlternatingItemTemplate> <SeparatorTemplate> <hr /> </SeparatorTemplate> </asp:Repeater> </asp:Panel> <table style="width: 500px"> <tr> <td> <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label><br /> </td> <td> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="*" ControlToValidate = "txtName"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label ID="lblEmail" runat="server" Text="Email"></asp:Label><br /> </td> <td> <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> <asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="*Invalid Email address." display="dynamic"></asp:RegularExpressionValidator> <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage="*" ControlToValidate = "txtEmail"></asp:RequiredFieldValidator> </td> </tr> <tr> <td valign="top"> <asp:Label ID="lblComment" runat="server" Text="Comment"></asp:Label> </td> <td> <asp:TextBox ID="txtComment" runat="server" TextMode="MultiLine" ></asp:TextBox> <asp:RequiredFieldValidator ControlToValidate="txtComment" ID="rfvComment" runat="server" ErrorMessage="Write a Comment"></asp:RequiredFieldValidator> </td> </tr> <tr> <td valign="top"> <asp:Label ID="lblCaptcha" runat="server" Text="Enter Text"></asp:Label> </td> <td> <recaptcha:RecaptchaControl ID="recaptcha" runat="server" PublicKey=”your_public_key" PrivateKey="your_private_key" /> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnComment" runat="server" Text="Submit Comment" OnClick="btnComment_Click" OnClientClick="return Call()" /> </td> </tr> <tr> <td> </td> <td> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </td> </tr> </table> </div> </form> </body> </html>
================================================================================================
OUTPUT
================================================================================================
NOTE :-
-
Validation of user input can be done in a much better way. We can parse the Html strings which are submitted by user and only can display the content which is not harmful (as a malicious user can send <script> tags as an attack). So we can think of using HtmlAgilityPack or even Regular Expressions to parse the content and then display it to the user.
-
The above functionality can be highly interactive if AJAX is used in the page (say UpdatePanels for partial page rendering).
-
There are many other third party components for Html Editors and also for Captchas. I have chosen these TinyMCE and reCaptcha on a random basis.
-
In the above code we customized TinyMCE in the JavaScript. For more options refer to the documentation of the TinyMCE.
-
I never narrated the flow of code, it can be better understood if the same is debugged with break points.
Disclaimer:
All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world.







[...] this article: Simple Html Editor based Comments Section with Captcha feature … Share and [...]
this is cool dude
public string ConnectionString { get; set; }
I know what this line does but I don’t understand why you have get; set; in there can you plz explain?
hi im getting this error message.. can u please help?
G:\Documents and Settings\Prashanth\My Documents\Visual Studio 2008\WebSites\WebSite2\Default.aspx(34,9): error CS0246: The type or namespace name ‘List’ could not be found (are you missing a using directive or an assembly reference?)
import System.Collections.Generic namespace
Very nice article…I was looking for some tutorial like this as i had to implement the same technique in my website….Thanx a lot…superb article