65.9K
CodeProject 正在变化。 阅读更多。
Home

为您的网站添加一个易于使用的博客引擎:使用 UnRio.dll 第三部分

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3投票s)

2016 年 1 月 24 日

CPOL

8分钟阅读

viewsIcon

11562

downloadIcon

252

本文扩展了我之前写的两篇文章,演示如何使用 ASP.NET MVC 编写自己的博客引擎。

引言

您可以在我之前写的两篇文章中找到如何使用 ASP.NET MVC(和 Visual Studio 2013 或 2015)创建博客引擎的详细步骤,链接如下:

本文将指导您完成如何使用 `UnRio` 库(我们在第二部分中构建的)的步骤,以便您可以将其添加到您当前运行的 ASP.NET MVC 网站中。

背景

市面上很少有预先构建的、易于使用的库可以“直接添加到您的网站中,帮助您为现有网站添加博客页面”。`UnRio` 库和本文中的步骤正是为了帮助您实现这一点。

为了让您了解使用该库有多么简单,我将快速列出步骤。 

步骤概述

一次性步骤

要开始使用 `UnRio` 库,您需要

  1. 将 _UnRio.dll_ 放入您的 _bin_ 目录(在您的网站下)
  2. 在您的 _global.asax.cs_ 文件中,添加一个 `static` 对 `UnRio.Models.BlogArticleRepository` 的引用
  3. 在您的网站中添加一个文件夹,用于存放您的 _<blog>.dat_* 文件和 _<yourArticle>.htm_ 文件。
  4. 在您的 ASP.NET 网站中添加一个 `<Blog>Controller`,它将提供一种初始化博客的一些基本值的方式
  5. 添加一个链接或菜单项,以便用户可以访问您的 `<Blog>Controller`
  6. 添加一个匹配的 `<Blog> View`,它将渲染您的可点击文章列表,并将每个 _*.htm_ 文件的视图加载到视图区域,以便用户可以阅读您的文章。
  7. 创建您的 _<blog>.dat_ 文件,并将其放入您的 _<blog>_ 文件夹
  8. 创建您的 ** _*.htm_ 文章文件,并将它们放入您的 _<blog>_ 文件夹

*我用尖括号 <> 标记了所有这些项目,因为这些值不是硬编码的,您可以在您的网站中任意命名。您只需要将信息提供给 `UnRio` 库。

重复步骤

在创建您的博客后,之后任何时候,您要添加新文章只需要:

  1. 编辑您的 _<blog>.dat_ 文件,添加一个新的文章条目(放在文件顶部)
  2. 创建您的新 _*.htm_ 文件,代表您的新文章。
  3. 使用浏览器访问 _http://<yoursite.com>/blog?forceReload=true_ 来从磁盘重新加载 _<blog.dat>_,以便新文章能够加载到 `static`(内存中)的应用程序变量 `BlogArticleRepository` 中,供所有访问者使用。(注意:如果应用程序重启,它也会重新加载列表。)

本文的其余部分将指导您完成在您的网站上实现此功能的实际步骤。

Using the Code

要求

如果您已经拥有一个 ASP.NET 网站,那么您可以通过简单地将 _UnRio.dll_ 放入您网站的 _bin_ 目录来使用 _UnRio.dll_。但是,如果您的网站不是 ASP.NET 驱动的网站,`UnRio` 很可能无法正常加载。

将 UnRio.dll 放入 Bin

获取 `UnRio` 源代码(本文附带下载)并使用 Visual Studio Community 2013 或 2015 构建它,或者下载二进制文件(本文也附带下载)。

将其放入您的 ASP.NET MVC _bin_ 目录。如果您是在 Visual Studio 中添加代码,那么您应该添加一个对 _UnRio.dll_ 的引用。(右键单击 References...Add... 等)。

加载 UnRio

要加载 `UnRio` 库非常容易。编辑您网站的 _global.asax.cs_ 文件,并添加一个 `using` 语句,以便您可以轻松地引用 `UnRio` 的功能。

using UnRio.Models;

之后,转到您 _global.asax.cs_ 文件中的 `Application_Start()` 方法,并添加一个新的 `static` 路径变量(您可以根据您的博客命名),并添加一个新的 `static` `BlogArticleRepository`。

在我写这篇文章时,我正在为我的网站(http://raddev.us)添加一个 techBlog,在 Visual Studio 中添加这些项目时,它看起来是这样的。

adding BlogArticleRepository

我将在下面的代码片段中添加代码,但我认为之前的图像很有帮助,因为它显示了我们需要的唯一两个东西,并且显示了智能感知,这样我们就可以讨论传递给 `BlogArticleRepository` 的**参数**。

您实际上不需要创建 `static rootPath` 变量。您也可以像下面这样,直接用字符串字面量实例化 `BlogArticleRepository`。

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

第一个参数:博客文件夹

第一个参数就是您将存储 _<blog>.dat_ 文件和 _*.htm_ 文件的**文件夹的绝对路径**。它可以是您喜欢的任何位置,只要它在您的网站之下(这是 IIS / Web 服务器的限制),因为您的 Web 服务器必须能够提供这些文件。

第二个参数:<blog>.dat

第二个参数也可以按您喜欢的方式命名。但是,我建议您给它一个 _ .dat_ 扩展名。为什么?因为默认情况下,ASP.NET 网站会保护该文件,即使有人知道了文件的路径,也不会允许任何人直接访问它。这实际上并没有什么区别,因为它只是一个管道分隔的文本文件,但收紧安全始终是最好的做法。

我将我的命名为与我正在称之为我的技术博客的这个特定博客匹配(_techBlog.dat_)。

使用 UnRio 运行多个博客?

现在您已经看到创建 `BlogArticleRepository` 有多容易,我想明确说明,您**可以通过 UnRio 提供多个博客存储库**。要做到这一点,您只需在您的 _global.asax.cs_ 文件中实例化多个 `BlogArticleRepository` 变量。

您的 _global.asax.cs_ 代码将如下所示:

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");
        }
    }
}

文件夹和文件至关重要

如果您在创建文件夹或 _ .dat_ 文件之前尝试运行应用程序,那么您的网站将崩溃,因为 ASP.NET 在尝试加载 _<blog>.dat_ 文件时会抛出异常。

这是因为当您实例化 `BlogArticleRepository` 并传入文件夹和文件时,它会尝试从磁盘读取 _<blog>.dat_ 文件但找不到它,因此会抛出异常。

错误将如下所示:

app crash

应用程序崩溃是因为 `UnRio` 库调用了以下代码,该代码尝试访问一个不存在的文件和/或文件夹。

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();

粗体显示的行是应用程序崩溃的地方,因为它无法读取无法访问的文件。我们可以将其包装在 `try...catch` 中,但这被认为是 `UnRio` 中的一个关键错误,您应该被通知某些地方出了严重问题。但是,如果您希望您的网站显示一个更干净的错误页面,您可以获取源代码并轻松地进行更改。

将您的 <Blog> 文件夹添加到您的网站

您可以直接在您的实际网站上或在 ASP.NET MVC 项目中执行此操作。只需确保 Web 服务器允许用户从该目录读取。

为了保持整洁,我添加了一个名为 _techBlog_ 的文件夹,以匹配我的其他项目。

添加您的 <Blog> Controller

这些步骤与我们在本文第二部分遵循的步骤相同,但我将在此处再次展示它们,以保持本文的流畅性。

添加一个具有读/写操作的新 Controller。

add controller

我将其命名为 `TechBlogContoller` 以匹配我的所有项目,并再次保持整洁。

techblog controller

当您单击 [添加] 按钮时,Visual Studio 将打开新的 Controller 文件并显示代码。

转到 `Index()` 操作并进行修改,使其看起来像下面的代码。

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();
        }

在代码示例中,我粗体显示了您需要确保进行更改以匹配您的值的两个项目。

现在,让我们添加视图,这样我们就完成了。

添加视图以显示文章列表和文章

如果您在添加新视图方面需要任何帮助,请参阅**第二部分的相应章节**。

请记住将视图命名为 Index(默认文档路由),并将其放在您的 **_Views<BlogName>_ 文件夹中**。Visual Studio 在您在上一步中添加 Controller 时创建了该文件夹。

add view

在您单击 [添加] 按钮后,Visual Studio 将在编辑模式下打开 _index.cshtml_ 文件。

用下面的代码替换该文件中的所有代码。

<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="//#/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>

同样,我粗体显示了您需要更改的两个项目。

一旦您添加了 _<blog>.dat_ 文件和 _*.htm_ 文件,这个功能就可以在您的网站上运行了。

添加 <blog>.dat

创建一个 _<blog>.dat_ 文件,并将其保存到您的 _<blog>_ 文件夹中。

您的 _ .dat_ 文件必须遵循以下格式。

  1. 管道分隔
  2. 包含五个字段(`int`、`string`、`string`、`string`、`date`)

示例 _<blog>.dat_

2|Visual Studio's Greatest Hits|Visual Studio|VisStudio1.htm|2015-04-02
1|TITLE|CATEGORY|Article.htm|publicationDate

最重要的一点是为您提供每个字段代表的内容。但是,**该行不是有效条目**,因为 `publicationDate` 将无法解析为 `Date` 类型。

您可以复制它并将其用作模板来创建您自己的文件。

一旦创建了 _<blog>.dat_ 文件,您就拥有了所需的一切。

创建您的单独 HTML 文章(命名方式与您的 _<blog>.dat_ 条目行相匹配),您就可以开始了。

您的文章将显示出来,并在单击标题(左侧)时加载。

CSS 样式

对于样式,您可以在主 CSS 文件中使用以下内容。

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;
}

它看起来会与以下内容类似。

final product

就这样。希望这能帮助您极快地创建和更新您网站上的内容。

历史

  • 2015-01-24:本文初版
© . All rights reserved.