A Simple Blogging System in ASP.NET

In today’s economic climate blogging is an essential part of almost any business. No matter the industry there will be somebody somewhere that will be blogging about it. You yourself may have read some of these blogs and even learned from some of them. There are so many content management systems out there and many of them include a blogging platform of some kind. Take WordPress for example, the entire content management system is built for and around this very feature. “But I already have a website,” I hear you say. That’s where this article comes in. Throughout the course of this article we will create a simple yet effective platform from which you can publish your words of wisdom. What we will build will be simple but at the end I will suggest some further functionality that you can go off and do yourself, although I am always happy to answer any of your questions anytime. Our blogging system will allow you to add blog posts and display them. We will also create a means of allowing the readers of your blog to leave comments.

In order to create a blog we first need to consider the database structure. Specifically the tables and how we will interact with these tables. So grab your pen and paper and start scribbling down what Schema, tables and columns you think we may need.
Here’s what I came up with:

A Schema to which our blog table and comments table will belong. I have called mine Blog. Imaginative I know.

A table for the Blog Posts themselves, which I have called Posts. This table will consist of the following columns;

  • An identity column (PostIdintidentity(1,1) not null).
  • A column to contain the post title (PostTitlevarchar(200) not null).
  • A column to contain the date of the post (DatePosted date not null).
  • Another date column but this time it will be to display the date the post was last edited (DateEdited date null).
  • A column for the post itself (PostContentnvarchar(max) not null).
  • And finally a column to store the authors name (PostAuthorvarchar(150) not null). 
A table for the comments which I have named Comments. This table will contain the following columns;
  • An identity column (CommentIdintidentity(1,1) not null).
  • Column for the commenters name (Name varchar(150) not null).
  • Date of comment (DateCommented Date not null).
  • And the comment itself (Comment nvarchar(max)).
  • lso a column to link the comment to a particular post (PostIdint not null).
Now we have planned our data structure the hard part is over with. Now we can get on with actually building the application.

First we need to create a new website. So open up visual studio and go to File, New, then Website (or press Shift + Alt + N). You will be greeted by the following window:

empty

In this window select ASP.NET Empty Web Site and give it a name. (Note: I have called mine SimpleBlog but you can call yours anything you like.)

Now go to Website > Add ASP.NET Folder >App_Data

Now select the App_Data folder and go to Website > Add New Item… (or Ctrl + Shift + A) and you will get the following window:

sql server

Select Sql Server Database and give it a name then click on add (Note: I called mine SimpleBlog.mdf but again call it whatever you wish)

Next open up you web.config file and in the configuration section add the following:
  1. <connectionStrings>  
  2.     <add name="SimpleBlog" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\SimpleBlog.mdf;Initial Catalog=SimpleBlog;Integrated Security=True" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
Now we need to create the schema. To do this we will right click on our database from within the Sql Server Object Explorer window and select New Query in which we will add the following line of T-Sql Code:

CREATE SCHEMA [Blog]

Run the query and you will have created a new schema.

Now we need to create our tables. There are 2 ways you could do this within Visual Studio. You could use the visual designer or you could write the T-Sql code yourself. Either option is fine, I personally am going to write the T-Sql code.

To create the post table I used the following T-Sql script:
  1. CREATE TABLE [Blog].[Posts]  
  2. (  
  3. [PostId] INT NOT NULL PRIMARY KEY IDENTITY,   
  4. [PostTitle] VARCHAR(200) NOT NULL,   
  5. [DatePosted] DATE NOT NULL,   
  6. [DateEdited] DATE NULL,   
  7. [PostContent] NVARCHAR(MAXNOT NULL,   
  8. [PostAuthor] VARCHAR(150) NOT NULL  
  9. )  
To create the Comments table I have used the following script:
  1. CREATE TABLE [Blog].[Comments]  
  2. (  
  3. [CommentId] INT NOT NULL PRIMARY KEY IDENTITY,   
  4. [PostId] INT NOT NULL,   
  5. [NameVARCHAR(150) NOT NULL,   
  6. [CommentDate] DATE NOT NULL,   
  7. [Comment] NVARCHAR(MAXNOT NULL,   
  8. CONSTRAINT [FK_Comments_Blog] FOREIGN KEY ([PostId]) REFERENCES [Blog].[Posts]([PostId])   
  9. )  
Our next step is to write some stored procedures to add / display posts and comments.

Add the following stored procedures to your database:
  1. CREATE PROCEDURE [Blog].[addPost]  
  2. @pTitle varchar(200),  
  3. @pContent nvarchar(max),  
  4. @pAuthor varchar(150)  
  5. AS  
  6. BEGIN  
  7. INSERT INTO Blog.Posts(PostTitle, DatePosted, PostContent, PostAuthor)  
  8. VALUES (@pTitle, GETDATE(), @pContent, @pAuthor)  
  9. END  
  10.   
  11.   
  12. CREATE PROCEDURE [Blog].[displayPosts]  
  13. AS  
  14. BEGIN  
  15. SELECT PostTitle, PostId  
  16. FROM Blog.Posts  
  17. END  
  18.   
  19. CREATE PROCEDURE [Blog].[displayPost]  
  20. @postId int  
  21. AS  
  22. BEGIN  
  23. SELECT PostTitle, PostAuthor, DatePosted, PostContent  
  24. FROM Blog.Posts  
  25. WHERE PostId = @postId  
  26. END  
  27.   
  28. CREATE PROCEDURE [Blog].[addComment]  
  29. @postId int,  
  30. @cName varchar(150),  
  31. @comment nvarchar(max)  
  32. AS  
  33. BEGIN  
  34. INSERT INTO Blog.Comments(PostId, Name, CommentDate, Comment)  
  35. VALUES(@postId, @cName, GETDATE(), @comment)  
  36. END  
  37.   
  38. CREATE PROCEDURE [Blog].[displayComments]  
  39. @PostId int  
  40. AS  
  41. BEGIN  
  42. SELECT Name, CommentDate, Comment  
  43. FROM Blog.Comments  
  44. WHERE PostId = @PostId  
  45. END  
Now we have created our insert and display stored procedures for the Posts and Comments tables we need to write some C# code. We will be creating two class files. One for displaying and adding blog posts and one for displaying and adding comments.
We will start with the blog posts class file.

First go to Website > Add New Item (or Ctrl + Shift + A). When the Add New Item window appears select Class from the list, give it a name (I have called mine BlogPosts.cs) and click add. You will get an alert box appear which will say that files of this type are normally stored in the App_Code folder and it will ask if you wish to create an App_Code folder and add your file to it. Click yes.

Now you will be presented with an empty class file. Remove all code from the page and add the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.Sql;  
  7. using System.Data.SqlClient;  
  8. using System.Data.SqlTypes;  
  9. using System.Web.Configuration;  
  10.   
  11. /// <summary>  
  12. /// This class will be responsible for calling the Stored Procedures   
  13. /// </summary>  
  14. public class BlogPosts   
  15. {  
  16.     private static string connectionString =  
  17.         WebConfigurationManager.ConnectionStrings["SimpleBlog"].ConnectionString;  
  18.   
  19.     public static DataSet getPosts()  
  20.     {  
  21.         DataSet ds = new DataSet();  
  22.         SqlConnection con = new SqlConnection(connectionString);  
  23.         SqlCommand cmd = new SqlCommand("Blog.displayPosts", con);  
  24.         SqlDataAdapter adp = new SqlDataAdapter(cmd);  
  25.         cmd.CommandType = CommandType.StoredProcedure;  
  26.         try {  
  27.             con.Open();  
  28.             adp.Fill(ds, "Posts");  
  29.         } catch (Exception er) {  
  30.             Console.WriteLine(er.Message);  
  31.         } finally {  
  32.             con.Close();  
  33.         }  
  34.   
  35.   
  36.         return ds;  
  37.     }  
  38.     public static DataSet getPost(int postident) {  
  39.         DataSet ds = new DataSet();  
  40.         SqlConnection con = new SqlConnection(connectionString);  
  41.         SqlCommand cmd = new SqlCommand("Blog.displayPost", con);  
  42.         SqlDataAdapter adp = new SqlDataAdapter(cmd);  
  43.         cmd.CommandType = CommandType.StoredProcedure;  
  44.         cmd.Parameters.Add(new SqlParameter("@postId", SqlDbType.Int));  
  45.         cmd.Parameters["@postId"].Value = postident;  
  46.         try {  
  47.             con.Open();  
  48.             adp.Fill(ds, "Post");  
  49.         } catch (Exception er) {  
  50.             Console.WriteLine(er.Message);  
  51.         } finally {  
  52.             con.Close();  
  53.         }  
  54.   
  55.   
  56.         return ds;  
  57.     }  
  58.   
  59.   
  60.     public static void addPost(string title, string cont, string auth) {  
  61.         SqlConnection con = new SqlConnection(connectionString);  
  62.         SqlCommand cmd = new SqlCommand("Blog.addPost", con);  
  63.         cmd.CommandType = CommandType.StoredProcedure;  
  64.         cmd.Parameters.Add(new SqlParameter("@pTitle", SqlDbType.VarChar, 200));  
  65.         cmd.Parameters["@pTitle"].Value = title;  
  66.         cmd.Parameters.Add(new SqlParameter("@pContent", SqlDbType.NVarChar, -1));  
  67.         cmd.Parameters["@pContent"].Value = cont;  
  68.         cmd.Parameters.Add(new SqlParameter("@pAuthor", SqlDbType.VarChar, 150));  
  69.         cmd.Parameters["@pAuthor"].Value = auth;  
  70.         int added = 0;  
  71.         try {  
  72.             con.Open();  
  73.             added = cmd.ExecuteNonQuery();  
  74.         } catch (Exception ex) {  
  75.             Console.WriteLine(ex.Message);  
  76.         } finally {  
  77.             con.Close();  
  78.         }  
  79.     }  
  80. }  
Now we need to create two webforms. One to display blog posts and one to add them.

So go toWebsite > Add New Item (or Ctrl + Shift + A). From the list select webform. Give it a name then click add. Do this twice, once for adding posts(which I have named addPost.aspx) and once more for displaying the posts(this one I called displayPosts.aspx).

Go to your addPost.aspx file and open it up. On your page add the following mark-up:
  1. <form id="form1" runat="server">  
  2.     <div>  
  3.         <h1>Add Post</h1>  
  4.         <label>Title</label>  
  5.         <asp:TextBox ID="txtTitle" runat="server" TextMode="SingleLine"></asp:TextBox><br />  
  6.         <label>Author</label>  
  7.         <asp:TextBox ID="txtAuth" runat="server" TextMode="SingleLine"></asp:TextBox><br />  
  8.         <label>Post Content</label>  
  9.         <asp:TextBox ID="txtCont" runat="server" TextMode="MultiLine"></asp:TextBox><br />  
  10.         <asp:Button ID="btnAdd" runat="server" Text="Add Post!" OnClick="btnAdd_Click" />  
  11.     </div>  
  12. </form>  
We have added text boxes for the post title, the post author and the post itself. We also added a button. Now we need to go to the code behind file and locate the click event of our button. Inside that event add the following line of code:

BlogPosts.addPost(txtTitle.Text, txtCont.Text, txtAuth.Text);

Once you have done that run the page(press f5) and fill in the form with some data. After clicking add go back into visual studio and check the database table to see if the data you just entered on the page is present in the table (Go to Sql Server Explorer, locate the Posts table and right cluck on it. You will be presented with a menu full of possible options you will need to select View Data which will bring up all the data in that table.) If your data is present then what we have created so far has worked. Yay!

Now we need to go to the displayPosts.aspx file and open it up. (Note: For the sake of simplicity I am going to use an asp:FormView control to display the data but that is by no means the only or even the best way to display the data. Your decision on which data control to use depends entirely on your circumstances and requirements.) On your displayPosts page add the following markup:
  1. <div>  
  2.     <h1>Display the posts.</h1>  
  3.     <asp:DropDownList ID="drpPosts" runat="server"></asp:DropDownList><br />  
  4.     <asp:Button ID="btnDisplay" runat="server" Text="Display Post" OnClick="btnDisplay_Click" />  
  5.     <asp:FormView ID="frmPosts" runat="server">  
  6.         <ItemTemplate>  
  7.             <asp:Label ID="lblTitle" runat="server" Text='<%# Eval("PostTitle") %>'></asp:Label><br />  
  8.             <asp:Label ID="DatePosted" runat="server" Text='<%# Eval("DatePosted") %>'></asp:Label><br />  
  9.             <asp:Label ID="lblAuth" runat="server" Text='<%# Eval("PostAuthor") %>'></asp:Label><br />  
  10.             <asp:Label ID="lblCont" runat="server" Text='<%# Eval("PostContent") %>'></asp:Label><br />  
  11.         </ItemTemplate>  
  12.     </asp:FormView>  
  13. </div>  
Now we need to go to the code behind and add in the following code:
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     DataSet ds = BlogPosts.getPosts();  
  4.     drpPosts.DataSource = ds;  
  5.     drpPosts.DataTextField = ds.Tables[0].Columns["PostTitle"].ToString();  
  6.     drpPosts.DataValueField = ds.Tables[0].Columns["PostId"].ToString();  
  7.     drpPosts.DataBind();  
  8. }  
  9. protected void btnDisplay_Click(object sender, EventArgs e)   
  10. {  
  11.     DataSet dat = BlogPosts.getPost(Convert.ToInt32(drpPosts.SelectedValue));  
  12.     frmPosts.DataSource = dat;  
  13.     frmPosts.DataBind();  
  14.   
  15. }  
Don’t forget to add this using statement to the top of the code behind:

using System.Data;

Run your page and try it out. If you followed the steps correctly you will be able to select a post from the drop down list which will then display the post underneath it.

Now we have built that part of our blogging platform we can move onto the comments part. There is nothing difficult or complex about what we are about to do, in fact it’s not all that different to what we have just done.

So, our first step is to create a class file which will be responsible for calling the relevant stored procedures that we created earlier. I have named mine Comments.cs As before this file belongs in the App_Code folder.

In your comments.cs file add the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.Sql;  
  7. using System.Data.SqlClient;  
  8. using System.Data.SqlTypes;  
  9. using System.Web.Configuration;  
  10.   
  11. /// <summary>  
  12. /// This class will be responsible for calling the Stored Procedures  
  13. /// </summary>  
  14. public class Comments  
  15. {  
  16.     private static string connectionString =  
  17.         WebConfigurationManager.ConnectionStrings["SimpleBlog"].ConnectionString;  
  18.   
  19.     public static DataSet GetComments(int post)  
  20.     {  
  21.         SqlConnection con = new SqlConnection(connectionString);  
  22.         SqlCommand cmd = new SqlCommand("Blog.displayComments", con);  
  23.         cmd.CommandType = CommandType.StoredProcedure;  
  24.         SqlDataAdapter adp = new SqlDataAdapter(cmd);  
  25.         cmd.Parameters.Add(new SqlParameter("@PostId", SqlDbType.Int));  
  26.         cmd.Parameters["@PostId"].Value = post;  
  27.   
  28.         DataSet dSet = new DataSet();  
  29.         try {  
  30.             con.Open();  
  31.             adp.Fill(dSet, "Comments");  
  32.         } catch (Exception er) {  
  33.             Console.WriteLine(er.Message);  
  34.         } finally {  
  35.             con.Close();  
  36.         }  
  37.         return dSet;  
  38.     }  
  39.   
  40.     public static void addComment(int post, string name, string com)  
  41.     {  
  42.         SqlConnection con = new SqlConnection(connectionString);  
  43.         SqlCommand cmd = new SqlCommand("Blog.addComment", con);  
  44.         cmd.CommandType = CommandType.StoredProcedure;  
  45.   
  46.         cmd.Parameters.Add(new SqlParameter("@postId", SqlDbType.Int));  
  47.         cmd.Parameters["@postId"].Value = post;  
  48.         cmd.Parameters.Add(new SqlParameter("@cName", SqlDbType.VarChar, 150));  
  49.         cmd.Parameters["@cName"].Value = name;  
  50.         cmd.Parameters.Add(new SqlParameter("@comment", SqlDbType.NVarChar, -1));  
  51.         cmd.Parameters["@comment"].Value = com;  
  52.   
  53.         int added = 0;  
  54.         try  
  55.         {  
  56.             con.Open();  
  57.             added = cmd.ExecuteNonQuery();  
  58.         } catch (Exception er) {  
  59.             Console.WriteLine(er.Message);  
  60.         } finally {  
  61.             con.Close();  
  62.         }  
  63.     }  
  64. }  
Now head over to your displayPosts.aspx page and underneath your formview add the following mark-up:
  1. <div>  
  2.     <h1>Comments</h1>  
  3.     <div style="width:50%; float:left;">  
  4.         <h3>Add a comment</h3>  
  5.         <label>Name:</label><br />  
  6.         <asp:TextBox ID="txtName" runat="server" TextMode="SingleLine"></asp:TextBox><br />  
  7.         <label>Comment:</label>  
  8.         <asp:TextBox ID="txtComm" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox> <br />  
  9.         <asp:Button ID="btnAddComm" runat="server" Text="Add Comment!" OnClick="btnAddComm_Click" />  
  10.     </div>  
  11.     <div style="width:50%;float:left;">  
  12.         <asp:Repeater ID="rptComments" runat="server">  
  13.             <ItemTemplate>  
  14.                 <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>  
  15.                 <asp:Label ID="lblDateCom" runat="server" Text='<%# Eval("CommentDate") %>'></asp:Label>  
  16.                 <br />  
  17.                 <asp:Label ID="lblComm" runat="server" Text='<%# Eval("Comment") %>'></asp:Label>  
  18.                 <hr />  
  19.             </ItemTemplate>  
  20.         </asp:Repeater>  
  21.     </div>  
  22. </div>  
Then go into your code behind and add the following code:
  1. protected void getcomms()  
  2. {  
  3.     DataSet ds = Comments.GetComments(Convert.ToInt32(drpPosts.SelectedValue));  
  4.     rptComments.DataSource = ds;  
  5.     rptComments.DataBind();  
  6. }  
  7. protected void btnAddComm_Click(object sender, EventArgs e)   
  8. {  
  9.     Comments.addComment(Convert.ToInt32(drpPosts.SelectedValue), txtName.Text, txtComm.Text);  
  10.     getcomms();  
  11. }  
In your btnDisplay_Click event, after all the code we wrote previously add this line:

getcomms();

And that’s all there is to it. We have not built a very basic blogging system that you can incorporate into your ASP.NET web application.

As promised way back in the beginning of this article I have a few suggestions to further improve your brand new blogging system; you could incorporate ASP.NET Identity to allow more users to add posts. You could create a table and the accompanying code to put your posts into categories. Also you could create facilities to update and delete posts and comments. That’s just a few ideas to get you going but the sky is the limit. Just make sure you don’t set yourself too big a task at once, chop them up into smaller more manageable goals.

I hope you found this article informative and helpful. If you have suggestions for improvements I would love to hear them.
 
Read more articles on ASP.NET:


Similar Articles