Using Cloudflare With Kentico - Purging Cached Media Files

This month I've been writing some blog posts on why I decided to start using Cloudflare service for my website and utilising its API to allow me to purge cached files from the Cloudflare CDN on demand. Before reading further, I highly suggest perusing those posts just to put everything into context for my reasoning into using Cloudflare as well as the C# code that interacts with the API, which I will be referencing later on within this very post.

My intial Cloudflare integration evolves around serving media files more efficiently through a CDN and having the ability to refresh these files automatically as updates are made within the Kentico CMS. Cloudflare's CDN services can help cache your content across their large global network, moving static files closer to your visitor.

Based on the Page Rules I configured within the Cloudflare dashboard, I am caching all media library files served through the /getmedia/ URL path into the Cloudflare CDN. The same file will be served through the CDN until the set cache limit has expired. We need to implement functionality that will add some automation to the Kentico platform to purge the cache of a specific media library file when updated.

Add A Global Event

I created an event handler for the updating of Media library files as I wanted to get details of the file being updated by leveraging the MediaFileInfo class to access the Update.After event.

protected override void OnInit()
{
    base.OnInit();

    MediaFileInfo.TYPEINFO.Events.Update.After += Update_After;
}

private void Update_After(object sender, ObjectEventArgs e)
{
    MediaFileInfo fileInfo = e.Object as MediaFileInfo;

    GlobalEventFunctions.PurgeMediaCache(fileInfo);
}

PurgeMediaCache() Method

The event above calls a GlobalEventFunctions.PurgeMediaCache() method that will pass the information about the changed file ready for purging. The file URL parsed to the Cloudflare.PurgeSelectedFiles() method needs to be exact and take into consideration how your instance of Kentico is serving media files. If Permanent URL's are being used the /getmedia/ URL needs to be constructed consisting of:

  • Current domain
  • File GUID
  • File Name
  • File Extension

Otherwise, we can just use get the file path as normal to where the media file resides.

public class GlobalEventFunctions
{
    /// <summary>
    /// Purges a file from the Cloudflare cache.
    /// </summary>
    /// <param name="fileInfo"></param>
    public static void PurgeMediaCache(MediaFileInfo fileInfo)
    {
        bool permanentURLEnabled = SettingsKeyInfoProvider.GetBoolValue($"{SiteContext.CurrentSiteName}.CMSMediaUsePermanentURLs");
        string filePath = string.Empty;
            
        if (permanentURLEnabled)
            filePath = $"{GetCurrentDomain()}/getmedia/{fileInfo.FileGUID.ToString()}/{fileInfo.FileName}{fileInfo.FileExtension}";
        else
            filePath = $"{GetCurrentDomain()}/{fileInfo.FilePath}";

        try
        {
            // Get code from: https://www.surinderbhomra.com/Blog/Post/2018/11/11/Cloudflare-API-Purge-Files-By-URL-In-C
            CloudflareCacheHelper cloudflareHelper = new CloudflareCacheHelper();

            cloudflareHelper.PurgeSelectedFiles(new List<string> { filePath });
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Cloudflare Purge File Cache", "CLOUDFLARE_PURGE", ex, SiteContext.CurrentSiteID, $"Purge File: {filePath}");
        }
    }

    /// <summary>
    /// Get domain from current http context.
    /// </summary>
    /// <returns></returns>
    private static string GetCurrentDomain()
    {
        return $"{HttpContext.Current.Request.Url.Scheme}{Uri.SchemeDelimiter}{HttpContext.Current.Request.Url.Host}{(!HttpContext.Current.Request.Url.IsDefaultPort ? $":{HttpContext.Current.Request.Url.Port}" : null)}";
    }
}

We need not consider any other scenarios, such as insert or deletion. If a file is inserted, there is nothing to purge as it's a new file that will be cached directly into in the CDN on first request and when it comes to deletion we can just wait for the cache to expire.

What's Next?

The integration I have detailed so far is just scratching the surface of what Cloudflare has to offer and will investigate further on pushing more content over to the CDN. One area, in particular, I am looking into is carrying out full page caching. You might be thinking why even bother as Kentico has pretty good caching mechanisms already in place?

Well Cloudflare has a really neat feature called "Always Online", where a cached version of a page is served if on the off chance it happens to go down or requires a reboot to install key security updates. But implementing this feature requires strict Page Rules to be setup within the Cloudflare dashboard to ensure the general workings of Kentico are not effected.

My Reasons for Using Cloudflare With Kentico

A couple day ago my website got absolutely hammered by a wave of constant SQL injection attacks by the same IP over a time period of a couple hours.

I only managed to notice this whilst perusing the Event Log within the Kentico Administration interface. I don't normally check my own error logs as regularly as I should do, but since my site has recently gone through a bit of a revamp (which I'm still yet to post about), I wanted to ensure I haven't broken anything.

To be honest, I am flattered that someone would think this site is worth the time and energy in trying to hack my site. Trust me, it ain't worth it.

Even though Kentico has handled these attacks well, as a precaution I wanted to implement an additional layer of security before any further untoward activity reaches to my site. Being on a shared hosting platform my options are limited and my hands are tied to put in an infrastructure that doesn't cost the world.

Enter Cloudflare

I have always had some form of awareness of the Cloudflare content delivery network, just never put the service into practice. At one point I was looking into utilising Cloudflare to manage all my site media files over their CDN. But Cloudflare isn't just a CDN, it's able to offer much more:

  • Analytics - monitor traffic as well as caching ratio and more!
  • Firewall - manage access by IP, country, or query rules.
  • Rate limiting - protect your site or API from malicious traffic by blocking client IP addresses that hit a URL pattern and exceed a threshold you define.
  • Page rules - to allow caching to be triggered by a number of rules targeting specific areas of a site.

The great thing is that these options are part of the free plan... even though there are restrictions to the number of settings you are able to put in place. The security options alone was enough of a reason to try out Cloudflare. But for my needs, the free plan seemed to tick all the boxes. I am just scratching the surface to what Cloudflare has to offer and have already got a few of the features working alongside Kentico.

How I'm Using Cloudflare With Kentico

As security was a main concern for me, one of the first things I did was to add in some rules through the firewall and block suspicious traffic. Naturally the next was to take advantage of the CDN capabilities. I wouldn't recommend full site caching unless you have some pretty strict page rules in place as this has a chance to cause issues with the Kentico Admin interface. By default, Cloudflare doesn't cache HTML pages, which is a good thing as it gives us a plain canvas to target the areas we want to cache.

Being on the free plan, I only had three page rules at my disposal and made the decision to cache the following parts of my site.

Area Regex Rule Settings
Media Library Files (using Permanent URL's) *surinderbhomra.com/
getmedia/*

Cache Level: Caches Everything
Edge Cache TTL: A month
Browser Cache TTL: 16 days

Site CSS, JavaScript and Images *surinderbhomra.com/
resources/*
Cache Level: Caches Everything
Edge Cache TTL: A month
Browser Cache TTL: 16 days
ScriptResource.axd/WebResource.axd *surinderbhomra.com/*.axd Cache Level: Caches Everything
Edge Cache TTL: 7 days
Browser Cache TTL: 7 days

Two cache types are used:

  1. Edge Cache TTL - is the setting that controls how long CloudFlare's edge servers will cache a resource before requesting a fresh copy from your server. 
  2. Browser Cache TTL - is the time that CloudFlare instructs a visitor's browser to cache a resource. Until this time expires, the browser will load the resource from its local cache and speeding up the request.

I am caching my assets for a considerable amount of time, which begs the question how will changes to files purge the cache in Cloudflare? Luckily, Cloudflare has quite a nice API, where I have the ability to purge everything or individual files (maximum of 30 in one request).

Purge Media Library File Cache

I am in the middle of testing a GlobalEvent handler that will carry out the following steps when files are inserted or updated:

  • Get path of the file.
  • Check if site is using Permanent URL's. As the URL to the file will be constructured differently if enabled.
  • Convert the relative path to an absolute path.
  • Pass the absolute file path to Cloudflare using the following Purge Files by URL API endpoint.

Once I have carried out some further tests, I will be posting this code in a follow-up post.

Purge Site File Cache

Now attempting to purge the cache for site files such as JavaScript, CSS and images are a little more tricky as I need to keep an eye on the files changed. The easiest thing to do is I could write some code that will iterate through all the files in the /resources folder and purge everything from the CDN. Not the most elegant solution. Still, need to ponder on the correct implementation. If anyone has got any better suggestions, let me know.

How Do I Know Cloudflare Is Caching My Site Files?

It does take a little time in Cloudflare to cache all files on a site. It all depends on pages being viewed. A page needs to be loaded in order to submit all its contents to cache. On first load, the response header CF-Cache-Status will return a "MISS", which means the content has not been served from Cloudflare.

Cloudflare Response - MISS

However, when you go back to the page and re-check the page headers, the CF-Cache-Status should return "HIT". If this is not the case, check your Page Rules within the Cloudflare dashboard.

Cloudflare Response - HIT

Is Cloudflare Worth It?

Quick answer - Yes!

Setup is very straight-forward. All that is required is to carry out a change to your domain and point your DNS to the DNS Cloudflare assigns to you. There is no downtime in doing this. As a result, overall site performance has improved and page speed test faired much better.

To give you a better insight for transparency, here are some statistics straight from my Cloudflare portal over a 24 hour period:

Requests Through Cloudflare
(Understandably, the number of cached items served through Cloudflare is low due to only caching specific areas)

Cloudflare Performance
(My basic shared hosting should now be performing better as less requests are being served via the origin server)

Cloudflare Detected Threats
(Blocked threats - the reason why I decided to give Cloudflare a try in the first place)

I still have to carry out a lot more research in using Cloudflare to its full potential and will use my website as a test bed to see what I can achieve. My end goal is to make my website quicker and more secure!

Kentico - Call 404 Page From Code

There will be times when you want to direct a user to a 404 page based on certain conditions from within your code. For example, when dealing with pages that use wildcard URL's, you might want to redirect the user to a 404 page if the value of that wildcard parameter returns no data.

In my blog I have two wildcard parameters to allow the user to filter my posts by either category or tag. At code-level if no blog posts are returned based on the category or tag value, I have two choices:

  1. Display a "no results" message
  2. Redirect to a 404 page

As you can tell by the title of this post, I wanted to go for the latter.

From a Kentico perspective wildcard parameters in a URL aren't what I call "proper" pages and the CMS routing engine won't send you a 404 page as you'd think. So we need to carry the redirect at code-level ourselves based on the conditions we provide. As far as I'm aware, Kentico doesn't have a method in code to do this and settled for a workaround suggested by Sébastien Gumy in the following DevNet post.

I made some minor changes to the code and placed it in a helper method for use throughout my project with ease:

using CMS.Helpers;
using CMS.PortalEngine;
using CMS.URLRewritingEngine;

namespace Site.Common.Kentico
{
    public class PortalContextHelper
    {
        /// <summary>
        /// Redirect page to 404.
        /// </summary>
        public static void SendToPageNotFound()
        {
            PortalContext.Clear();
            CMSHttpContext.Current.Response.StatusCode = 404;
            URLRewriter.RewriteUrl(RequestStatusEnum.PageNotFound, string.Empty, ExcludedSystemEnum.Unknown);
        }
    }
}

The SendToPageNotFound() method can then be used in the following way:

#region Get Querystring Parameters

string tag = QueryHelper.GetString("Tag", string.Empty);
string category = QueryHelper.GetString("Category", string.Empty);
int pageNo = QueryHelper.GetInteger("PageNo", 1);

#endregion

int tagId = TagLogic.GetTagIdFromQuerystring(tag);

// A custom method to get back blog posts based on parameters.
BlogListing postData = BlogLogic.GetBlogPosts(CurrentDocument.NodeAliasPath, category, tagId, (pageNo - 1));

if (postData.BlogPosts != null)
{
    BlogListing.DataSource = postData.BlogPosts;
    BlogListing.DataBind();
}
else
{
    // Send to 404 page.
    PortalContextHelper.SendToPageNotFound();
}

Please note: This has only been tested in Kentico 10.

The Journey To Kentico Cloud

From working at Syndicut, I have had both the opportunity and pleasure of working with many different platforms. The most exciting development for me over the years has been the shift on how content management systems are being decoupled from the very applications they push content to. I have blogged about this many years ago when I first used Prismic, which at the time seemed the most viable option. Even though there were pros and cons.

I always felt the cons were more related to the restrictions on what the platform offered and not the architecture itself. I write my thoughts on the journey to how [at Syndicut] we've used headless CMS's in the past, to now using Kentico Cloud. Kentico Cloud is indeed a very promising headless CMS platform. Even though it hasn't been in the market that long when compared to its competitors, but it embodies something more:

  • Proactive development team who take an active step towards bugs and improvements.
  • A wide variety of boilerplate templates to accommodate different code frameworks.
  • Boilerplate templates updated regularly.
  • A clear roadmap to the features developers can expect and release deadlines.
  • Accessible and quick to respond support team.

Some highlights to take away from the post:

The common misconception we get from clients is on the surface, a headless based CMS can appear restrictive compared to platforms they are previously used to. However, that cannot be further from the truth. Once there is an understanding of how data can be given a hierarchy, category, relationships and workflow, they seem to run with curating content fairly quickly.

For agile projects where there is a need to manage content for multiple channels, or for creating tagged content hubs for digital marketing purposes, Kentico Cloud is the best option.

Headless CMS is a ticket to freedom for those who wish to take it. Why waste time worrying about hardware infrastructure, security and platform updates when you can invest that time in purely building your application and content?

As a business or developer, you might be hesitant to make the change. When I first read about decoupled architecture, I too had some hesitation as a lot of faith is invested in the platforms scalability and features. But with services like Kentico Cloud, who are pushing the boundaries with every release, they are changing our perception for the better on what we think we should expect from a headless CMS.

Take a read here: https://medium.com/syndicut/our-headless-cms-journey-to-kentico-cloud-b26c4eb39ed7

Kentico MVC - Getting TreeNode At Controller Level

I wrote a post a couple of years ago regarding my observations on developing a Kentico site using MVC in version 9. Ever since Kentico 9, there was a shift in how MVC applications are to be developed, which has pretty much stood the test of time as we've seen in releases since then. The biggest change being the CMS itself is purely used to manage content and the presentation layer is a separate MVC application connected through a Web Farm interface.

The one thing I missed when working on sites in Kentico's MVC is the ability to get values from the current document as you could do in Kentico 8 MVC builds:

public ActionResult Article()
{
    TreeNode page = DocumentContext.CurrentDocument;

    // You might want to do something complex with the TreeNode here...

    return View(page);
}

In Kentico 11, the approach is to use wrapper classes using the Code Generator feature the Kentico platform offers from inside your Page Type. The Kentico documentation describes this approach quite aptly:

The page type code generators allow you to generate both properties and providers for your custom page types. The generated properties represent the page type fields. You can use the providers to work with published or latest versions of a specific page type.

You can then use these generated classes inside your controllers to retrieve page type data.

Custom Route Constraint

In order to go down a similar approach to get the current document just like in Kentico 8, we'll need to modify our MVC project and add a custom route constraint called CmsUrlConstraint. The custom route constraint will call DocumentHelper.GetDocument() method and return a TreeNode object based on the Node Alias path.

CmsUrlConstraint

Every Page Type your MVC website consists of will need to be listed in this route constraint, which will in turn direct the incoming request to a controller action and store the Kentico page information within a HttpContext if there is a match. To keeps things simple, the route constraint contains the following pages:

  • Home
  • Blog
  • Blog Month
  • Blog Post
public static class RouteConstraintExtension
{
    /// <summary>
    /// Set a new route.
    /// </summary>
    /// <param name="values"></param>
    /// <param name="controller"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public static RouteValueDictionary SetRoute(this RouteValueDictionary values, string controller, string action)
    {
        values["controller"] = controller;
        values["action"] = action;

        return values;
    }

    #region CMS Url Contraint

    public class CmsUrlConstraint : IRouteConstraint
    {
        /// <summary>
        /// Check for a CMS page for the current route.
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="route"></param>
        /// <param name="parameterName"></param>
        /// <param name="values"></param>
        /// <param name="routeDirection"></param>
        /// <returns></returns>
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            string pageUrl = values[parameterName] == null ? "/Home" : $"/{values[parameterName].ToString()}";

            // Check if the page is being viewed in preview.
            bool previewEnabled = HttpContext.Current.Kentico().Preview().Enabled;

            // Ignore the site resource directory containing Image, CSS and JS assets to save call to Kentico API.
            if (pageUrl.StartsWith("/resources"))
                return false;

            // Get page from Kentico by alias path in its published or unpublished state.
            // PageLogic.GetByNodeAliasPath() method carries out the document lookup by Node Alias Path.
            TreeNode page = PageLogic.GetByNodeAliasPath(pageUrl, previewEnabled);

            if (page != null)
            {
                // Store current page in HttpContext.
                httpContext.Items["CmsPage"] = page;

                #region Map MVC Routes

                // Set the routing depending on the page type.
                if (page.ClassName == "CMS.Home")
                    values.SetRoute("Home", "Index");

                if (page.ClassName == "CMS.Blog" ||  page.ClassName == "CMS.BlogMonth")
                    values.SetRoute("Blog", "Index");

                if (page.ClassName == "CMS.BlogPost")
                    values.SetRoute("Blog", "Post");

                #endregion

                if (values["controller"].ToString() != "Page")
                    return true;
            }

            return false;
        }
    }

    #endregion
}

To ensure page data is returned from Kentico in an optimum way, I have a PageLogic.GetByNodeAliasPath() method that ensures cache dependencies are used if the page is not in preview mode.

Apply Route Constraint To RouteConfig

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        ...

        // Maps routes to Kentico HTTP handlers.
        // Must be first, since some Kentico URLs may be matched by the default ASP.NET MVC routes,
        // which can result in pages being displayed without images.
        routes.Kentico().MapRoutes();

        // Custom MVC constraint validation to check for a CMS template, otherwise fallback to default MVC routing.
        routes.MapRoute(
            name: "CmsRoute",
            url: "{*url}",
            defaults: new { controller = "HttpErrors", action = "NotFound" },
            constraints: new { url = new CmsUrlConstraint() }
        );

        ...
    }
}

Usage In Controller

Now that we have created our route constraint and applied it to our RouteConfig, we can now enjoy the fruits of our labour by getting back the document TreeNode from HttpContext. The code sample below demonstrates getting some values for our Home controller.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        TreeNode currentPage = HttpContext.Items["CmsPage"] as TreeNode;

        if (currentPage != null)
        {
            HomeViewModel homeModel = new HomeViewModel
            {
                Title = currentPage.GetStringValue("Title", string.Empty),
                Introduction = currentPage.GetStringValue("Introduction", string.Empty)
            };

            return View(homeModel);
        }

        return HttpNotFound();
    }
}

Conclusion

There is no right or wrong in terms of the approach you as a Kentico developer use when getting data out from your page types. Depending on the scale of the Kentico site I am working on, I interchange between the approach I detail in this post and Kentico's documented approach.

Cache Busting Kentico

When developing a website that is quick to load on all devices, caching from both a data and asset perspective is very important. Luckily for us, Kentico provides a comprehensive approach to caching data in order to minimise round-trips to the database. But what about asset caching, such as images, CSS and JavaScript files?

A couple days ago, I wrote an article on the Syndicut Medium publication on how I have added cache busting functionality in our Kentico CMS builds. I am definitely interested to hear what the approaches other developers from the Kentico network take in order to cache bust their own website assets.

Take a read here: https://medium.com/syndicutstudio/cache-busting-kentico-cf89496ffda0.

Kentico Cloud: Custom MVC Cache Attribute

I decided to write this blog post after one of my fellow Kentico Cloud developer Matt Nield tweeted the following last week:

Webhook capability is something I have been yearning for since I built my first Kentico Cloud project and this feature cannot come soon enough! It will really take the Kentico Cloud headless CMS integration within our applications to the next level. One of the main things I am looking forward to is using webhooks is to develop a form of dependency caching, so when content is updated in Kentico Cloud, the application can reflect these changes.

In fact, I am so excited to have this feature in my hands for my caching needs, I have already started developing something I could potentially use in time for the Q3 2017 release - should be any time now.

As we all know, to not only improve overall performance of your application as well as reducing requests to the Kentico Cloud API, we are encouraged to set a default cache duration. There is documentation on the different routes to accomplish this:

  1. Controller-level - using OutputCache attribute
  2. CachedDeliveryClient class - provided by the Kentico Cloud Boilerplate that acts as a wrapper around the original DeliveryClient object to easily cache data returned from the API for a fixed interval.

I personally prefer caching at controller level, unless the application is doing something very complex at runtime for manipulating incoming data. So in the mean time whilst I wait for webhook functionality to be released, I decided to create a custom controller attribute called "KenticoCacheAttribute", that will only start the caching process only if the application is not in debug mode.

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

namespace Site.Web.Attributes
{
    public class KenticoCacheAttribute : OutputCacheAttribute
    {
        public KenticoCacheAttribute()
        {
            Duration = HttpContext.Current.IsDebuggingEnabled ? 0 : int.Parse(ConfigurationManager.AppSettings["KenticoCloud.CacheDuration"]);
        }
    }
}

The "KenticoCacheAttribute" inherits the OutputCacheAttribute class, which gives me additional control to when I'd like the caching process to happen. In this case, the cache duration is set within the web.config.

I found the one main benefit of my custom controller attribute is that I will never forget to start caching pages on my website when it comes to deployment to production, since we never want our website to have debugging enabled unless we're in a development environment. This also works the other way. We're not too concerned about caching in a development environment as we always want to see changes in incoming data straight away.

The new cache attribute is used in the exact same approach as OutputCacheAttribute, in the following way:

[Route("{urlSlug}")]
[KenticoCacheAttribute(VaryByParam = "urlSlug")]
public async Task<ActionResult> Detail(string urlSlug)
{
     // Do something...

    return View();
}

This is a very simple customisation I found useful through my Kentico Cloud development.

The custom attribute I created is just the start on how I plan on integrating cache managment for Kentico Cloud applications. When webhook capability is released, I can see further improvements being made, but may require a slightly different approach such as developing a custom MVC Action Filter instead.

Kentico Open Graph Custom Macro

Ever since I re-developed my website in Kentico 10 using Portal Templates, I have been a bit more daring when it comes to immersing myself into the inner depths of Kentico's API and more importantly - K# macro development. One thing that has been on my list of todo's for a long time was to create a custom macro extension that would render all required META open graph tags in a page.

Adding these type of META tags using ASPX templates or MVC framework is really easy to do when you have full control over the page markup. I'll admit, I don't know if there is already an easier way to do what I am trying to accomplish (if there is let me know), but I think this macro is quite flexible with capability to expand the open graph output further.

This is how I currently render the Meta HTML within my own website at masterpage level (click for a larger image):

Open Graph HTML In Masterpage

I instantly had problems with this approach:

  1. The code output is a mess.
  2. Efficiency from a performance standpoint does not meet my expectations.
  3. Code maintainability is not straight-forward, especially if you have to update this code within the Page Template Header content.

CurrentDocument.OpenGraph() Custom Macro

I highly recommend reading Kentico's documentation on Registering Custom Macro Methods before adding my code. It will give you more of an insight on what can be done that my blog post alone will not cover. The implementation of my macro has been developed for a Kentico site that is a Web Application and has been added to the "Old_App_Code" directory.

// Registers methods from the 'CustomMacroMethods' container into the "String" macro namespace
[assembly: RegisterExtension(typeof(CustomMacroMethods), typeof(TreeNode))]
namespace CMSApp.Old_App_Code.Macros
{
    public class CustomMacroMethods : MacroMethodContainer
    {
        [MacroMethod(typeof(string), "Generates Open Graph META tags", 0)]
        [MacroMethodParam(0, "param1", typeof(string), "Default share image")]
        public static object OpenGraph(EvaluationContext context, params object[] parameters)
        {
            if (parameters.Length > 0)
            {
                #region Parameter variables

                // Parameter 1: Current document.
                TreeNode tnDoc = parameters[0] as TreeNode;
                
                // Paramter 2: Default social icon.
                string defaultSocialIcon = parameters[1].ToString();

                #endregion

                string metaTags = CacheHelper.Cache(
                    cs =>
                    {
                        string domainUrl = $"{HttpContext.Current.Request.Url.Scheme}{Uri.SchemeDelimiter}{HttpContext.Current.Request.Url.Host}{(!HttpContext.Current.Request.Url.IsDefaultPort ? $":{HttpContext.Current.Request.Url.Port}" : null)}";

                        StringBuilder metaTagBuilder = new StringBuilder();

                        #region General OG Tags
                        
                        metaTagBuilder.Append($"<meta property=\"og:title\" content=\"{DocumentContext.CurrentTitle}\"/>\n");

                        if (tnDoc.ClassName == KenticoConstants.Page.BlogPost)
                            metaTagBuilder.Append($"<meta property=\"og:description\" content=\"{tnDoc.GetValue("BlogPostSummary", string.Empty).RemoveHtml()}\" />\n");
                        else
                            metaTagBuilder.Append($"<meta property=\"og:description\" content=\"{tnDoc.DocumentPageDescription}\" />\n");

                        if (tnDoc.GetValue("ShareImageUrl", string.Empty) != string.Empty)
                            metaTagBuilder.Append($"<meta property=\"og:image\" content=\"{domainUrl}{tnDoc.GetStringValue("ShareImageUrl", string.Empty).Replace("~", string.Empty)}?width=600\" />\n");
                        else
                            metaTagBuilder.Append($"<meta property=\"og:image\" content=\"{domainUrl}/{defaultSocialIcon}\" />\n");

                        #endregion

                        #region Twitter OG Tags

                        if (tnDoc.ClassName == KenticoConstants.Page.BlogPost || tnDoc.ClassName == KenticoConstants.Page.GenericContent)
                            metaTagBuilder.Append("<meta property=\"og:type\" content=\"article\" />\n");
                        else
                            metaTagBuilder.Append("<meta property=\"og:type\" content=\"website\" />\n");

                        metaTagBuilder.Append($"<meta name=\"twitter:site\" content=\"@{Config.Twitter.Account}\" />\n");
                        metaTagBuilder.Append($"<meta name=\"twitter:title\" content=\"{DocumentContext.CurrentTitle}\" />\n");
                        metaTagBuilder.Append("<meta name=\"twitter:card\" content=\"summary\" />\n");

                        if (tnDoc.ClassName == KenticoConstants.Page.BlogPost)
                            metaTagBuilder.Append($"<meta property=\"twitter:description\" content=\"{tnDoc.GetValue("BlogPostSummary", string.Empty).RemoveHtml()}\" />\n");
                        else
                            metaTagBuilder.Append($"<meta property=\"twitter:description\" content=\"{tnDoc.DocumentPageDescription}\" />\n");

                        if (tnDoc.GetValue("ShareImageUrl", string.Empty) != string.Empty)
                            metaTagBuilder.Append($"<meta property=\"twitter:image\" content=\"{domainUrl}{tnDoc.GetStringValue("ShareImageUrl", string.Empty).Replace("~", string.Empty)}?width=600\" />");
                        else
                            metaTagBuilder.Append($"<meta property=\"twitter:image\" content=\"{domainUrl}/{defaultSocialIcon}\" />");

                        #endregion

                        // Setup the cache dependencies only when caching is active.
                        if (cs.Cached)
                            cs.CacheDependency = CacheHelper.GetCacheDependency($"documentid|{tnDoc.DocumentID}");

                        return metaTagBuilder.ToString();
                    },
                    new CacheSettings(Config.Kentico.CacheMinutes, KenticoHelper.GetCacheKey($"OpenGraph|{tnDoc.DocumentID}"))
                );

                return metaTags;
            }
            else
            {
                throw new NotSupportedException();
            }
        }
    }
}

This macro has been tailored specifically to my site needs with regards to how I am populating the OG META tags, but is flexible enough to be modified based on a different site needs. I am carrying out checks to determine what pages are classed as "article" or "website". In this case, I am looking out for my Blog Post and Generic Content pages.

I am also being quite specific on how the OG Description is populated. Since my website is very blog orientated, there is more of a focus to populate the description fields with "BlogPostSummary" field if the current page is a Blog Post, otherwise default to "DocumentPageDescription" field.

Finally, I ensured that all article pages contained a new Page Type field called "ShareImageUrl", so that I have the option to choose a share image. This is not compulsory and if no image has been selected, a default share image you pass as a parameter to the macro will be used.

Using the macro is pretty simple. In the header section of your Masterpage template, just add the following:

Open Graph Macro Declaration

As you can see, the OpenGraph() macro can be accessed by getting the current document and passing in a default share icon as a parameter.

Macro Benchmark Results

This is where things get interesting! I ran both macro implementations through Kentico's Benchmark tool to ensure I was on the right track and all efforts to develop a custom macro extension wasn't all in vain. The proof is in the pudding (as they say!).

Old Implementation

Total runs: 1000
Total benchmark time: 1.20367s
Total run time: 1.20267s

Average time per run: 0.00120s
Min run time: 0.00000s
Max run time: 0.01700s

New Implementation - OpenGraph() Custom Macro

Total runs: 1000
Total benchmark time: 0.33222s
Total run time: 0.33022s

Average time per run: 0.00033s
Min run time: 0.00000s
Max run time: 0.01560s

The good news is that the OpenGraph() macro approach has performed better over my previous approach across all benchmark results. I believe caching the META tag output is the main reason for this as well as reusing the current document context when getting page values.

New Year, New Site!

This site has been longing for an overhaul, both visually and especially behind the scenes. As you most likely have noticed, nothing has changed visually at this point in time - still using the home-cooked "Surinder theme". This should suffice in the meantime as it currently meets my basic requirements:

  • Bootstrapped to look good on various devices
  • Simple
  • Function over form - prioritises content first over "snazzy" design

However, behind the scenes is a different story altogether and this is where I believe matters most. Afterall, half of web users expect a site to load in 2 seconds or less and they tend to abandon a site that isn’t loaded within 3 seconds. Damning statistics!

The last time I overhauled the site was back in 2014 where I took a more substantial step form to current standards. What has changed since then? I have upgraded to Kentico 10, but this time using ASP.NET Web Forms over MVC.

Using ASP.NET Web Form approach over MVC was very difficult decision for me. Felt like I was taking a backwards step in making my site better. I'm the kind of developer who gets a kick out of nice clean code output. MVC fulfils this requirement. Unfortunately, new development approach for building MVC sites from Kentico 9 onwards will not work under a free license.

The need to use Kentico as a platform was too great, even after toying with the idea of moving to a different platform altogether. I love having the flexibility to customise my website to my hearts content. So I had to the option to either refit my site in Kentico 10 or Kentico Cloud. In the end, I chose Kentico 10. I will be writing in another post why I didn't opt for the latter. I'm still a major advocate of Kentico Cloud and started using it on other projects.

The developers at Kentico weren't lying when they said that Kentico 10 is "better, stronger, faster". It really is! I no longer get the spinning loader for obscene duration of time whilst opening popups in the administration interface or lengthy startup times when the application has to restart.

Upgrading from Kentico 8.0 to 10 alone was a great start. I have taken some additional steps to keep my site clean as possible:

  1. Disable view state on all pages, components and user controls.
  2. Caching static files, such as CSS, JS and images. You can see how I do this at web.config level from this post.
  3. Maximising Kentico's cache dependencies to cache all data.
  4. Took the extra step to export all site contents into a fresh installation of Kentico 10, resulting in a slightly smaller web project and database size.
  5. Restructured pages in the content tree to be more efficient when storing large number of pages under one section. 

I basically carried out the recommendations on optimising website performance and then some! My cache statatics have never been so high!

My Kentico 10 Cache Statistics

One slight improvement (been a long time coming) is better open graph support when sharing pages on Facebook and Twitter. Now my links look pretty within a tweet.

I Ain't Afraid Of No Ghost

As I have been writing the last few blog posts, I've been getting the case of "twitchy feet" during the writing process. I normally get "twitchy feet" when frustrated or annoyed by things in my life that I feel could be done easier. In this case, my site has started to frustrate me and felt that adding new posts became a chore.

Over the 10 years (has it really been this long!?) owning and maintaining this site, it's started to become a bit of the beast from the initial outset. I've jumped from platform to platform based on my needs at the time:

  • Wordpress (2006)
  • BlogEngine (2007 to 2012)
  • Kentico (2012 to present)

I feel at the grand old age of 31, I need a platform that nurtures my writing creativity without having to worry about general maintainance and somewhat restrictive editorial functionality. Ever since I tasted the pure nectar that is Markdown, my writing speed has gone through the roof and love having full control through the simplistic editing interface - Markdown is the furture!

I am a certified Kentico Developer (you may have got that impression from my vast posts on the platform) and specifically chose Kentico CMS because it gave me the full flexibility to build the site how I wanted. As great as the platform is, I've come to the conclusion that this site will never grow to be anything more than one thing: a blog. So I want to down-size like a person getting on in his years and move to a smaller house.

Enter Ghost...

Ghost

The Ghost platform has garnered a lot of traction over the years ever since its concept in 2012. I've been keeping an eye on it over the years and never really gave the platform much thought until I noticed quite a few popular bloggers making the move and experiencing the lightening fast performance. This is possibly down to the blogger hosting their instance on Ghost Pro. Could be wrong. I am planning on going down the Ghost Pro hosting route and get everything setup by the very nice people behind the scenes at Ghost HQ, who will lovingly host and look after my site.

I opened up a dialog on Twitter to Ghost who were very kind in alleviating my initial migration worries:

The only thing I will have to get over, which Ghost will not be able to help me with is getting over the mindset that I will not be able to to tinker around with my site to the full extent as I do now. But this isn't necessarily a bad thing and will give me the opportunity to concentrate more on writing quality content. I just hate the thought of restricting myself.

Ghost has put a framework in place that no other platform has done so well - giving power to write content anywhere:

  • Desktop browser
  • Mobile browser
  • Desktop application

Looks like Ghost lives up to its main selling point:

An open source blogging platform which makes writing pleasurable and publishing simple.

What I also love is the SEO optimisation out-of-the-box. God knows how many hours I've spent trying to get my site SEO friendly, not only from an search indexing standpoint, but a social sharing standpoint too with all the open graph tags built-in. No need for extra plugins or development from a code perspective.

Whats Next?

As it currently stands, I am evaluating Ghost through their 14 day trial and need to send an email to their support team before I make a confirmed decision to move. I like what I am seeing to far. Just need to get the time to put a migration process in place to move the 200 posts on this site. Eek!

Ghost is definitely not as scary as I once thought. Cue Ray Parker Jr...