Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Creating a “customizable” personal blog using ASP.NET

0.00/5 (No votes)
15 Dec 2015 1  
This is part 1 of the articles that I want to write for ASP.NET beginners, who want to build their own personal web sites, that mimic characteristics of blog. It covers the ASP.NET web application part.

Introduction and Background

I don’t want to speak too much in this piece of article, instead I just want to demonstrate the presentation that I have to make today. This article is a short piece of “long report” that can be considered as an answer to most common question, “How to create a blog in ASP.NET?”

Well, I find it most compelling that most people are unaware of what a blog itself is, because if they knew they could just play around with ASP.NET to build one for themselves in a night or two. In this article I will discuss a few steps that are needed to be followed while creating your own blog. I am not a good designer, so please forgive the most annoying design that you are going to witness in coming sections. But I promise I will give you an overview of a “blog in ASP.NET”. The facts that I will talk about, or the reason that you should read this article is that this article is not a “specific” how to for my own procedures. Instead, I am writing this article to give you a brief overview of what a blog is, what ASP.NET has in it for you, how you can create it and not just that, but also, how you can create a blog with all that you have. In most cases, you just have a small area for hosting with less HDD space and no database. I will cover what to do in such cases too. Just read the post.

To add some “content” I wrote a Windows 10 client application to consume the blog posts through ASP.NET Web API. I am sure in most cases this Web API thing for ASP.NET blog posts would interest you.

What is a blog, anyways?

Putting the content here simple, a blog is a place where you can share, what you want, anytime you want, with anyone you want! That is a general type of blog being used. Blog is a short form for weblog (logging, makes sense?). More specific types of blogs come depending on your content. Some of blog categories are as below:

  1. Microblogs
    Compact and straight-forward blogs. 140 characters beast, Twitter, is an example of this type.
  2. Personal blogs
    Anyone can create them and they are very much personal, demonstrating only one person. Your website can be your personal blog.
  3. Media blogs
    You can share the images, videos and other multi-media content in media blogs.

So basically a blog is just a website for sharing the content. If you ever created an online website for sharing the content, current work information, regular “diary”, then you have already worked on developing a personal blog. Blog is just a term given to online log system, where you can “log” your regular discussion topics.

So, in this article post I am going to cover a basic application that can act as a blog for someone. As an additional support I will also give you an idea of using ASP.NET’s Web API to promote your blog on native applications, such as a native Windows 10 application that loads the content from your only blog and display the blog posts to users natively.

Getting started with ASP.NET

Since most of the readers are currently not upgrading themselves to ASP.NET MVC 6, I will use ASP.NET MVC 5 (not ASP.NET 5) to show you how to do it. Things are very much similar in ASP.NET MVC 5 and ASP.NET MVC 6. The common things that I have found to change in the coming versions is that ASP.NET is now cross-platform, so if you continue to write the same application by following my article, in ASP.NET MVC 6, you will be able to run it on a server in Ubuntu, or Mac and so on. But that is not a big deal here, is it?

I will be using ASP.NET MVC 5 (not ASP.NET 5!) to demonstrate how to build your own ASP.NET personal blog. But before I get Visual Studio started, I wanted to explain the term “customizable”, which is used in the title of my current article. By the term “customizable” I mean

  1. A blog that is entirely flexible. You can integrate plugins, or update the theme and so on.
  2. A blog that doesn’t rely on a specific third-party framework, even a data source.
  3. A blog that is built just on top of ASP.NET assemblies and doesn’t require you to do anything at all.
  4. A general blogging platform, which can be then altered to create
    1. Social blogging service.
    2. Personal CV house
    3. Your own website to demonstrate your services
    4. So on and so forth.

In simple, the blog can be altered to your own needs and requirements. After all an ASP.NET blog is just an ASP.NET web application that you have modified to suit your own needs.

At this stage I would ask you to create a new ASP.NET project in your own machine, in the next section I will continue with the next things, like create controllers, defining the Views and so on. So, it would be good for you to create a new project at this moment and continue with the article next.

Building the application

First of all, I would like to share how I actually built the ASP.NET web application to be able to host my blog. I am going to use a web interface and an API interface, to be able to consume the blog from multiple native applications. So, I will talk about the ASP.NET programming in this section and then I will talk about the Windows 10 application programming, to actually consume the blog posts and show it to the users in a “native experience”.

Web interface controller

First of all, I will consider building the web interface to be able to showcase the blog on the internet, using a browser. This is what ASP.NET was initially developed for. To build web sites, and web applications. Web applications were introduced a bit later and then was introduced the Web API and so on. So, I am going to use the very basic concepts of ASP.NET MVC to build a simple web application, that can “act” as a blog.

If you are novice to ASP.NET, because most of the times the question (in the title) is asked by a beginner in ASP.NET, so if you have no idea about ASP.NET, please read the previous posts of mine that cover ASP.NET in a great detail and would help you in understanding and learning every bit of ASP.NET programming, as from a beginner’s perspective.

  1. Understanding ASP.NET MVC using real world example, for beginners and intermediate
  2. Novice to MVC? Read this… (ASP.NET MVC is implementation of MVC pattern of software development, this post talks about MVC not ASP.NET MVC)

I will continue to share more of my articles and posts, as the topic proceeds. I would recommend that you read the above posts if you are new to ASP.NET, most of the concepts like Controller, Views and Models may cause a confusion to you, if you are a newbie!

Almost there…

I am very much fan of JSON data, I prefer using JSON over SQL databases and thus I am a fan of Newtonsoft.Json library. So, please consider installing the library before moving further. This library would be the backbone for our data source.

PM> Install-Package Newtonsoft.Json -Version 7.0.1

Once this package gets installed, please continue to the next section.

1. Build the model for application

In my case, I always prefer building the models first. This gives me an idea of building the controllers and then building the views for the application. So, I would also give you a tip, to always build the models, data structures first and then continue to build the rest of the stuff.

The model we need is just a model for the blog post. So, the structure would just be as easy as the following,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Newtonsoft.Json;

namespace PersonalBlogTemplateWithServices.Models
{
     public class BlogPostModel
     {
         // General properties
         public int ID { get; set; }
         public string Title { get; set; }
         public string Content { get; set; }
         public List<string> Tags { get; set; }

         // Time based properties
         public DateTime CreateTime { get; set; }

         // Other properties and settings may include UserID, RoleID etc.
      }
 
      // The class to manage the data-sources
      public class PostManager
      {
          // Define the members
          private static string PostsFile = HttpContext.Current.Server.MapPath("~/App_Data/Posts.json");
          private static List<BlogPostModel> posts = new List<BlogPostModel>();

          // The CRUD functions
          public static void Create(string postJson)
          {
              var obj = JsonConvert.DeserializeObject<BlogPostModel>(postJson);

              if(posts.Count > 0)
              {
                  posts = (from post in posts
                           orderby post.CreateTime
                           select post).ToList();
                  obj.ID = posts.Last().ID + 1;
              } else
              {
                  obj.ID = 1;
              }
          }

          posts.Add(obj);
          save();
      }

      public static List<BlogPostModel> Read()
      {
          // Check if the file exists.
          if(!File.Exists(PostsFile))
          {
              File.Create(PostsFile).Close();
              File.WriteAllText(PostsFile, "[]"); // Create the file if it doesn't exist.
          }
          posts = JsonConvert.DeserializeObject<List<BlogPostModel>>(File.ReadAllText(PostsFile));
          return posts;
      }

      public static void Update(int id, string postJson)
      {
          Delete(id);
          Create(postJson);
          save();
      }

      public static void Delete(int id)
      {
          posts.Remove(posts.Find(x => x.ID == id));
          save();
      }

      // Output function
      private static void save()
      {
          File.WriteAllText(PostsFile, JsonConvert.SerializeObject(posts));
       }
    }
}

In the model , I have the following attributes that can be used to identify or describe the blog post at the instance.

  1. ID
  2. Title
  3. Content
  4. Tags (is an array; List)
  5. CreateTime (used to sort the items)

Great, we now have a model, and now we can continue to write the rest of the logic for our application. The model implements the CRUD functions, that we can call from external objects, from both, web interface and from Web API interface. This would allow us to manage the data layer in this class.

2. Creating the controller

Alright, first of all, create the controller. The controller would have the actions that we need to perform in our blog. Please pay attention to the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using PersonalBlogTemplateWithServices.Models;
using Newtonsoft.Json;

namespace PersonalBlogTemplateWithServices.Controllers
{
    public class BlogController : Controller
    {
        // GET: Blog
        public ActionResult Index()
        {
            // Read the list
            var blogs = PostManager.Read();
            if (blogs == null)
            {
                 ViewBag.Empty = true;
                 return View();
            }
            else
            {
                 // Just for sorting.
                 blogs = (from blog in blogs
                          orderby blog.CreateTime descending
                          select blog).ToList();

                 ViewBag.Empty = false;
                 return View(blogs);
            }
        }
 
        [Route("blog/read/{id}")] // Set the ID parameter
        public ActionResult Read(int id)
        {
            // Read one single blog
            var blogs = PostManager.Read();
            BlogPostModel post = null;
 
            if(blogs != null && blogs.Count > 0)
            {
                post = blogs.Find(x => x.ID == id);
            }

            if(post == null)
            {
                ViewBag.PostFound = false;
                return View();
            } else
            {
                ViewBag.PostFound = true;
                return View(post);
            }
        }

        public ActionResult Create()
        {
            if (Request.HttpMethod == "POST")
            {
                 // Post request method
                 var title = Request.Form["title"].ToString();
                 var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                 var content = Request.Form["content"].ToString();

                 // Save content
                 var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
                 PostManager.Create(JsonConvert.SerializeObject(post));

                 // Redirect
                 Response.Redirect("~/blog");
            }
            return View();
        }

        [Route("blog/edit/{id}")]
        public ActionResult Edit(int id)
        {
             if(Request.HttpMethod == "POST")
             {
                 // Post request method
                 var title = Request.Form["title"].ToString();
                 var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                 var content = Request.Form["content"].ToString();

                 // Save content
                 var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
                 PostManager.Update(id, JsonConvert.SerializeObject(post));

                 // Redirect
                 Response.Redirect("~/blog");
             } else
             {
                 // Find the required post.
                 var post = PostManager.Read().Find(x => x.ID == id);

                 if (post != null)
                 {
                     // Set the values
                     ViewBag.Found = true;
                     ViewBag.PostTitle = post.Title;
                     ViewBag.Tags = post.Tags;
                     ViewBag.Content = post.Content;
                 }
                 else
                 {
                     ViewBag.Found = false;
                 }
             }

             // Finally return the view.
             return View();
        }
    }
}

The above code, is enough! This code contains the code that you may be needing. Now, I think I need to explain the code a bit.

I have implemented the CRUD functions, in this manner, I created the functions that would allow me to create a new post, read the list of posts, read a single post at the web page or perform other functions, like update the post. You can also see, that most of the codes and functions are being called from the model. That is why, I designed the model before I created the controller. I think now you understand the importance of a model before controller.

The controller would simply capture the request, extract the data from it and then pass the data and request over to the Model. The model would then perform as per our request and return a response, which can then be sent back to the client. The purpose of such a design, is to create a web application being consumed over by Web API too. In the later sections I will consider sharing that too.

Until now, the web application is able to show us messages on the blog. If we have created a post, it will show us the post otherwise it will show us a message that there is no post currently available.

3. Creating the views

Views are simple enough to be understood easily! If you have been developing using HTML, I won’t explain them. If you haven’t, go learn! Smile | :)

Default page…

The default page for the blog would be simple one, it would either enlist the blog posts otherwise show a message.

For this page, I would instead show the HTML code, and for the rest of the pages I will show the images, because I want to demonstrate how to use the actions.

@model List<PersonalBlogTemplateWithServices.Models.BlogPostModel>
@{
    ViewBag.Title = "My Blog";
}

@if(ViewBag.Message != null)
{
    <h4>@ViewBag.Message</h4>

The page uses the conditional values from the controller. You may have noticed the value from Controller, which is passed as a model (of type of the BlogPostModel). I have checked against that, to see if there are any posts in the data source. That is pretty much simple and straight-forward. The main thing to see, if what happens if there is a new post in the data source. Consider the next section, please!

Creating the post

When you create a new post, you follow the hyperlink, which takes you to a page where you have created a form and so on. I am not much a designer-type, so the UI is very ugly. You can make it better if you want to.

The view for “C” in “CRUD, is something like this.

@{
    ViewBag.Title = "New Post";
}

<h2>Create new blog post</h2>

<form method="post">
    <label>Title</label>
    <input type="text" name="title" style="" class="form-control" placeholder="The headline goes here..." /><br />
    <label>Tags</label>
    <input type="text" name="tags" style="" class="form-control" placeholder="Separate each tag using a comma ','." /><br />
    <label>Content</label>
    <textarea name="content" class="form-control" style="height: 300px;" placeholder="What would you like to write?"></textarea><br />
    <input type="submit" style="width: auto; font-weight: 600;" value="Post" /><br />
</form>

Very simple though, yet powerful! Power is in your hands. Add some, or leave it if you do not want to share the admin panel with anyone. Smile | :) Once this page gets loaded, it takes the following web page shape.

Screenshot (219)
Figure 1: Create a new blog post page. Form is filled.

The above HTML takes this shape. The HTML looks clean because of hard work of

  1. ASP.NET team for providing a template.
  2. Bootstrap guys, Twitter bootstrap is being used here (is provided along with ASP.NET template)

You can now submit the post. Alright, until now things are pretty neat and simple. Do you have any questions? Please re-read this section. Smile | :)

Reviewing the default page now

If you go back to the default page now, you will see that the blog would now enlist the posts (currently only 1). The following is the image, you already have the HTML for this page.

Screenshot (220)
Figure 2: Default page showing one blog in the list. 

Now the page is able to demonstrate that we have a post, it displays the tags and name. Nothing else. After all, why would we show anything else on the default page?

Reading the blog posts, one by one

If you could read the HTML for the default page, you will see that the title of the blog post is actually a URL to the blog post, to be read. I have created the action for that (please read the controller code for Read action). This would let us now read the content,

Screenshot (221).png
Figure 3: Reading the post, shows date time, content and tags. 

This is how I display the content. I agree, a very bad design. But I am very bad at designing the web applications. (I know, my first attempt went wrong because IDs were null and… Ah, you get it the second time, didn’t time? Quit whining!)

I used the following HTML code for this, the thing was that I just wanted to display the blog post, in a very simple way. Indeed in your case, you will write something much more useful. But, at the moment, just read this.

@model PersonalBlogTemplateWithServices.Models.BlogPostModel
@{
    ViewBag.Title = Model.Title;
    var tagIndex = 1;
}

<h4 style="font-weight: bold;">@Model.Title</h4>

<p>@Html.Raw(Model.Content.Replace("\r\n", "<br />"))</p>
<p>Posted by &mdash; Afzaal Ahmad Zeeshan &mdash; on @Model.CreateTime.ToString("MMMM dd, yyyy 'at' hh:mm tt")</p>
<p>
    Tagged under:
    @foreach (var tag in Model.Tags)
    {
        <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>
        if (tagIndex == Model.Tags.Count)
        {
            // In the end, write the edit hyperlink
            <span><a href="~/blog/edit/@Model.ID">Edit</a></span>
        }

        // Finally increment the index
        tagIndex++;
    }
</p>

So, this code would give us the post. I have many things hardcoded, like, “Posted by &mdash; Afzaal Ahmad Zeeshan &mdash; on {Date Time}”. You can change it, to see who is the author and so on. There are many other things to be taken care of.

One thing to understand is that your HTML is not the same that gets saved in the data source. So, you might need to re-consider the HTML, then render it using Html.Raw function. Have a look at the following code, for example,

<p>@Html.Raw(Model.Content.Replace("\r\n", "<br />"))</p>

Now, each of the occurrence of “\r\n” would be replaced with the breakline object in HTML. This way, you can re-build the HTML and show it as plain text on the HTML web page.

Updating the posts

The final concept that I will be talking about here would be of updating the posts. Updating is similar to creating the new post, but just that you also provide the previous data that you are having. Title, content and other stuff can be provided and then user is allowed to update them as required and then you save it back to the data source.

I have used the same HTML form in this case,

@{
 ViewBag.Title = "Edit the post";

 var tags = string.Join(", ", ViewBag.Tags as List<string>);
}

<h2>Edit the post</h2>

<form method="post">
    <label>Title</label>
    <input type="text" name="title" style="" class="form-control" value="@ViewBag.PostTitle" placeholder="The headline goes here..." /><br />
    <label>Tags</label>
    <input type="text" name="tags" style="" class="form-control" value="@tags" placeholder="Separate each tag using a comma ','." /><br />
    <label>Content</label>
    <textarea name="content" class="form-control" style="height: 300px;" placeholder="What would you like to write?">@ViewBag.Content</textarea><br />
    <input type="submit" style="width: auto; font-weight: 600;" value="Post" /><br />
</form>

This is similar to what we had previously. But it renders along with the previous data we had.

Screenshot (222)
Figure 4: HTML page showing the form to edit the previously updated post.

As you can see, the post contains the previous data, but also allows me to update the post. This is useful, in cases when you want to update the post. I am adding a new paragraph line, which would then be rendered as it is being written.

Tip: This is not WYSIWYG editor, just a plain-textarea. You should get a WYSIWYG editor if you want to be able to use the full power of HTML in your post.

Now, once I will submit this, it would get published as this version. Please revise the controller action,

if(Request.HttpMethod == "POST")
{
    // Post request method
    var title = Request.Form["title"].ToString();
    var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    var content = Request.Form["content"].ToString();

    // Save content
    var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
    PostManager.Update(id, JsonConvert.SerializeObject(post));

    // Redirect
    Response.Redirect("~/blog");
 }

This demonstrates, how you will update the post. Once again, we are using PostManager, the object we created in our model to be able to perform the actions. The post is now updated, have a look at the revisit to the post preview. Screenshot (223).png
Figure 5: Updated post preview.

This now shows the updates being made. It is also clear as to how the new line is added to the post. Pretty simple it was, but I wanted to demonstrate the concept of this too.

Adding new posts

One more thing is, to add new posts. This is same, requires just a view. I am about to give you an overview of adding new posts, multiple posts and how does this preview them on the default page.

Screenshot (224).png
Figure 6: Creating a new blog post, second one.

This is similar, the only thing to understand is how is it rendered on the blog.

Screenshot (225).png
Figure 7: Two posts being previewed.

The thing that I wanted to share here, is that ASP.NET won’t automatically sort the posts, you would have to do that yourself. If you pay attention to the LINQ code, you will understand it.

// Just for sorting.
blogs = (from blog in blogs
         orderby blog.CreateTime descending
         select blog).ToList();

This would now sort the blogs, a descending order. That is why, “Two posts” shows above, whereas in the JSON data it would come after the “First blog post!” But we have now sorted the list as per our requirements.

Heading over to Windows 10 application and Web API

Before I actually head over, I want to make a final post, that would be read in the application! Please see the following image, then we continue to the next section.

Screenshot (226).png
Figure 8: Final post online.

Web interface has been discussed enough, the next sections will talk about the Web API and Windows 10 application programming.

Further reading:

If you want to get more in-depth information, please read the following documents and articles.

  1. A tip for ajax developers in ASP.NET MVC framework
  2. Getting Started with LINQ in C#

Web API and Windows 10 client application

In this section, I will first talk about the ASP.NET Web API and then I will build the application to consume the API and show the blogs. In the client application, we do not need any functions, like create, update etc. We just consume and display the data, so the client application won’t have enough functions but it would display the content.

Building the API

Actually, the API is simple and does not need anything to be done! The application has already been completed, so our API would only redirect to the application and load the data from the model and return it. API does not need to have any HTML data or CSS stylesheets, instead API just returns the data in JSON or XML format. I personally recommend and always will recommend using JSON. XML is a very heavy format and is also not efficient. JSON is much simple, lightweight and portable format!

The API is just a controller, with the same actions that we need and a return-type. Since we do not need any functions but C (from CRUD), I defined the API to be as simple as,

using Newtonsoft.Json;
using PersonalBlogTemplateWithServices.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace PersonalBlogTemplateWithServices.Controllers
{
    public class BlogApiController : ApiController
    {
        // In this controller, we just need the Read functions. Nothing else!
        // We do not need the clients to be able to write or update the blogs... Just read them

        [HttpGet]
        [Route("blog/api")]
        public List<BlogPostModel> Get()
        {
            return PostManager.Read();
        }
    }
}

Small, but enough.This would let us consume the API from our client application. There is also no need to edit the API configuration, because I have provided the Routing scheme to the function.

[Route("blog/api")]

This would automatically get routed to this URL. The rest of the functionality is to be provided by the application.

One thing to note, is that this function again, reads the data from the model and returns is, as a collection. This would then be translated as JSON data later. So our application will be able to use the JSON converters to get the data from the API and render it on the application.

I hope things for API are clear upto this stage! If not, please re-read. I think the post is pretty much simple. Smile | :)

Building the client application; Windows 10 application

Great, until now you have learnt how to build the online blog, that has a web interface and an API interface. I will continue with the next post, to teach you how to consume the API, the post has gone way more than I was expecting (it overwent 4k words).

Read the above article and leave your feedback, I would love to hear it!

Points of interest

Thank you for reading the post, I have shared a common, yet easy and simple way to build your own blog. The post contains the information that you may need to have to create your own online personal blog. I have not shared any third-party library because I want you to be able to add your own. The blog is built on top of native ASP.NET frameworks.

In a later post, I will also share the common concepts for building the data sources, so that the only dependency of “Newtonsoft.Json” would also be removed from this project. Until then, please bear with me.

One more thing, the text editor used is plain-textarea, you can replace it with your favorite WYSIWYG editor to be able to use the power of HTML, then render the HTML on the screen.

In coming days, I will write two more posts:

  1. Consuming the Web API from Windows 10 application.
  2. Building your own custom data sources.

Stay tuned for more of such content! Smile | :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here