Tracking PDF Downloads in Google Analytics in a Sitecore Website

1 Comment

Hello my dear Sitecore Family,

Firstly, Thank you so much for your response on my last post — how to Configure Google Analytics for a Sitecore Website via Twitter and Email. It inspired my to write more on the connecting yet quite useful topic. In case you missed the last post, check it out here: http://varunvns.wordpress.com/2014/09/22/configuring-google-analytics-for-a-sitecore-website/

Today, lets look at how to track PDF downloads in Google Analytics.

  • Basic understanding of Tracking PDF Downloads in Google Analytics:

There are two ways in which we can track them:

  1. As a Virtual PageView
  2. As an Event.

But logically, I feel that tracking a PDF download as an Event is better – still choice is yours, and we will also discuss how to track it as a virtual PageView if required.

How can we configure this?

What we need to do is, we need to put the Google Tracking code in the link of PDF, so that whenever it is clicked, it sends the required information to Google. This information is inturn available to us via Google Analytics.

A sample given by Google for the same is as follows:


<a href="#" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);">Play</a>

  • Basics of Configuring and Tracking PDF Downloads in Google Analytics:

We will first discuss how to track PDF Downloads as events in Google Analytics. By the end of the post, we will also discuss a few changes, so that we can configure PDF downloads as a Virtual Pageview. As with the case of Configuring Google Analytics, we can do this in one of the two ways – either using Classic Google Analytics (ga.js) or using Universal Google Analytics (analytics.js)

Still, we need to make sure that Google has already mentioned, to upgrade to Universal Analytics from Classic Analytics. So its good to use that.

Add-Universal-Analytics

 

Pre-requisites:

  1. Google Analytics must be configured in our website.
  2. Media.RequestExtension in our web.config is not set to ashx (because, in that case, your PDF will have an extension of .ashx in the HTML and if so, then how can we append the Google tracking code to it. (http://sitecoreblog.patelyogesh.in/2013/09/sitecore-media-url-remove-ashx-extension.html)

Events Classic Google Analytics (ga.js)

There is a nice post written by Mr. Mortaza Kamal Nourestani, to track PDF Downloads in Sitecore for Classic Google Analytics – http://nourestani.wordpress.com/2012/06/12/how-to-track-downloads-in-google-analytics/

So its a great thanks to him for this.

Events Universal Analytics (analytics.js)

A small piece of code written by me, inspired by Mr. Mortaza.


<script type="text/javascript">
if (typeof jQuery != 'undefined') {
jQuery(document).ready(function ($) {
var filetypes = /\.(pdf)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
jQuery('a').each(function () {

var href = jQuery(this).attr('href');
if (href) {

if (href.indexOf('?') != '-1') {
href = href.substring(0, href.indexOf('?'));
}
if (href.match(filetypes)) {
jQuery(this).click(function () {
//var ga = ga || [];
var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
var filePath = String(href);
var filename = filePath.replace(/^.*[\\\/]/, '')
ga('send', 'event', 'PDF-Downloads', filename, document.URL);
if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function () {
location.href = baseHref + href;
}, 200);
return false;
}
});
}
}
});
});
}
</script>

Both the above code snippets, do the same thing, — find the extension “PDF” and append the Google Analytics Event Tracker code into it. Thus, whenever the PDF link is clicked — the PDF is opened or downloaded — information is gathered by Google and shown to us.

 

Basic Steps:

  1. Make sure that Google Analytics is Configured for the current Sitecore Site. In case it isn’t follow this article to configure it – http://varunvns.wordpress.com/2014/09/22/configuring-google-analytics-for-a-sitecore-website/
  2. Create a Sublayout in our Sitecore Solution.
  3. Copy one of the above given code (preferably Universal Analytics) to the Sublayout.
  4. Statically bind the Sublayout to all (one or more main layouts of the Sitecore Site. (http://varunvns.wordpress.com/2014/07/03/sitecore-beginner-static-and-dynamic-binding/)
  5. Upload a test PDF and link it to one of your Sitecore content item. (I haven’t checked, what would happen if we have upload as ashx you can check and definitely let me know. But better check the pre-requisite above.)
  6. Open any page with a PDF link.
  7. When the page load completes, view the Page Source.
  8. Search for the PDF link (anchor tag using which the PDF is linked)

These are the simple basic steps, which would make it work just fine. They will be displayed in a Category called PDF-Downloads, as that’s what we have mentioned in the code above.

Now, lets consider a case, wherein we have different PDFs for different use and want to configure them category wise in Google Analytics. But before that, lets first understand something.

PDF-Downloads-GA-Understanding

So now, if we want to categorize the PDFs further based on need or Client requirement and as we said in the beginning of the post, if we want to configure it as a virtual PageView instead of Event Tracking on the fly, we can do that too. Lets see how.

Advanced Steps:

  1. Make a section in Global Sublayouts (which is shared between all the sites in our solution) and lets create a Sublayout GA-PDFDownloads.
  2. Copy the  Universal Analytics code given above with just one line of change — adding Properties instead of Hit Type and Category as in the screenshot below:PDF-Downloads-Sublayout-code
  3. Statically bind the Sublayout to all (one or more main layouts of the Sitecore Site. (http://varunvns.wordpress.com/2014/07/03/sitecore-beginner-static-and-dynamic-binding/)
  4. In the Template of HomePage of the website or in a Global Settings Section template of a site, create two fields to store Data about Google Analytics PDF Downloads.PDF-Downloads-Template-Sections
  5. Add the field values in the items. PDF-Downloads-Item-Values6.  In the code behind of the Sublayout, initialize the Properties and in the Page_Load function write a code to fetch their values as below:PDF-Downloads-Sublayout-code-behind

 

Want the code? Well, here it is!

<script type="text/javascript">
 if (typeof jQuery != 'undefined') {
 jQuery(document).ready(function ($) {
 var filetypes = /\.(pdf)$/i;
 var baseHref = '';
 if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
 jQuery('a').each(function () {

 var href = jQuery(this).attr('href');
 if (href) {

 if (href.indexOf('?') != '-1') {
 href = href.substring(0, href.indexOf('?'));
 }
 if (href.match(filetypes)) {
 jQuery(this).click(function () {
 //var ga = ga || [];
 var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
 var filePath = String(href);
 var filename = filePath.replace(/^.*[\\\/]/, '')
 //ga('send', 'event', 'PDF-Downloads', filename, document.URL);

 ga('send', '<%= GoogleAnalyticsHitType %>', '<%= GoogleAnalyticsCategory %>', filename, document.URL);

 if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
 setTimeout(function () {
 location.href = baseHref + href;
 }, 200);
 return false;
 }
 });
 }
 }
 });
 });
 }
</script>
public string GoogleAnalyticsHitType { get; set; }
public string GoogleAnalyticsCategory { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
Item SettingsItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.RootPath + Sitecore.Context.Site.StartItem + "/Settings");

//Google Analytics Tracking can either be Event Tracking or Virtual PageView Tracking - better is Event Tracking
//If "Google Analytics Track PDF Downloads" field is empty in the Settings Item, then consider it as Event Tracking by default
if (SettingsItem != null && !String.IsNullOrEmpty(SettingsItem["Google Analytics Track PDF Downloads"]))
GoogleAnalyticsHitType = SettingsItem["Google Analytics Track PDF Downloads"];
else
GoogleAnalyticsHitType = "event";

//If "Google Analytics PDF Category" field is empty in the Settings Item, then consider "PDF-Downloads" as the category by default
if (SettingsItem != null && !String.IsNullOrEmpty(SettingsItem["Google Analytics PDF Category"]))
GoogleAnalyticsCategory = SettingsItem["Google Analytics PDF Category"];
else
GoogleAnalyticsCategory = "PDF-Downloads";
}

Happy Tracking PDF Downloads in Google Analytics! :)

Configuring Google Analytics for a Sitecore Website

2 Comments

Hello Sitecore Family,

A few weeks back, I had a nice small task to work on, the title of the above post – Configuring Google Analytics for a Sitecore Website. Lets see how easy it can be to configure. Yes, you are right,  the first question that would come to the mind of any Sitecorian, is why Google Analytics and not Sitecore DMS. That proves you are a Sitecorian — but again sometimes, the requirement is such – such as in my case, where the client was using Google Analytics for a number of other sites of his.

So he also wanted the Analytics of the current site to be there in Google Analytics – So be it!

 

How does Google do to show us the Analytics data?

Basically, we need to copy a Javascript from Google into all our pages along with the Tracking Code generated by Google for us, so that whenever the page loads on the client side, it send its related data back to Google and finally we can see and analyze it.

 

Configuring Google Analytics, is as simple for Sitecore as for any other Site – so lets divide it into two steps to understand it better:

  • Basics of Google Analytics:

For a beginner who wants to know how to configure Google Analytics, the steps are as given in this link – https://support.google.com/analytics/answer/1008080?hl=en

There are two ways in which Google does it and we can choose any one of them.

Google’s Classic Analytics code (ga.js)

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Google’s Universal Analytics code (analytics.js)

<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');

</script>
<!-- End Google Analytics -->

As of now, if you are adding Google Analytics to a website, Google recommends to add the Universal Analytics code.

Add-Universal-Analytics

  •  Basics of Configuring Google Analytics in Sitecore:

Basic/Beginner Steps:

  1. Create a Sublayout in our Sitecore Solution.
  2. Copy one of the above given code (preferably Universal analytics) to the Sublayout.
  3. Statically bind the Sublayout to all (one or more) main layouts of the Sitecore Site.(http://varunvns.wordpress.com/2014/07/03/sitecore-beginner-static-and-dynamic-binding/)
  4. Replace the UA-XXXX-Y with the Google Analytics code for the client website. The client might have given you a code starting with UA. If in case he hasn’t ask him for it. (how to get the Google Analytics code:  https://support.google.com/analytics/answer/1008080)
  5. Let’s Open our page/s in browser and check in Realtime Tab on the left side to see the data that appears.

This is in normal case that any developer would do.

Now lets consider a case, that we have a multi-site Sitecore Solution. As per the best practices of Programming, we would definitely want to reuse the code.

Advanced Steps:

  1. Make in a section of Global Sublayouts (which would be shared for all the sites in the solution), let’s create a Sublayout for Google Analytics.
  2. Copy the Universal Analytics code to the Sublayout, with just one change – adding a Property to fetch the Google Analytics code on runtime – as below screenshot:Add-Universal-Analytics-dynamic-code
  3. Statically bind the Sublayout to all (one or more) main layouts of the Sitecore Site.(http://varunvns.wordpress.com/2014/07/03/sitecore-beginner-static-and-dynamic-binding/)
  4. In the Template of HomePage of the website or in a Global Settings Section template of a site (whichever we feel we are comfortable with, as per the Site structure – nothing is good or bad, right or wrong, Sitecore is so good in architecture, that we can configure as per our requirement and that thing becomes right!) create a field to store the Google Analytics code of a website.Google-Analytics-Code-Template-Structure
  5. Add the code to the specified field of the corresponding item.Google-Analytics-Code-updatead-in-Item
  6. In the code behind of the Sublayout, write the function to fetch the value of the Google Analytics code, from the item.Google-Analytics-Code-Behind

Oh, you want to check the code? — Here it is!

<!-- Google Analytics -->
<script>
 (function (i, s, o, g, r, a, m) {
 i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
 (i[r].q = i[r].q || []).push(arguments)
 }, i[r].l = 1 * new Date(); a = s.createElement(o),
 m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
 })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

 ga('create', '<%= GaTrackingCode %>', 'auto'); // Replace with our property ID.
 ga('send', 'pageview');

</script>
<!-- End Google Analytics -->


protected string GaTrackingCode { get; private set; }

protected void Page_Load(object sender, EventArgs e)
{
Item SettingsItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.RootPath + Sitecore.Context.Site.StartItem + "/Settings");

GaTrackingCode = SettingsItem["Google Analytics Code"];
}

Happy Tracking data of our Sitecore Site in Google Analytics! :)

My First Windows App – SitecoreVideos

Leave a comment

Hi Sitecore Lovers,

I was trying my hands on Windows Apps development, thanks to my friend and colleague Nikki Punjabi who has developed a number of apps.

As it was my first, I made one using the AppStudio by provided to us by Microsoft — a real great way of making an app.

The reason why I am referring to the Sitecore community in this post of a Windows App, is because I think that the community would be interested in using this app. The name of the App is SitecoreVideos. (Aha! I can see a smile on your face!) Yes, exactly, as the name suggests, it finds videos on Sitecore shared by some really helpful Youtube channels.

Its available for Windows Phone 8.1 and Windows 8 Store.

Oh, so you want to know how to try it?

Just go to your Windows Store in your Windows Phone or Windows 8 Store, and search for “Sitecore”. You will find it in the search results.

Do try it and let me know if you like it.

And I suppose, with the Sitecore Symposiums going on, its the right time to use such it.

2

Happy Watching Sitecore Videos in Style!

Page Editor Experience – Add a Thumbail Image to our Presentation Component

Leave a comment

This tip, was given to me by my senior and colleague Nilesh Thakkar. He blogs about his Sitecore Journey, at http://sitecorejourney.nileshthakkar.com/

He said, some things are not compulsory to be done, but good if they are done to make it easy for the client. Like say add a thumbnail image to your presentation component. How? Lets have a look.

We already know “A Picture is worth thousand words” so yes, we got to agree upon what Nilesh Thakkar says! So, lets see, how it can be done and how helpful can it be for our clients/users.

Setting up a plot:

Lets for example say, we have a Blog to manage in Sitecore. We have already created a few presentation components for various sections of the page as below.

Header Section:

  1. Blog Header
  2. Blog Search

Left Sidebar Section:

  1. Blog Roll
  2. Recent Comments
  3. Recent Posts
  4. Featured Posts
  5. etc..

Main Content Section:

  1. Blog Article Summary
  2. Blog Article
  3. Article Share Tools
  4. Blog Comments

Why Add an image to Presentation Component?

For any Page Editor user, it might definitely be very easy if there is an image, depicting what that particular presentation component does.

Now, lets say, a user is configuring a Blog Landing page, and is confused between two presentation components — Blog Article Summary and Blog Article. So he/she can add it to a page, configure a datasource to it, and see how it looks. We developers always unit test various scenarios whenever we develop some code, to make sure it works well. So instead of, the page editor user has to configure and check, if we add an image of that component while testing, wont it be a great idea?

How to add it?

Let’s say, the Blog Article Summary component looks like as below:

Blog-Summary

while the Blog Article Component Looks as below:

Blog-Article-Complete

To configure its thumbnail lets go to the Presentation Component (sublayout in this case) in the content tree.

Make sure that Standard values checkbox is checked in View Tab of the ribbon.

Sitecore-Ribbon-View-Tab-Standard-Values

Go to the Appearance Section and find the Thumbnail field in it.

Content-Item-Appearance-Section-Thumbnail-Field

Upload an appropriate Thumbnail image, suitable to the component as well as that makes it recognizable while adding it through the page editor.

Blog-Summary-Thumbnail

Save the item, and now, lets go to the Page Editor mode and click the Components button.

Click-Components-Button-Add-to-Here

Lets click on “Add to here” so that Select a Rendering dialog opens.

Select-a-rendering

As we see above, the Blog Article Summary component is self explanatory, it becomes pretty easy for the Page Editor users to identify and select it if they want to use it.

So simple it is to make someone’s life easy, by applying a very small effort,  in a right direction. And according to me, that is what a developer is for — to make the life of normal people easy, in whatever way possible, by making great technology.

Happy Sitecoring! :)

Placeholder Settings – Empower your Page Editor Users – Part – 2

Leave a comment

In the part one of this post, we saw what a Placeholder Setting is and why is it good to use Placeholder Settings in architecturing of our Sitecore Projects. In case you missed it, have a look at it here –  Placeholder Settings – Empower your Page Editor Users How to Setup Placeholder Settings? Suppose we are developing a Site with a blog. So lets configure various elements considering that blog has the following  layout:

Blog-Site-Layout

Various presentation components that we need for the blog are as follows:

Blog-related-Sublayouts

Next, lets create a Placeholder Setting item. At the location /sitecore/layout/Placeholder Settings right-click and say insert Placeholder.

Creating-Placeholder-Setting

Now, we can have the following components in our left Sidebar:

  1. Blog Roll
  2. Recent Comments
  3. Featured Posts
  4. Recent Posts
  5. Subscribe to Blog
  6. Blog Stats
  7. Blog Authors
  8. Blog Archive

So lets add them in Allowed Controls of the setting.

Blog-Placeholder-Settings-Item

Please note, that in the above screenshot, we haven’t specified any Placeholder Key. This means, it is a Data-Template Placeholder Setting. So, we need to add this setting to the Presentation Details all the blog related items (ideally to blog related template’s standard values).

[Moving a step back from our configuration step, lets discuss why we used a Data-Template specific setting, and how beneficial can it be in our case. The advantage of making a global Placeholder Setting, is that we have the Placeholder Key already specified in the Setting and we do not need to add it to the Presentation Details of that of the item or template standard values. Sitecore identifies, where to apply it, based on the Key that is specified in the Setting. But, its good to use it only if the site follows a single main layout.

Taking our current case of that of the Blog Section of a Site, we are using Sidebar with the key leftSidebar. Lets say, we make this setting as Global, and we have the same key in different layouts for other Site Sections (say Our Services Section) , then these Blog related Presentation Components, will be available for Page Editor users, to be added  in Our Services Section, which is conceptually wrong. So to avoid such cases, whenever we have multiple layouts section-wise its always good to create Data-Template specific placeholder settings. Also, in a case where we have a website setup, and we found later that Placeholder Settings could be useful for us to use, its preferable to make it Data-Template specific instead of Global Placeholder settings to avoid major level of testing into it. ]

Coming back to our How to configure Placeholder Settings, adding the Sidebar Placeholder Setting item, to the Presentation Details of the Blog Section Template’s Standard values and specifying the Placeholder Key as “leftSidebar”.

Data-Template-Specific-Placeholder-Settings

Once added, it can be seen in the presentation details of every item of that template and when we can click on it, we can see the controls that can be added to the specific Placeholder Key, by our Page Editor Users.

Creating-Placeholder-Setting-2

Once this is done, we can start adding components to the left Sidebar. Say we have added Blog Archive.

Left-Sidebar-Architecture

And some of the following (Recent Posts and Featured Posts) might be added by client in future, so he/she doesn’t need to depend on us, or come to us to get it added. Their Page Editor users can do the same as follows:

Left-Sidebar-Blog-Roll

As we want to add a new Component, that of Recent Posts, above this blog roll component, we click on the Add to here button above it. Note that, when we hover over the Add to here button, here’s what we see:

Add-to-here-onHover

The Placeholder’s name is replaced by the Placeholder Setting’s name. And now, on clicking it, we get all the allowed controls.

Allowed-Controls-Placeholder-Settings

 

I’ll Select the Recent Posts Component, and that’s how it looks on my page, in Left Sidebar.

Recent-Posts-Above-Blog-Roll

Hope you enjoyed the couple of posts on Placeholder Settings? Lets make use of various things, simple in use yet very powerful features and make situations for our clients and stakeholders easy!

Good Reads: http://www.sitecore.net/Community/Technical-Blogs/Maximizing-Usability/Posts/2012/08/The-Power-of-Placeholder-Settings.aspx

Happy Sitecoring! :)

Placeholder Settings – Empower your Page Editor Users

1 Comment

While binding the Content with its presentation, we have two terminologies, Static Binding and Dynamic Binding. Know more..

In this post, we’ll see how Sitecore adds one more level of abstraction over binding Content with its Presentation Components, empowering both – the Developer as well as the Page Editor user – and moving to a simple and very effective solution. I have added this to my list of reasons for Why I Love Sitecore. For anything that we do, we have 3 questions in our What, Why & How? So lets start getting answers for these questions.

What are Sitecore Placeholder Settings?

A Placeholder setting is linked to a Placeholder key and adds a level of abstraction while binding a presentation component with the corresponding content.  In a Placeholder Settings item, we give it a name so that it can be easily identified — for which specific location would it be made — and specify a number of sublayouts and/or renderings in it, which are appropriate according to the design changes of the current website. They are of two types:

  1. Global Placeholder settings
    • Placeholder Key is specified in the Settings item.
    • Does not need to be attached to Presentation details of various Template’s Standard Values or that of items.
    • Sitecore by default identifies if the placeholder key mentioned here is present on the page, and allows us to add the controls allowed here to be added to the page.
  2. Data Template-specific Placeholder settings
    • Placeholder Key is Template specific.
    • Placeholder Key needs to be specified while adding it to the Presentation Details of Template’s Standard values or that of item.

Why Sitecore Placeholder Settings?

  1. It empowers the Page Editor users, to make the necessary design changes at required locations, without being dependent on the Developer.
  2. It relieves the Developer from the hassle of going back to the client site, just to make simple design level changes.
  3. The components that can be added at any location in a website, are specified in the allowed controls of it. So the Page Editors  can select the ones out of them. This not only helps them in selection for which component they want, but also makes sure that an inappropriate component is not added to a location where it should not be. (Lets say, in case of a blog, we have a left sidebar, with components of Recent Posts & Recent Comments. We can have a Placeholder setting, for left sidebar with other allowable components along with the above, say Blog Roll, Blog Archives and link it with the data template to avoid a component of main blog post to be added to the left sidebar)
  4. Ideally, Placeholder settings should be configured before various presentation components are bound to its corresponding content. But in case that’s not done, they can be easily plugged-in whenever we want to, with a little effort, by understanding the broad-level architecture of the site.

In part 2 of this post, lets see how to configure Placeholder Settings.

 

Happy Sitecoring! :)

Older Entries

Follow

Get every new post delivered to your Inbox.

Join 402 other followers

%d bloggers like this: