CourtesyFlush : A Nuget package for flushing buffers early in ASP.NET MVC

In my previous post I have written about a Nuget package called Polly for Exception handling which you can find here.

In this post I will again write for a Nuget package which is called CourtesyFlush which was before known as PerfMatters.Flush and it is created by Nik

CourtesyFlush , as the name suggests it does the same effect in Coding word which simply means it is forcing a buffer to be moved along, usually to a file or the network. Rather than holding data, you flush it, and move it along.

banner

To install Courtesy Flush, run the following command in the Package Manager Console

image

I will try to explain the effects of this Nuget package by sample Project.

By keeping in mind that you know how to add new project in Asp.Net MVC we are now having below code in our Home controller page.

The only thing we will add in “About” action method is Thread.Sleep(2000).

Reason?

If you have a long running, but important process (we are pretending that Thread.Sleep(2000) is important) that takes 2 seconds, no HTML is sent to the browser. It’s just waiting.

Now basic code would like as below :-


        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }
        public ActionResult About()
        {
            ViewBag.Title = "Your About page.";
            Thread.Sleep(2000);

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

In above scenario there is no HTML is sent to the browser because we are waiting for 2 seconds. The timeline looks like this  

Here we didn't flush

As we can see in above image there is not any javascript or css files loaded until the process completed.

Now CourtseyFlush comes to rescue your application and let javascipt and css file not to wait in a vein like it did in above image.

First of all you need to add _Head.cshtml in shared folder as shown in below image :-

Create new MVC Partial View Menu in Visual studio
And in that view write below piece of code :-

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     @if (ViewBag.Description != null)
     {
         <meta name="description" content="@ViewBag.Description">
     }
     <title>@ViewBag.Title - My ASP.NET Application</title>
     @Styles.Render("~/Content/css")
     @Scripts.Render("~/bundles/modernizr")
</head>

and add @Html.FlushHead() in Layout.cshtml  page as shown below :-

@Html.FlushHead()
 <body>
 <!-- Lots of lovely HTML -->
 <div class="container body-content">
 @RenderBody()
 <hr />
 <footer>
 <p>&copy; @DateTime.Now.Year - My Application</p>
 </footer>
 </div>
 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/bootstrap")
 @RenderSection("scripts", required: false)
 </body>
 </html>

How to use on partilcar action level? 

Three Usage Patterns

The core of what you need to know to use PerfMatters.Flush is that I’ve tried to make it easy to use by providing a few different usage models. Pick the one that works best in your scenario, and feel free to mix and match across your application.

1. Attribute Based

The easiest way to use PerfMatters.Flush is via the [FlushHead] action filter attribute, like this:

[FlushHead(Title = &amp;quot;About&amp;quot;)]
public ActionResult About()
{
      // Do expensive work here
      return View();
}

The attribute can be used alone for HTML documents with a static <head> section. Optionally, a Title property can be set for specifying a dynamic <title> element, which is very common.

2. Code Based

For more complex scenarios, extension methods are provided which allow you to set ViewData or pass along a view model:

public ActionResult About()
{
     ViewBag.Title = &amp;quot;Your About page.&amp;quot;; 
     this.FlushHead();

     return View();
}

As you can see, this mechanism allows for very dynamic <head> sections. In this example you could imagine a <title> element, <meta name="description" content="…"> attribute (for SEO purposes) and <link rel="dns-prefetch" href="…"> (for performance optimization) all being set.

3. Global Lambda

Finally, PerfMatters.Flush offers a model to flush early across all your application’s action methods – which simply leverages the same global action filters that have been in ASP.NET MVC for years now:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     filters.Add(new HandleErrorAttribute());
     filters.Add(new FlushHeadAttribute(actionDescriptor =&amp;gt;
         new ViewDataDictionary&amp;lt;CustomObject&amp;gt;(new CustomObject())
         {
             {&amp;quot;Title&amp;quot;, &amp;quot;Global&amp;quot;},
             {&amp;quot;Description&amp;quot;, &amp;quot;This is the meta description.&amp;quot;}
         }));
}
Let us just take Code Based approach so our particular method would like as below :-
public ActionResult About()
{
    ViewBag.Title = DateTime.Now.Second;
    this.FlushHead();
 
    Thread.Sleep(2000);
    ViewBag.Message = &amp;quot;Your application description page.&amp;quot;;
 
    return View();
}

Here’s what the SAME page looks like with the <head> flushed out first.

Here we flushed
From the above picture it is clear that the formula works and now javascript and css files does not wait till the process completes
Now just look at below image which shows before\after effects :-
difference
After going through this code some might be wondering that Is this package is in use in any live website?
The answer is Yes. It is being used in http://getglimpse.com/ already!

 

Why Flush Early?

Flushing early can provide performance improvements in web applications and has been a recomended best practice in the web performance community since 2007.

To find out more, check out my blog where I covered the benefits of flushing early in two posts:

Happy Coding!


Advertisements

Polly : A latest nuget package for Exception handling

We all know that every applications sometime or other gives exception.

Have you ever wondered wish you could give Retry, Retry Forever or Wait and Retry on your particular exception? Well we have already a nuget package for that which is called Polly.

Polly is a .NET 3.5 / 4.0 / 4.5 / PCL library that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.

First of all we will see how to install Polly. Well there is not any rocket science for it and we will simply do it as we install other nugget packages as shown below :-

Install-Package Polly

Now I will summarise what facilities Polly provides us.

Handling exceptions :-

Handling exceptions can be a hassle sometimes. Not just setting the try/catches up, but deciding on the policy for the catch can make the exception management code more complex than the method itself!

So in Polly we can simply handle the exception as shown below :-


Policy.Handle<ArgumentNullException>();


and if you want to handle more exceptions then simply add .Or as shown below :-


Policy.Handle<ArgumentNullException>().Or<DivideByZeroException>();


Now suppose you want to handle only particular parameter for handling null exception then simply write :-

Policy.Handle<ArgumentNullException>(ex => ex.ParamName == "test");

Retry :-
Suppose you are in need where we want to give try to your code for more than one time not to fall in exception then here is the solution.

// Retry once
Policy.Handle<ArgumentNullException>().Retry();// Retry multiple times
Policy.Handle<ArgumentNullException>().Retry(3);

Now suppose you want to Retry multiple times, calling an action on each retry with the current exception and retry count.

Policy
.Handle<ArgumentNullException>()
.Retry(3, (exception, count) =>
{
// do something
});

Retry forever :-
As the name suggests this would retry forever.

Policy.Handle<ArgumentNullException>().RetryForever();

Suppose you want to Retry forever, calling an action on each retry with the current exception.

Policy
.Handle<ArgumentNullException>()
.RetryForever(exception =>
{
// do something
});

Retry and Wait :-
If you want to Retry and wait for a specified duration between each retry.

Policy
.Handle<ArgumentNullException>()
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(3)
});

And if you want to Retry and wait for a specified duration between each retry, calling an action on each retry with the current exception and duration

Policy
.Handle<ArgumentNullException>()
.WaitAndRetry(new[]
{
1.Seconds(),
2.Seconds(),
3.Seconds()
}, (exception, timeSpan) => {
// do something
});

Circuit Breaker :-
If you want to break the circuit after the specified number of exceptions and keep circuit broken for the specified duration.

Policy
.Handle<ArgumentNullException>()
.CircuitBreaker(2, TimeSpan.FromMinutes(1));

Once you have set up a policy, you execute on it.


Policy
  .Handle<SqlException>(ex => ex.Number == 1205)
  .Or<ArgumentException>(ex => ex.ParamName == "example")
  .Retry()
  .Execute(() => DoSomething());

Asynchronous Support (.NET 4.5 Only) :-

You can use Polly with asynchronous functions by using the asynchronous methods

  • RetryAsync
  • RetryForeverAsync
  • WaitAndRetryAsync
  • CircuitBreakerAsync
  • ExecuteAsync

In place of their synchronous counterparts

  • Retry
  • RetryForever
  • WaitAndRetry
  • CircuitBreaker
  • Execute

For example :-


await Policy
.Handle<SqlException>(ex => ex.Number == 1205)
.Or<ArgumentException>(ex => ex.ParamName == example)
.RetryAsync()
.ExecuteAsync(() => DoSomethingAsync());


I hope it will be useful and let me know if you want improvement because this is my first blog and by this blog I have started my journey of blogging!

Happy coding!