Brian McKeiver's Blog

How to Connect Disqus Comments to Kentico EMS Activity Tracking


Introduction

My team and I use the Disqus blog comment system on the blogs that we have created for BizStream.com, my site here at Mcbeev.com, and many other of our client projects. Disqus is a great system for handling blog post comments. It makes the moderating, anti-spam, and community building aspect of running a blog a breeze. I could not recommend it more.

All of those aforementioned blogs are of course powered by my favorite ASP.Net based CMS, Kentico. You might be wondering why, for those very same sites, we do not use the built-in Blog Comment View webpart that comes with Kentico. The truth is that this one area of Kentico is a bit outdated in terms of HTML markup and overall functionality. These deficiencies make styling the webpart a challenge, to meet a good responsive design, plus the anti-spam system that Kentico has is ok, but not great. For those reasons we now use Disqus.

One thing that has always bugged me about using Disqus for comments is that the service is all purely client side / JavaScript based, and therefore I lose a little bit of insight into exactly who is commenting on my blog posts from a Kentico Contact Management and Activity Tracking perspective.

My goal today is to show you how to fix that and trap those client side events that happen via JavaScript and log them in the built in Kentico Activity Tracking database and UI.

This is part one of a two part series. The second part can be found here.

 

Disqus Setup

The quantity of blog post comments is one metric that website owners and/or marketing departments care quite a bit about. Most experts agree that one way to get more blog post comments and customer engagement is to make it as dead simple as possible for website visitors to make a comment on your post. Again this is why I feel Disqus is a good overall solution. It makes it easy for people to use existing social accounts such as Facebook and Twitter to login, saving them the hassle of having to create an account. In theory the solution reduces the learning curve to almost zero for website visitors to sign up and write more comments.

Disqus is very easy to get started with. Simply register for a Disqus account, and then you can add your website as a new Site profile. Remember you even take this step for your localhost development environment. After that you generate a  Unique Disqus URL on the new Site profile for your site or “shortname”. Remember that “shortname” for sure.

 

Disqus Blog Post Comments for Kentico

 

Next open up a new browser tab (and leave it open) to the Admin –> Settings –> Install page and choose Universal Code so that later on you can copy and paste the script from Disqus right into your Kentico site.

 

Disqus Install for Kentico

 

 

Kentico Pre-Setup

Now would be a good time to mention that this solution was tested with Kentico 8.1 with all of the online integrated marketing capabilities enabled. I’m not entirely sure it is backwards compatible to version 8.0, but it should not be that hard to retro fit it. If you are interested in this for older versions of Kentico just leave a comment on this post.

The solution for Kentico 8.1 contains two projects by default. We will be using the CMSApp_MVC project that comes with the default install of Kentico 8.1, and we will be leveraging WebApi to act as our data broker between the client side script and event that Disqus loads up and triggers when a website visitor leaves a new comment.

I would also like to point out that I was inspired to create this post after reading the great Kentico DevNet article about Tracking Activities and Conversions from JavaScript in Kentico 8. I wanted to put the technique that Jakub Kadlubiec described to use. If you follow his example, he shows the basics of how we need to create a WebApi Controller to handle the backend update to the Activity Tracking database that Kentico’s On-line Marketing Solution uses. So let’s do that.

Step 1: Create a new custom Activity Type to correctly categorize the new activity that we are tracking. That can easily be done by navigating to On-line Marketing –> Contact Management –> Configuration –> Activity types. Click on the New Activity type button and type in Activity type as Disqus Comment and click save.

 

 

Kentico EMS - New Activity Type

 

 

Step 2: Now switch back to Visual Studio and get ready to start coding. From here we need to create a new WebApi Controller. I created a new folder named WebApiControllers and then created a new class in that folder for our controller named LogDisqusCommentController.cs (special note: the name of the controller class has to end in Controller).

 

 

Kentico 8.1 Solution Explorer

 

 

Step 3: Now that the file is created, inside of LogDisqusCommentController.cs add the following code and save the file. Again thanks to Jakub Kadlubiec for most of the snippet.

 

 

using System.Net;
using System.Web.Http;

using CMS.OnlineMarketing;
using CMS.SiteProvider;
using CMS.WebAnalytics;
using CMS.Localization;

namespace CMS.Mvc.Controllers
{
    /// 
    /// Handles API Methods for Disqus client side action tracking
    /// 
    public class LogDisqusCommentController : ApiController
    {
        /// 
        /// Log new Activity and Conversion for Disqus Comment
        /// 
        /// CommentID from Disqus API
        /// string OK on success
        public string Post([FromBody] string CommentID)
        {
            var currentContact = OnlineMarketingContext.CurrentContact;

            // Do not proceed, if OnlineMarketing is disabled
            if (currentContact == null)
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }

            //Create an Activity record
            ActivityInfo newActivity = new ActivityInfo()
            {
                ActivityType = "DisqusComment",
                ActivityTitle = string.Format("Comment Added to Document {0}", string.Empty),
                ActivitySiteID = SiteContext.CurrentSiteID,
                ActivityValue = string.Format("Disqus CommentID: {0}", CommentID),
                ActivityOriginalContactID = currentContact.ContactID,
                ActivityActiveContactID = currentContact.ContactID,
                ActivityURL = CMS.Helpers.RequestContext.URLReferrer,  //switching this around on purpose so UI shows which page we received the comment on
                ActivityURLReferrer = CMS.Helpers.RequestContext.URL.AbsoluteUri, //switching this around on purpose so UI shows referrer as the API call
            };
            ActivityInfoProvider.SetActivityInfo(newActivity);

            //Treat it as a Conversion
            string siteName = SiteContext.CurrentSiteName;
            if (AnalyticsHelper.TrackConversionsEnabled(siteName))
            {
                HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, "DisqusComment", 0, 1, 1);
            }

            return "OK";
        }
    }
}

 

 

As you can see, we are passing in the Disqus Comment ID in a POST of this WebApi Controller and from there checking creating a new Activity record via the Kentico API to save this activity for the current Contact. I am also treating it as a conversion for Web Analytics purposes. The last code block is optional, but it made sense to me to treat it as a conversion.

 

ProTip: There can be only one parameter to the Post method that is tagged with the [FromBody] attribute. Read why here.

 

 

Step 4: Next we need to add a few references to our CMSApp_MVC project so that the above code compiles. Add a reference in that project to the following files in the Lib folder of your Kentico 8.1 install.

 

  • CMS.Localization.dll
  • CMS.OnlineMarketing.dll
  • CMS.WebAnalytics.dll
  • CMS.WebApi.dll

 

 

Step 5: The last piece of code we need to modify is to the existing file that Kentico provides WebApiConfig.cs. This file should be in the App_Start directory. It should be pretty much exactly the same except for the guts of the static Register method. There we have to simply add the ApiControllerManager line, or you can just copy and paste the whole class in that file that I have below.

The special ApiControllerManager  line is the magic that tells the Kentico specific WebApi route registration to also register our custom LogDisqusCommentController class and make it available at  ~/cmsapi/logindisquscomment endpoint URL route.

 

 

using System.Web.Http;
using CMS.WebApi;
using CMS.Mvc.Controllers;

namespace CMS.Mvc
{
   
///


    /// Class providing manipulation with the application API routes.
   
///

    public static class WebApiConfig
   
{
       
///
        /// Registers the specified config.
       
///

        ///
The http configuration
       
public static void Register(HttpConfiguration config)
        {
           
// Uncomment if you want to use your own URL like /api/{controller} instead of /cmsapi ....
            //config.Routes.MapHttpRoute(
            //     name: "MyAPI",
            //     routeTemplate: "api/logdisquscomment",
            //     defaults: new { controller = "logdisquscomment", }
            //     );
           
            // Register the controller type so that CMS.WebApi.WebApiModule knows to load your type
            // This will now put your route to "cmsapi/{controller}"
           
ApiControllerManager.Current.Register(typeof(LogDisqusCommentController));
        }
    }
}

 

 

Step 6: Rebuild the CMSApp_MVC project and make  sure everything compiles and deploys correctly to the bin directory of the main CMS project that holds the Kentico site. If you don’t see the datestamp update on ~/bin/CMSApp_MVC.dll to the same time you built the CMSApp_MVC project, add a reference to CMSApp_MVC in your KenticoCMS project. I think that by default it should be already referenced though.

 

 

Up Next

Having fun yet ? Excited about the use of WebApi with Kentico ? I know I was when I started reviewing all of this.

Quick recap: I have introduced how to install Disqus on your blog for blog post comments. I have also shown you how to use the new MVC / WebApi project that comes in the Kentico 8.1 solution. Up next we connect the dots. Continue reading part two of How to Connect Disqus Comments to Kentico EMS Activity Tracking to complete the solution.