Step 2-1: Track all external links with a custom processor

This article is part of Sitecore How To: Track Exteral links with DMS series. Before starting with this step you need to be finished with Step 1: Save outgoing click to the DMS analytics database.

For this solution I want to measure all the outgoing link using the Analytics Database of Sitecore Digital Marketing System (DMS). Based on this data I want to create a report in the Sitecore Engagement Analytics that will show all outgoing clicks by page. I want to create a solution that rewrites all external links within rich-text fields and General Link fields. With this solution all external links on an existing website will be automatically rewritten and measured.

In this article I will create a solution for measuring outgoing links in the following steps:

  • Create a processor to rewrite all external links on the website.

Let get started!

Create the processor for rewriting external links

For the rewriting of the external links we are creating a Render Field Processor. This processor will fire for every field that is rendered. During this process we will rewrite the URL.

The easiest way to create a new processor is with the Visual Studio 2010  plugin Sitecore Rocks. One of the many things Sitecore Rocks does is creating Visual Studio Templates. These templates will help you extending Sitecore. Open your solution in VS2010 and add a new item. In the dialog window go to Sitecore –> Pipelines en selecteer Render Field Processor. Name the processor ExternalUrlReWriterProcessor.cs and click Add.

Sitecore custom processor

The Render Field Processor Template will generate two files for you; the ExternalUrlReWriterProcessor.cs and a  ExternalUrlReWriterProcessor.config.

 

Custom sitecore config processor

Modify the ExternalUrlReWriterProcessor class that all external URLs are rewritten to out /link.aspx page that we are going to create next. Below is my POC code. Please take notice of the comments and the TODO comments.

[code language=”csharp”]
public class ExternalUrlReWriterProcessor
{
public void Process([NotNull] RenderFieldArgs args)
{
// Do not modify output if the field is not a rich text field or general link
// or if the page is in page editor mode
if ((args.FieldTypeKey != “rich text” && args.FieldTypeKey != “general link”) ||
String.IsNullOrEmpty(args.FieldValue) ||
Sitecore.Context.PageMode.IsPageEditorEditing)
{
return;
}

//Check if URL is external link
if (args.FieldTypeKey == “general link”)
{
Sitecore.Data.Fields.LinkField linkField = args.GetField();
//Don’t change the link if it’s not a external link
if (linkField.LinkType != “external”)
return;

}
string fieldValue = args.Result.FirstPart;

string changedUrl = Regex.Replace(fieldValue, @”href=””(.*?)”””, delegate(Match match)
{
//Regex definition to check if URL contains HTTP or HTTPS (so it’s an external link)
Regex rgxExternal = new Regex(@”Regex rgxExternal = new Regex(@”(((http(s?))\://){1}\S+)”);”);

string orriginalUrl = match.Groups[1].Value.ToString();
if (rgxExternal.IsMatch(orriginalUrl))
{
//Rewrite the url to the redirect item
//TODO: Make the path configurable
return @”href=””/link.aspx?url=” + orriginalUrl + @””””;

}

return match.Value;
}, RegexOptions.Compiled);

args.Result.FirstPart = changedUrl;

}
}

[/code]

If you check your website all external links will be rewritten to /link.aspx?url=[EXTERNAL LINK]. Now let’s create the links.aspx and save the outgoing link information to the DMS Analytics database.

Test if it works

You can test if the solution is working on your website by testing the following functionalities

Action Expected result
Create a internal link in a rich-text field The link is not rewritten.
Create a external link in a rich-text field The link is rewritten to /link.aspx?url=[THE LINK]
Create a internal link in a general link field The link is not rewritten.
Create a external link in a general link field The link is rewritten to /link.aspx?url=[THE LINK]
Click a external URL The visitor is redirected to the external website.

Step 1: Save outgoing click to the DMS Analytics database

This step is the first of the series: How to track External Links with Sitecore DMS. In this step we are going to create a page (link.aspx) that will register the outgoing traffic into the Sitecore Analytics database and redirects the visitor to the external website.

Save the outgoing click information to the Analytics database

Create the custom page event

Open the content editor, go to /sitecore/system/Settings/Analytics/Page Events and create a Page event called External Link.

Under the Options field section select the IsSystem checkbox

 

We refer to the name of this Page Event Item when saving the outgoing link to the Analytics database.

Create the sublayout

Create a sublayout called LogExternalLink. In the Page_Load event add the code.

[code language=”csharp”]

protected void Page_Load(object sender, EventArgs e)
{
if (Tracker.IsActive)
{
bool trackClick = true;
//Check if outgoing traffic is generated within a visit of the site
if (Tracker.CurrentVisit.PreviousPage == null)
{
//The visit is a direct visit or from another website, don’t add this link to the analytics db.
//OPTIONAL; Log these links based on referrer url.
trackClick = false;
}

//Get linkUrl from querystring
string externalUrl = Request.QueryString[“url”];

//Check if link is set
if (!string.IsNullOrEmpty(externalUrl))
{
if (trackClick)
{
//Create PageEvent, the name must match Page Event item in Sitecore
PageEventData data = new PageEventData(“External Link”);
//Set PageEvent data
data.Text = string.Format(“Outgoing traffic to: {0}”, externalUrl); ;
data.DataKey = externalUrl;
data.Data = externalUrl;

//Add the event to the previouspage; that’s where the link is clicked
Tracker.CurrentVisit.PreviousPage.Register(data);
Tracker.Submit();
}
//Redirect visitor
Response.Redirect(externalUrl);
}
}

//Something not right here, send them back to the homepage
//TODO: Log Error or Warning
Response.Redirect(“/”);
}

[/code]

Based on your businesscase you could choose to create a handler. A handler will have less overhead.  If you create a Sublayout you could create a screen telling the visitor that there are leaving the website (for example like Facebook does).

Now create an item link underneath the website root and place the LogExternalLink sublayout that we just created on this item. This item will be the link.aspx page. All external links will be redirected and processed trough this page.

Test if it works

At this point we cannot test this part of the solution. Testing this solution is only possible if the tracking page (link.aspx) is referred from the website. We don’t want to  track URLs that are triggered from a direct request.

We will test this part of the solution after Step 2  of the series: How to track External Links with Sitecore DMS.

 

Sitecore How To: Track Exteral links with DMS

In this How To I’ll show you how to extend Sitecore to track outgoing links trough the Sitecore Digital Marketing System (DMS).

First of we start with creating a sublayout that saves the outgoing link clicks to the Analytics database. Next step is creating a solution for tracking the outgoing link. There are multiple solutions of tracking external links but in this series we are creating the following two solutions; one that tracks all outgoing links automatically (step 2.1) and the other solution where it´s possible to enable tracking for-each outgoing link (step 2.2)And off-course we finish with  report that will show you the most clicked outgoing links.

This how to is part of the series: How to track External Links with Sitecore DMS and contains the following steps:

  • Step 1: Save outgoing click to the DMS analytics database (status: finished, published)
  • Step 2: Two solutions for outgoing link tracking
    • Step 2.1: Measure alloutgoing links with a custom processor  (status: finished, published)
    • Step 2.2: Measure specific outgoing links by creating a custom external link fieldtype
      • Step 2.2.1: Creating the custom external link fieldtype (status: review, publishdate: 17/05/2012)
      • Step 2.2.2: Creating pageeditor support for the custom external link fieldtype (status: coding)
      • Step 2.2.2: Tracking the external links that need to be tracked (status: on hold)
  • Step 3: Creating the outgoing link report  (status: finished, published) 
And off-course all publishdates are subjected to changes ;=)

Want to receive a reminder when a new article is publish subscribe to the RSS feed, maillinglist (in the right sidebar) or follow us on @new_guid

Feel free to ask your questions in the comment form below.

NewGuid.net live

Today we are happy to announce that NewGuid.Net is online. Newguid.net will be a weblog about Sitecore Development and sharing knowledge.  At this point all articles on NewGuid are the combination of all the articles from the personal weblogs of; Mark van Aalst and Pieter Brinkman.

We are willing to crossposts Sitecore articles and have guest Authors on this blog. If you are interested in placing your article on NewGuid.net please contact us and we’ll be happy to publish it!

Stay tune on all the nice things happening on NewGuid:

  • Subscribe to our newletter (in the sidebar)
  • Subscribe our RSS feed
  • Follow us on Twitter: @new_guid

Happy developing,
Mark and Pieter

 

Sitecore Recognizes Exceptional Technical Community Leaders From Around the World

We want to congratulate and thank all Sitecore MVP’s of 2011!


MVPs Recognized for Active Community Involvement in Advancing Web Strategies

San Francisco – April 10, 2012 – Sitecore today announced the 2011 Sitecore Most Valuable Professionals (MVPs). The program recognizes exceptional technical community leaders who serve as catalysts for change and innovation.

Sitecore MVPs voluntarily share their passion and commitment to Web technology and encourage the objective exchange of knowledge .The Sitecore MVP Award celebrates the most active Sitecore community members from around the world who provide invaluable contributions by solving problems and discovering new ways to transform technology. The program offers MVPs a number of benefits including access to technical resources such as alpha versions of Sitecore software, first release modules and full access to the Sitecore Developer Network and download section, and invitations to major events.

“MVPs are technology experts who inspire others to learn and grow through active participation in the Sitecore technical community,” said Lars Nielsen, senior vice president, technical marketing, Sitecore.  “MVPs are not just about evangelizing Sitecore. They are passionate about improving technology and driving innovation and sharing their knowledge and real-world experiences at user groups, on blogs and on social channels. This year’s prestigious list represents individuals who share the same passion for technology and a willingness to help others innovate and advance the use of Web technology. It’s my pleasure to recognize their demonstrated commitment to the technology community worldwide.”

For 2011, fifty-two outstanding individuals were selected to be members of the program and honored with a Sitecore Most Valuable Professional (MVP) Award and are as follows:                                                                  

  • Adam Najmanowicz                           Cognifide
  • Alan Gallauresi                                   NavigationArts
  • Alexander Pfandt                               Digitaria, a JWT Company
  • Alistair Deneys                                   Next Digital
  • Amanda Shiga                                    Non-linear creations
  • Anders Dryer                                      Created
  • Andrew King                                      WEtap Media
  • Andy Uzick                                        FMC Technologies
  • Aren Cambre                                       Southern Methodist University
  • Arend van de Beek                             Suneco
  • Atsuo Aoki                                         Nextscape
  • Barend van der Hout                          eFocus
  • Ben Golden                                         Aware Web Solutions
  • Brent McLean                                     Paragon Consulting
  • Brian Beckham                                   Brainjocks
  • Charlie Turano                                    Hedgehog Development
  • Chris Williams                                     Cyberplex/CX Interactive
  • Colin te Kemple                                  Consultant
  • Daniel DeLay                                      Velir
  • Daniel Tobner                                     ecx.io austria GmbH  
  • Eric Leong                                          Avanade
  • Eric Nordberg                                     Aware Web Solutions
  • Eric Briand                                          Ergonet
  • Gabriel Boys                                       Velir
  • Glen McInnis                                      Non-linear creations
  • Jakob Leander                                     Avanade Denmark
  • Jason Hedlund                                    Aware Web Solutions
  • Jens Mikkelson                                    Inmento Solutions
  • Jeroen Speldekamp                             Suneco
  • Joacim Schiodtz                                  Cabana
  • Karina Apostolides                             Endava
  • Keiichi Hashimoto                              Sigma Consulting
  • Kern Nightingale                                Herskind Limited
  • Klaus Petersen                                    Alpha Solutions
  • Lars Erhardsen                                    CometPeople
  • Mark Ursino                                        Agency Oasis
  • Matt Hovany                                       The Revere Group
  • Max Teo Wee Kwang                         Avanade
  • Mike Edwards                                    Eduserv
  • Nick Hills                                            True Clarity
  • Nick Wesselman                                 Hanson Dodge Creative
  • Paul Caponetti                                    Verndale
  • Peter Iuvara                                         mindSHIFT
  • Remco van Toor                                  iQuality
  • Richard Hauer                                     5 Limes
  • Robert Jongkind                                 eFocus
  • Roger Norrlén                                     Mogul
  • Sean Kearney                                      Hedgehog Development
  • Sebastian Winslow                              Codehouse
  • Thomas Eldblom                                 Pentia
  • Troy Lüchinger                                   Namics
  • Vincent van Middendorp                   Evident

Sitecore MVP nominees undergo an evaluation process based on each nominee’s technical expertise and voluntary community involvement over the past year. All the nominations were reviewed by an independent panel of Sitecore employees from technical, product marketing and executive roles.  The panel considers the quality, quantity, and level of impact of the nominees’ contributions, in the areas of general technical advocacy, input via blogs and forums and content development.

Sitecore has more than 4,500 certified developers, and more than 10,000 active community participants.

About Sitecore

Sitecore redefines how organizations engage with audiences, powering compelling experiences that sense and adapt to visitors both online and in-person.

Sitecore’s leading Content Management System software is the first to cohesively integrate with marketing automation, intranet portal, e-commerce, web optimization, social media and campaign management technologies. This broad choice of capabilities enable marketing professionals, business stakeholders and information technology teams to rapidly implement, measure and manage a successful website and digital  business strategy. Businesses can now easily identify, serve and convert new customers with Sitecore’s Digital Marketing System, part of its encompassing Customer Engagement Platform.

Thousands of public and private organizations have created and now manage more than 32,000 dynamic websites with Sitecore including ATP World Tour, CA Technologies, Comcast, EasyJet, Lloyd’s of London, Heineken, Microsoft, Omni Hotels, Siemens, The Knot, Thomas Cook, Verizon and Visa Europe.

Media Contact:
Kim Pegnato, Sitecore
781-620-1729
kmp@sitecore.net