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.

Kentico 9 Certified Developer

I haven't done the Kentico certified exam for over two years - but this doesn't make me any less of an awesome and competent Kentico Developer. Over the last two years, a lot has changed within the Kentico realm resulting in the subject matter becoming a little more of a challenge to keep up to speed with. Afterall, two years ago we saw the dawn of a new age - the end of Kentico 7 and the start of Kentico 8. I am seeing the same thing happening again, except this time we're just about seeing Kentico 10 making it's appearance over the horizon.

What I noticed this time round was the increased number of questions evolving around macro's. It felt like I was bombarded at the time of carrying out the exam. I think the only thing that got me through is remembering the approach I took to the macro's I wrote for a recent EMS project.

The Kentico Certification Preparation Guide has greatly improved compared to previous versions where in the past questions were pretty simple and a vast contrast to the real thing. This allowed me to gauge a lot more on the type of questions that would potentially be presented, but I did notice quite a few questions from the preparation guide cropped up in the real exam - although slightly re-worded.

I highly recommend anyone who is interested in becoming a Kentico Certified Developer to read the following post by Jeroen Furst prior to taking the exam called: Tips for becoming a Kentico Certified Developer. Jeroen brings up some really good points and guidance to prepare yourself. If only I came across this post two years ago when I wasn't too sure what to expect (being my first Kentico exam), I would have felt more comfortable in understanding what was required.

I was expecting there to be some questions relating to MVC due to all the effort made by the Kentico development team to make the MVC integration seamless within Kentico 9. Alas, this was not the case. Jeroen also states the following:

If you are planning to take any older v6, v7 or v8 exams (if still possible) you might run into questions regarding Azure and the Intranet solution. These topics are not part of the v9 exam anymore.

The Kentico 9 exam purely focuses on the core Kentico features as well as the platform architecture every Kentico developer should know in order to build high quality sites. You will also find yourself learning some new things in the process of preparing for the exam as well as brushing up on your existing knowledge.

If you succeed, you can proudly display this badge in all its glory! ;-)

Kentico 9 Certified Developer

My Development Overview of Kentico 9 MVC

When Kentico offered the option to build websites using MVC, I was one of the many developers who jumped at the chance to utilise the new programming model. I've been building websites using the MVC programming model ever since it was first made available in Kentico 7 and with each version, the MVC implementation just got better and better. So much so, I even built my very own website (currently in Kentico 8) in MVC.

MVC in Kentico has always been a bit of a hybrid being in the sense that it wasn't true MVC to the core, which is to be expected when you have to accommodate vast array of features the Kentico platform offers. Luckily for us Kentico 9 has wholeheartedly embraced MVC with open arms and things can only get better with subsequent versions.

I have listed a few observations I thought would be good to write about from my initial experience of using MVC in Kentico 9 whilst working on a client project. I will be talking (very high level) about the changes from previous versions of Kentico MVC as well as the new development approaches for Kentico 9.

1) Goodbye "Pages", Hello "Content-only Pages" Page Types

"Content-only pages" is a new addition to Kentico 9 and is another form of Page Type, with its primary job (as the name suggests) to store content. The main difference between "Pages" and "Content-only Pages", is:

  • Aren't based on Page Templates.
  • Provides a simplified interface when managing content.
  • Does not have a presentation URL. URL patterns now need to be specified which handles the presentation to the MVC site via routing.
  • Lacks the ability to create many Page Aliases.

"Content-only pages" is a requirement to developing MVC sites in Kentico 9. Overall, I actually found "Content-only pages" quite restrictive and useful key page properties are no longer available, such as the URLs and Navigation tabs. I really do wish that these features were left in.

Kentico 9 MVC Missing Page Properties

I will be talking more about the removal of the URLs in my next point, the missing Navigation property is easier to get around. I created a base content page called "Kentico Core Content" that contained all the fields that you would normally find under Navigation properties and inherited this page type on all my content-only pages, such as Articles. You'll then have to just make the customisations to inherit these fields at code level. Easy!

Kentico 9 Core Content Page Inheritance

2) No Document Aliases

There's no option to allow the site administrator to add multiple document aliases for a page. This alone was nearly a deal breaker for me and was tempted to either go down Portal or ASPX templates route. The ability to create multiple document aliases in the URLs section is very powerful feature, especially if you plan on adding 301 redirects.

To get around this excluded feature, you will either have to use URL Rewriting at web.config level or add additional routes at controller level to carry out all specific page redirects.

So before deciding whether to choose the MVC approach, ask yourself if this is pressing feature for you and your client.

3) Separation of the CMS and Presentation Layer

Kentico 8 stepped up the MVC integration by allowing the developer to build their sites using MVC through the CMSApp_MVC project. This created a basic form of separation at project level that was much better suited compared to mixing key MVC components (Controllers/Models/Views) into what is a Web Form powered site in it's infancy in Kentico 7.

Now there is complete separation between the CMS Admin and Presentation layer (or MVC site). Since the CMSApp_MVC approach has been made obselete in Kentico 9, you now have the full ability to create an MVC site as you would do normally in a non-Kentico web application. The only way Kentico and your MVC website can talk to one another is through a Web Farm configuration.

Kentico 9 MVC Architecture

I personally love this setup. My website can be kept light as possible and still harness the power of what Kentico has to offer through using conventional API calls from the Kentico library. I can tell you this for sure, the website itself performs better than ever and no one can tell what CMS is powering the site. Good for security.

4) Licensing and Environment Setup

Due to the need for Web Farm setup to allow syncronisation of content between the CMS and MVC site, the licensing requirements have changed. Based upon how you want to setup your separate sites, Kentico provides different licensing approaches, which pretty much covers all scenarios.

My preferred setup is to run the Kentico and the MVC application under two different sites, on separate domains. Again, my reasoning comes down to catering for that additional level of security where the management of your site is on a sub-domain and not so obvious where the administration area resides. In this case, two licenses will be required. For example:

  • MVC Website: www.surinderbhomra.com
  • Kentico Admin: admin.surinderbhomra.com

You will get a free license for the Kentico site as long as the subdomain is "admin".

The only sad part (for me personally) is that Kentico CMS Free Edition license does not allow for MVC websites. I really do hope that this changes at some point. I'd love to utilise full Kentico 9 MVC on future personal projects that are currently on the free edition. Otherwise they will forever be stuck in version 8.2.

5) Page Templates

The ability to use Page Templates alongside standard page types is still available within the Kentico interface, but you can only develop an MVC site this way by creating a (now obsolete) "CMSApp_MVC" project. Kentico 9 MVC is still fully backwards compatible with this approach.

6) Retrieving Content In MVC Controllers

In Kentico 8, a controller acted as the code-behind to your Page Template where you could get all the information about a current page by calling DocumentContext.CurrentDocument. In Kentico 9, this is no longer the case and it is recommended content should be retrieved using its auto-generated code. I generally don't go down the route of using the auto-generated code. I instead like to create my own custom methods so I have the freedom to pull out the exact data my data needs by passing the Node Alias Path into my control from the URL route patten. Personal preference.

7) Friendly URL's Should Include A Node ID

Kentico recommends all page URL's should consist of NodeID and Page alias, to ensure optimum search engine optimisation on the event the page alias of pages changes on the live site. Kentico's documentation states:

Typically, a page alias will be part of a macro expression that makes up a URL pattern in content only page types. For example, a URL pattern can be specified like this /Articles/{%NodeID%}/{%NodeAlias%}. Where {%NodeAlias%} accesses the page alias.

I've gone down the route of creating a custom route contraint in my MVC project, to allow me to retrieve TreeNode for the current document via HttpContext just from passing the Node Alias only. I could go into more detail, but this is probably best suited for another blog post. 

Conclusion

The MVC integration in Kentico is like a fine wine. It gets better and better every year (in this case release) and they should be congratulated for undertaking such a humongous task. Would I choose it over Portal or ASPX pages for every project? Probably not, because I can see clients expecting functionality that is not quite present in an MVC installation as of yet.

I do like the freedom MVC gives me whilst harnessing the power of Kentico and it works great on those projects that require maximum flexibility and the seperation of code-levels allows me to do that. In addition, if my site requires scaling, I can easily move it to Azure. I am very much looking forward to what Kentico has in store for feature releases.

If there is anything I have listed in my initial observation that are incorrect, please leave a comment and I will update this post.