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

Adding an Easy-to-use Blog Engine to your Web: Using UnRio.dll Part 3

0.00/5 (No votes)
24 Jan 2016 1  
This article extends the 2-part article I wrote showing you how to write your own blog engine in ASP.NET MVC.

Introduction

You can read the first two parts of this article series where I walk you through creating the blog engine using ASP.NET MVC (and Visual Studio 2013 or 2015) at:

This article will walk you through the steps of how to use the UnRio library (which we built in Part 2) so you can add it to your currently running ASP.NET MVC web site.

Background

There are not many pre-built, easy-to-use libraries which you can drop into your web site that will help you add a blog page to your existing site. That's what the UnRio library and the steps in this article will help you do.

To get an idea of how easy it is to use the library, I'll give you the quick list of steps.  

Overview of Steps

One-Time Steps

To begin using the UnRio library, you will:

  1. Drop the UnRio.dll into your bin directory (under your web site)
  2. Add a static reference to the UnRio.Models.BlogArticleRepository to your global.asax.cs
  3. Add a folder to your web site which will hold your <blog>.dat* file and <yourArticle>.htm files.
  4. Add a <Blog>Controller to your ASP.NET web site which will provide a way to initialize some basic values for your blog
  5. Add a link or menu item so users can access your <Blog>Controller
  6. Add a matching <Blog> View which will render your clickable article list and load the view of each *.htm into the view area so users can read your articles.
  7. Create your <blog>.dat file and drop into your <blog> folder
  8. Create your *.htm article files and drop them into your <blog> folder

*I mark all of these items in beaks <> because the values are not hard-coded, they can be any name you want them to be in your web site. You just have to provide the information to the UnRio library.

Repeated Steps

After you've created your blog, then any time after that, all you have to do to add a new article is:

  1. Edit your <blog>.dat file to add a new article entry (at the top of the file)
  2. Create your new *.htm file which represents your new article.
  3. Use your browser to call http://<yoursite.com>/blog?forceReload=true to reload <blog.dat> from disk so the new article will be loaded into the static (in memory) application variable BlogArticleRepository so it is available to all visitors. (NOTE: If the application restarts, it will also reload the list.)

The rest of this article will walk you through the actual steps to get this working on your web site.

Using the Code

Requirements

If you already have an ASP.NET site, then you can use the UnRio.dll by simply dropping it into your site's bin directory. However, if your site is not an ASP.NET powered site, UnRio is most likely not going to load properly.

Drop UnRio.dll Into Bin

Get the UnRio source (included for download with this article) and build it using Visual Studio Community 2013 or 2015 or download the binary (also included with this article).

Drop it into your ASP.NET MVC bin directory. If you're adding the code in Visual Studio, then you should add a reference to UnRio.dll. (Right-click References...Add... etc).

Load UnRio

It's very easy to get the UnRio library to load. Edit your site's global.asax.cs and add a using statement which will allow you to easily reference the UnRio functionality.

using UnRio.Models;

After that, go to the Application_Start() method of your global.asax.cs and add a new static path variable (name it after your blog if you like) and add a new static BlogArticleRepository.

I'm doing this work to add a techBlog to my website (http://raddev.us) as I write this article and it looks like the following in Visual Studio as I add these items:

adding BlogArticleRepository

I'll add the code below in a snippet, but I think that the previous image is helpful because it shows the only two things we need and shows the Intellisense so we can talk about the parameters sent into the BlogArticleRepository.

You do not actually have to create the static rootPath variable. You could just new up the BlogArticleRepository with a string literal like the following:

techBlog = new BlogArticleRepository(@"c:\path\morepath\techBlog\", "techBlog.dat");

First Parameter: Blog Folder

The first parameter is simply the absolute path to the folder where you will store your <blog>.dat file and your *.htm files. It can be wherever you like, as long as it is under your web site (this is a limitation of IIS / web servers) since your web server has to be able to serve the files.

Second Parameter: <blog>.dat

The second parameter can also be named whatever you like. However, I suggest you name it with a .dat extension. Why? Because by default an ASP.NET web site will protect that file and not allow anyone to access it directly even if they find out the path to the file. It wouldn't really matter because it is just a pipe-delimited text file, but it is always best to tighten down security as much as possible.

I've named mine to match this specific blog which I'm calling my tech blog (techBlog.dat).

Multiple Blogs with UnRio?

Now that you see how easy it is to create a BlogArticleRepository, I want to explicitly state that you can have multiple blog repositories served up by UnRio. To do that, you simply new up multiple BlogArticleRepository variables in your global.asax.cs.

Your global.asax.cs code would simply look something like the following:

using UnRio.Models;

namespace raddev
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static string techBlogPath = @"C:\dev\WebDev\raddev\raddev\techBlog";
        private static BlogArticleRepository techBlog;

        private static string patternsBlogPath = @"C:\dev\WebDev\raddev\raddev\patternsBlog";
        private static BlogArticleRepository patternsBlog;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            techBlog = new BlogArticleRepository(techBlogPath, "techBlog.dat");
            patternsBlog = new BlogArticleRepository(patternsBlogPath, "patternsBlog.dat");
        }
    }
}

Folders and Files Are Critical

If you try to run the application before creating the folder or the .dat file, then your site will crash as ASP.NET attempts to load the <blog>.dat file and throws an exception.

That's because when you new up the BlogArticleRepository sending in the folder and file, it attempts to read the <blog>.dat from disk and doesn't find it, so it throws an exception.

The error will look something like the following:

app crash

The app crashes because the UnRio library calls the following code which attempts to access a file and/or folder which doesn't exist:

private void LoadBlogArticlesFromDataStore()
        {
            string[] allLines = File.ReadAllLines(Path.Combine(RootPath,blogFile)); 
            foreach (string line in allLines)
            {
                try
                {
                    string[] allItems = line.Split('|');

                    BlogArticle ba = new BlogArticle();

The bolded line is where the app crashes, since it cannot read from a file it cannot access. We could wrap that in atry...catch but this is considered a critical error in UnRio and you should be notified that something is critically wrong. However, if you want your site to display a cleaner error page, you can get the source and change it with ease.

Add Your <Blog>Folder To Your Site

You can do this at your actual web site or in the ASP.NET MVC project. Just make sure that the web server allows users to read from that directory.

I'm adding a folder named techBlog to match my other items to keep things organized.

Add Your <Blog>Controller

These steps are just like the ones we followed in Part 2 of this article series but I will show them here also to keep the flow of this article.

Add a new Controller with read/write actions.

add controller

I named mine TechBlogContoller to match all my items and again keep organized:

techblog controller

When you click the [Add] button, Visual Studio will open the new controller file and display the code.

Go to the Index() action and alter it so it looks like the code in the following:

public ActionResult Index(int? articleId, bool? forceReload)
        {
            MvcApplication.mainBlog.GetAllBlogArticles(forceReload);
            ViewBag.Articles = (List<UnRio.Models.BlogArticle>)MvcApplication.techBlog;
            // WARNING!!! Insure that ViewBag.BlogPath terminates with a slash /
            ViewBag.BlogPath = "../techBlog/";
            if (articleId != null)
            {
                ViewBag.currentArticle = articleId;
            }
            return View();
        }

In the code sample, I've bolded the items you will need to ensure are changed to match your values.

Now, let's add the view and we're done.

Add View To Display Article List & Articles

If you need any help with adding a new View, please see the appropriate sections of Part 2.

Remember to name the View Index (default document route) and put it in your \Views\<BlogName> folder. Visual Studio created that folder when you added the controller in the previous step.

add view

After you click the [Add] button, Visual Studio will open the index.cshtml file in edit mode.

Replace ALL of the code found in that file with the following:

<div class="minus-container">
    @{
        ViewBag.Title = "RAD Dev US - Blog";
        Layout = "~/Views/Shared/_Layout.cshtml";
        ViewBag.selectedItem = "techblog";
    }
    <script>
  (function () {
    $(".pubDate").remove();
    $(".article").remove();

  }());
    </script>
    <div class="row">

        <h3 class="tight col-sm-3">
            Articles
            <span>
                <a href="fakePathToRSS.xml">
                    <img src="../images/rssfeedicon.jpg" 
                    width="16" height="16" />
                </a>
            </span>
        </h3>

        <div class="tight col-sm-3">
        (most recent article is loaded - click title to load others)</div>
        <div class="tight col-sm-3">
            <script async 
            src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <!-- blogtop -->
            <ins class="adsbygoogle"
                 style="display:inline-block;width:320px;height:100px"
                 data-ad-client="ca-pub-6286879032545261"
                 data-ad-slot="6030258726"></ins>
            <script>
    (adsbygoogle = window.adsbygoogle || []).push({});
            </script>
        </div>
    </div>
    <p>
        <div class="row">
            <div class="leftcolumn col-sm-3 ">
                @{
                    foreach (var item in ViewBag.Articles)
                    {

                        <span class="pubDate">Published: 
                        @item.Created.ToString("yyyy-MM-dd")</span>
            <p class="article list-unstyled" id="article_id_@item.Id" 
            onmousedown="showPreview('@ViewBag.BlogPath@item.RelativeFilePath',
            'article_id_@item.Id')">
                @item.Title
            </p>

                    }
                    if (ViewBag.currentArticle != null)
                    {
                        List<UnRio.Models.BlogArticle> localArticles = 
                        (List<UnRio.Models.BlogArticle>)ViewBag.Articles;
                        ViewBag.currentArticle = localArticles.Find(x => x.Id == ViewBag.currentArticle);
                        if (ViewBag.currentArticle == null)
                        {
                            // the id for the article wasn't valid so load the default;
                            ViewBag.currentArticle = @ViewBag.Articles[0];
                        }
                    }
                    else
                    {
                        ViewBag.currentArticle = @ViewBag.Articles[0];
                    }
                }
            </div>

            <div class="rightcolumn col-sm-9"></div>

            <script>
    (function () {
        
        showPreview('@ViewBag.BlogPath@ViewBag.currentArticle.RelativeFilePath');
    setSelectedArticle(@ViewBag.currentArticle.Id);
    }());

  function showPreview(article,element) {
    $('.rightcolumn').load(article);
    if (element != null) {
      $(".article").css("background-color", "");
      $("#" + element).css("background-color", "lightgrey");
    }
  }
  function setSelectedArticle(articleId) {
    $("#" + "article_id_" + 
    articleId).css("background-color", "lightgrey");
  }
</script>

Again, I have bolded the two items you need to change.

Once you add your <blog>.dat file and your *.htm files, this thing will work on your site.

Add <blog>.dat

Create a <blog>.dat file and save it into your <blog> folder.

Your .dat file must follow the following format.

  1. pipe-delimited
  2. contains five fields (int, string, string, string, date)

Sample <blog>.dat:

2|Visual Studio's Greatest Hits|Visual Studio|VisStudio1.htm|2015-04-02
<span style="font-size: 9pt;">1|TITLE|CATEGORY|Article.htm|publicationDate</span>

The bottom line is just providing you with what each field represents. However, that line is not a valid entry because publicationDate will fail to parse to a Date type.

You copy it and use it as a template to create your own file.

Once you create the <blog>.dat file, you have everything you need.

Create your individual HTML articles (named after your <blog>.dat entry lines) and you are ready to go.

Your articles will appear and will load when the title is clicked (on the left).

CSS Styling

For styles, you can use the following in your main CSS file.

input,
select,
textarea {
    max-width: 280px;
}

.article:hover{
    background-color:#efae14;
    font-weight:bold;
}
.article{
    font-size:large;
}

.pageSection {
    margin-left:0px;
    padding-left: 0px;
    padding-right: 0px;
     margin: 0px ;
     background-color:aliceblue;
}
.leftcolumn, .rightcolumn {
    border: 1px solid white;
    float: left;
    min-height: 25%;
    color: black;
}

.leftcolumn {
    margin: 0;
    padding: 0;
    border: 0;
    cursor: pointer;
        /*background-color: #111;*/
}

.rightcolumn {
/*        width: 75%;*/
        background-color: lightyellow;
        
}

.tight{
    margin-top:20px;
    padding:0px;
}

h3 .tight{
    display: inline-block;
    padding:-5px;
    padding-top:8px;

}
.pubDate{
    font-size:x-small;
    
}

.minus-container{
    margin: 0;
    padding: 0;
    border: 0;
}

.leftPad{
    margin-left:20px;
}

It will look similar to the following:

final product

That's it. Hope this helps you create and update content on your site extremely fast.

History

  • 2015-01-24: First version of this article

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