Highlighter Tutorial¶

|Simple sample|https://github.com/odinserj/Hangfire.Highlighter
|Full sample|http://highlighter.hangfire.io, sources

Table of Contents

Overview¶

Consider you are building a code snippet gallery web application like GitHub Gists, and want to implement the syntax highlighting feature. To improve user experience, you also want it to work even if a user has disabled JavaScript in her browser.

To support this scenario and to reduce the project development time, you chosen to use a web service for syntax highlighting, such as http://pygments.org/ or http://www.hilite.me.

Note

Although this feature can be implemented without web services (using different syntax highlighter libraries for .NET), we are using them just to show some pitfalls regarding to their usage in web applications.

You can substitute this example with real-world scenario, like using external SMTP server, another services or even long-running CPU-intensive task.

Setting up the project¶

Tip

This section contains steps to prepare the project. However, if you don’t want to do the boring stuff or if you have problems with project set-up, you can download the tutorial source code and go straight to The problem section.

Prerequisites¶

The tutorial uses Visual Studio 2012 with Web Tools 2013 for Visual Studio 2012 installed, but it can be built either with Visual Studio 2013.

The project uses .NET 4.5, ASP.NET MVC 5 and SQL Server 2008 Express or later database.

Creating a project¶

Let’s start from scratch. Create an ASP.NET MVC 5 Empty Project and name this awesome web application Hangfire.Highlighter (you can name it as you want, but prepare to change namespaces).

I’ve included some screenshots to make the project set-up not so boring:
../_images/newproj.png
Then, we need a controller to handle web requests. So scaffold an MVC 5 Controller - Empty controller and call it HomeController:
../_images/addcontrollername.png
Our controller contains now only Index action and looks like:

  1. public class HomeController : Controller
  2. {
  3. public ActionResult Index()
  4. {
  5. return View();
  6. }
  7. }

We have a controller with a single action. To test that our application is working, scaffold an empty view for Index action.
../_images/addview.png
The view scaffolding process also adds additional components to the project, like Bootstrap, jQuery, etc. After these steps my solution looks like:
../_images/solutionafterview.png
Let’s test the initial setup of our application. Press the F5 key to start debugging and wait for your browser. If you encounter exceptions or don’t see the default page, try to reproduce all the given steps, see the tutorial sources or ask a question in the comments below.

Defining a model¶

We should use a persistent storage to preserve snippets after application restarts. So, we’ll use SQL Server 2008 Express (or later) as a relational storage, and Entity Framework to access the data of our application.

Installing Entity Framework¶

Open the Package Manager Console window and type:

  1. Install-Package EntityFramework

After the package installed, create a new class in the Models folder and name it HighlighterDbContext:

  1. // ~/Models/HighlighterDbContext.cs
  2.  
  3. using System.Data.Entity;
  4.  
  5. namespace Hangfire.Highlighter.Models
  6. {
  7. public class HighlighterDbContext : DbContext
  8. {
  9. public HighlighterDbContext() : base("HighlighterDb")
  10. {
  11. }
  12. }
  13. }

Please note, that we are using undefined yet connection string name HighlighterDb. So, lets add it to the web.config file just after the </configSections> tag:

  1. <connectionStrings>
  2. <add name="HighlighterDb" connectionString="Server=.\sqlexpress; Database=Hangfire.Highlighter; Trusted_Connection=True;" providerName="System.Data.SqlClient" />
  3. </connectionStrings>

Then enable Entity Framework Code First Migrations by typing in your Package Manager Console window the following command:

  1. Enable-Migrations
Adding code snippet model¶

It’s time to add the most valuable class in the application. Create the CodeSnippet class in the Models folder with the following code:

  1. // ~/Models/CodeSnippet.cs
  2.  
  3. using System;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Web.Mvc;
  6.  
  7. namespace Hangfire.Highlighter.Models
  8. {
  9. public class CodeSnippet
  10. {
  11. public int Id { get; set; }
  12.  
  13. [Required, AllowHtml, Display(Name = "C# source")]
  14. public string SourceCode { get; set; }
  15. public string HighlightedCode { get; set; }
  16.  
  17. public DateTime CreatedAt { get; set; }
  18. public DateTime? HighlightedAt { get; set; }
  19. }
  20. }

Don’t forget to include the following property in the HighlighterDbContext class:

  1. // ~/Models/HighlighterDbContext.cs
  2. public DbSet<CodeSnippet> CodeSnippets { get; set; }

Then add a database migration and run it by typing the following commands into the Package Manager Console window:

  1. Add-Migration AddCodeSnippet
  2. Update-Database

Our database is ready to use!

Creating actions and views¶

Now its time to breathe life into our project. Please, modify the following files as described.

  1. // ~/Controllers/HomeController.cs
  2.  
  3. using System;
  4. using System.Linq;
  5. using System.Web.Mvc;
  6. using Hangfire.Highlighter.Models;
  7.  
  8. namespace Hangfire.Highlighter.Controllers
  9. {
  10. public class HomeController : Controller
  11. {
  12. private readonly HighlighterDbContext _db = new HighlighterDbContext();
  13.  
  14. public ActionResult Index()
  15. {
  16. return View(_db.CodeSnippets.ToList());
  17. }
  18.  
  19. public ActionResult Details(int id)
  20. {
  21. var snippet = _db.CodeSnippets.Find(id);
  22. return View(snippet);
  23. }
  24.  
  25. public ActionResult Create()
  26. {
  27. return View();
  28. }
  29.  
  30. [HttpPost]
  31. public ActionResult Create([Bind(Include="SourceCode")] CodeSnippet snippet)
  32. {
  33. if (ModelState.IsValid)
  34. {
  35. snippet.CreatedAt = DateTime.UtcNow;
  36.  
  37. // We'll add the highlighting a bit later.
  38.  
  39. _db.CodeSnippets.Add(snippet);
  40. _db.SaveChanges();
  41.  
  42. return RedirectToAction("Details", new { id = snippet.Id });
  43. }
  44.  
  45. return View(snippet);
  46. }
  47.  
  48. protected override void Dispose(bool disposing)
  49. {
  50. if (disposing)
  51. {
  52. _db.Dispose();
  53. }
  54. base.Dispose(disposing);
  55. }
  56. }
  57. }

  1. @ ~/Views/Home/Index.cshtml @

  2. @model IEnumerable<Hangfire.Highlighter.Models.CodeSnippet>
    @{ ViewBag.Title = "Snippets"; }

  3. <h2>Snippets</h2>

  4. <p><a class="btn btn-primary" href="@Url.Action("Create")">Create Snippet</a></p>
    <table class="table">
    <tr>
    <th>Code</th>
    <th>Created At</th>
    <th>Highlighted At</th>
    </tr>

  5. @foreach (var item in Model)
  6. {
  7.     &lt;tr&gt;
  8.         &lt;td&gt;
  9.             &lt;a href=&#34;@Url.Action(&#34;Details&#34;, new { id = item.Id })&#34;&gt;@Html.Raw(item.HighlightedCode)&lt;/a&gt;
  10.         &lt;/td&gt;
  11.         &lt;td&gt;@item.CreatedAt&lt;/td&gt;
  12.         &lt;td&gt;@item.HighlightedAt&lt;/td&gt;
  13.     &lt;/tr&gt;
  14.  }
  15. </table>

  1. @ ~/Views/Home/Create.cshtml @

  2. @model Hangfire.Highlighter.Models.CodeSnippet
    @{ ViewBag.Title = "Create a snippet"; }

  3. <h2>Create a snippet</h2>

  4. @using (Html.BeginForm())
    {
    @Html.ValidationSummary(true)

  5. &lt;div class=&#34;form-group&#34;&gt;
  6.     @Html.LabelFor(model =&gt; model.SourceCode)
  7.     @Html.ValidationMessageFor(model =&gt; model.SourceCode)
  8.     @Html.TextAreaFor(model =&gt; model.SourceCode, new { @class = &#34;form-control&#34;, style = &#34;min-height: 300px;&#34;, autofocus = &#34;true&#34; })
  9. &lt;/div&gt;
  10. &lt;button type=&#34;submit&#34; class=&#34;btn btn-primary&#34;&gt;Create&lt;/button&gt;
  11. &lt;a class=&#34;btn btn-default&#34; href=&#34;@Url.Action(&#34;Index&#34;)&#34;&gt;Back to List&lt;/a&gt;
  12. }

  1. @ ~/Views/Home/Details.cshtml @

  2. @model Hangfire.Highlighter.Models.CodeSnippet
    @{ ViewBag.Title = "Details"; }

  3. <h2>Snippet <small>#@Model.Id</small></h2>

  4. <div>
    <dl class="dl-horizontal">
    <dt>@Html.DisplayNameFor(model => model.CreatedAt)</dt>
    <dd>@Html.DisplayFor(model => model.CreatedAt)</dd>
    <dt>@Html.DisplayNameFor(model => model.HighlightedAt)</dt>
    <dd>@Html.DisplayFor(model => model.HighlightedAt)</dd>
    </dl>

  5. &lt;div class=&#34;clearfix&#34;&gt;&lt;/div&gt;
  6. </div>

  7. <div>@Html.Raw(Model.HighlightedCode)</div>

Adding MiniProfiler¶

To not to profile our application by eye, we’ll use the MiniProfiler package available on NuGet.

  1. Install-Package MiniProfiler

After installing, update the following files as described to enable profiling.

  1. // ~/Global.asax.cs
  2.  
  3. public class MvcApplication : HttpApplication
  4. {
  5. /* ... */
  6.  
  7. protected void Application_BeginRequest()
  8. {
  9. StackExchange.Profiling.MiniProfiler.Start();
  10. }
  11.  
  12. protected void Application_EndRequest()
  13. {
  14. StackExchange.Profiling.MiniProfiler.Stop();
  15. }
  16. }

  1. @ ~/Views/Shared/_Layout.cshtml @

  2. <head>
    <!— —>
    @StackExchange.Profiling.MiniProfiler.RenderIncludes()
    </head>

You should also include the following setting to the web.config file, if the runAllManagedModulesForAllRequests is set to false in your application (it is by default):

  1. <!-- ~/web.config -->
  2.  
  3. <configuration>
  4. ...
  5. <system.webServer>
  6. ...
  7. <handlers>
  8. <add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
  9. </handlers>
  10. </system.webServer>
  11. </configuration>

Hiliting the code¶

It is the core functionality of our application. We’ll use the http://hilite.me service that provides HTTP API to perform highlighting work. To start to consume its API, install the Microsoft.Net.Http package:

  1. Install-Package Microsoft.Net.Http

This library provides simple asynchronous API for sending HTTP requests and receiving HTTP responses. So, let’s use it to make an HTTP request to the hilite.me service:

  1. // ~/Controllers/HomeController.cs
  2.  
  3. /* ... */
  4.  
  5. public class HomeController
  6. {
  7. /* ... */
  8.  
  9. private static async Task<string> HighlightSourceAsync(string source)
  10. {
  11. using (var client = new HttpClient())
  12. {
  13. var response = await client.PostAsync(
  14. @"http://hilite.me/api",
  15. new FormUrlEncodedContent(new Dictionary<string, string>
  16. {
  17. { "lexer", "c#" },
  18. { "style", "vs" },
  19. { "code", source }
  20. }));
  21.  
  22. response.EnsureSuccessStatusCode();
  23.  
  24. return await response.Content.ReadAsStringAsync();
  25. }
  26. }
  27.  
  28. private static string HighlightSource(string source)
  29. {
  30. // Microsoft.Net.Http does not provide synchronous API,
  31. // so we are using wrapper to perform a sync call.
  32. return RunSync(() => HighlightSourceAsync(source));
  33. }
  34.  
  35. private static TResult RunSync<TResult>(Func<Task<TResult>> func)
  36. {
  37. return Task.Run<Task<TResult>>(func).Unwrap().GetAwaiter().GetResult();
  38. }
  39. }

Then, call it inside the HomeController.Create method.

  1. // ~/Controllers/HomeController.cs
  2.  
  3. [HttpPost]
  4. public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
  5. {
  6. try
  7. {
  8. if (ModelState.IsValid)
  9. {
  10. snippet.CreatedAt = DateTime.UtcNow;
  11.  
  12. using (StackExchange.Profiling.MiniProfiler.StepStatic("Service call"))
  13. {
  14. snippet.HighlightedCode = HighlightSource(snippet.SourceCode);
  15. snippet.HighlightedAt = DateTime.UtcNow;
  16. }
  17.  
  18. _db.CodeSnippets.Add(snippet);
  19. _db.SaveChanges();
  20.  
  21. return RedirectToAction("Details", new { id = snippet.Id });
  22. }
  23. }
  24. catch (HttpRequestException)
  25. {
  26. ModelState.AddModelError("", "Highlighting service returned error. Try again later.");
  27. }
  28.  
  29. return View(snippet);
  30. }

Note

We are using synchronous controller action method, although it is recommended to use asynchronous one to make network calls inside ASP.NET request handling logic. As written in the given article, asynchronous actions greatly increase application capacity, but does not help to increase performance. You can test it by yourself with a sample application – there are no differences in using sync or async actions with a single request.

This sample is aimed to show you the problems related to application performance. And sync actions are used only to keep the tutorial simple.

The problem¶

Tip

You can use the hosted sample to see what’s going on.

Now, when the application is ready, try to create some code snippets, starting from a smaller ones. Do you notice a small delay after you clicked the Create button?

On my development machine it took about 0.5s to redirect me to the details page. But let’s look at MiniProfiler to see what is the cause of this delay:
../_images/smcodeprof.png
As we see, call to web service is our main problem. But what happens when we try to create a medium code block?
../_images/mdcodeprof.png
And finally a large one:
../_images/lgcodeprof.png
The lag is increasing when we enlarge our code snippets. Moreover, consider that syntax highlighting web service (that is not under your control) experiences heavy load, or there are latency problems with network on their side. Or consider heavy CPU-intensive task instead of web service call that you can not optimize well.

Your users will be annoyed with un-responsive application and inadequate delays.

Solving a problem¶

What can you do with a such problem? Async controller actions will not help, as I said earlier. You should somehow take out web service call and process it outside of a request, in the background. Here is some ways to do this:

  • Use recurring tasks and scan un-highlighted snippets on some interval.
  • Use job queues. Your application will enqueue a job, and some external worker threads will listen this queue for new jobs.
    Ok, great. But there are several difficulties related to these techniques. The former requires us to set some check interval. Shorter interval can abuse our database, longer interval increases latency.

The latter way solves this problem, but brings another ones. Should the queue be persistent? How many workers do you need? How to coordinate them? Where should they work, inside of ASP.NET application or outside, in Windows Service? The last question is the sore spot of long-running requests processing in ASP.NET application:

Warning

DO NOT run long-running processes inside of your ASP.NET application, unless they are prepared to die at any instruction and there is mechanism that can re-run them.

They will be simple aborted on application shutdown, and can be aborted even if the IRegisteredObject interface is used due to time out.

Too many questions? Relax, you can use Hangfire. It is based on persistent queues to survive on application restarts, uses reliable fetching to handle unexpected thread aborts and contains coordination logic to allow multiple worker threads. And it is simple enough to use it.

Note

YOU CAN process your long-running jobs with Hangfire inside ASP.NET application – aborted jobs will be restarted automatically.

Installing Hangfire¶

To install Hangfire, run the following command in the Package Manager Console window:

  1. Install-Package Hangfire

After the package installed, add or update the OWIN Startup class with the following lines of code.

  1. public void Configuration(IAppBuilder app)
  2. {
  3. GlobalConfiguration.Configuration.UseSqlServerStorage("HighlighterDb");
  4.  
  5. app.UseHangfireDashboard();
  6. app.UseHangfireServer();
  7. }

That’s all. All database tables will be created automatically on first start-up.

Moving to background¶

First, we need to define our background job method that will be called when worker thread catches highlighting job. We’ll simply define it as a static method inside the HomeController class with the snippetId parameter.

  1. // ~/Controllers/HomeController.cs
  2.  
  3. /* ... Action methods ... */
  4.  
  5. // Process a job
  6. public static void HighlightSnippet(int snippetId)
  7. {
  8. using (var db = new HighlighterDbContext())
  9. {
  10. var snippet = db.CodeSnippets.Find(snippetId);
  11. if (snippet == null) return;
  12.  
  13. snippet.HighlightedCode = HighlightSource(snippet.SourceCode);
  14. snippet.HighlightedAt = DateTime.UtcNow;
  15.  
  16. db.SaveChanges();
  17. }
  18. }

Note that it is simple method that does not contain any Hangfire-related functionality. It creates a new instance of the HighlighterDbContext class, looks for the desired snippet and makes a call to a web service.

Then, we need to place the invocation of this method on a queue. So, let’s modify the Create action:

  1. // ~/Controllers/HomeController.cs
  2.  
  3. [HttpPost]
  4. public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
  5. {
  6. if (ModelState.IsValid)
  7. {
  8. snippet.CreatedAt = DateTime.UtcNow;
  9.  
  10. _db.CodeSnippets.Add(snippet);
  11. _db.SaveChanges();
  12.  
  13. using (StackExchange.Profiling.MiniProfiler.StepStatic("Job enqueue"))
  14. {
  15. // Enqueue a job
  16. BackgroundJob.Enqueue(() => HighlightSnippet(snippet.Id));
  17. }
  18.  
  19. return RedirectToAction("Details", new { id = snippet.Id });
  20. }
  21.  
  22. return View(snippet);
  23. }

That’s all. Try to create some snippets and see the timings (don’t worry if you see an empty page, I’ll cover it a bit later):
Highlighter Tutorial - 图8
Good, 6ms vs ~2s. But there is another problem. Did you notice that sometimes you are redirected to the page with no source code at all? This happens because our view contains the following line:

  1. <div>@Html.Raw(Model.HighlightedCode)</div>

Why the Model.HighlightedCode returns null instead of highlighted code? This happens because of latency of the background job invocation – there is some delay before a worker fetch the job and perform it. You can refresh the page and the highlighted code will appear on your screen.

But empty page can confuse a user. What to do? First, you should take this specific into a place. You can reduce the latency to a minimum, but you can not avoid it. So, your application should deal with this specific issue.

In our example, we’ll simply show the notification to a user and the un-highlighted code, if highlighted one is not available yet:

  1. @ ~/Views/Home/Details.cshtml @

  2. <div>
    @if (Model.HighlightedCode == null)
    {
    <div class="alert alert-info">
    <h4>Highlighted code is not available yet.</h4>
    <p>Don't worry, it will be highlighted even in case of a disaster
    (if we implement failover strategies for our job storage).</p>
    <p><a href="javascript:window.location.reload()">Reload the page</a>
    manually to ensure your code is highlighted.</p>
    </div>

  3.     @Model.SourceCode
  4. }
  5. else
  6. {
  7.     @Html.Raw(Model.HighlightedCode)
  8. }
  9. </div>

But instead you could poll your application from a page using AJAX until it returns highlighted code:

  1. // ~/Controllers/HomeController.cs
  2.  
  3. public ActionResult HighlightedCode(int snippetId)
  4. {
  5. var snippet = _db.Snippets.Find(snippetId);
  6. if (snippet.HighlightedCode == null)
  7. {
  8. return new HttpStatusCodeResult(HttpStatusCode.NoContent);
  9. }
  10.  
  11. return Content(snippet.HighlightedCode);
  12. }

Or you can also use send a command to users via SignalR channel from your HighlightSnippet method. But that’s another story.

Note

Please, note that user still waits until its source code will be highlighted. But the application itself became more responsive and he is able to do another things while background job is processed.

Conclusion¶

In this tutorial you’ve seen that:

  • Sometimes you can’t avoid long-running methods in ASP.NET applications.
  • Long running methods can cause your application to be un-responsible from the users point of view.
  • To remove waits you should place your long-running method invocation into background job.
  • Background job processing is complex itself, but simple with Hangfire.
  • You can process background jobs even inside ASP.NET applications with Hangfire.
    Please, ask any questions using the comments form below.

原文:

http://docs.hangfire.io/en/latest/tutorials/highlight.html