Skip to content

Instantly share code, notes, and snippets.

@ezlateva
Created February 22, 2017 18:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezlateva/559f138818e2a0cec9de6f7b27c7b153 to your computer and use it in GitHub Desktop.
Save ezlateva/559f138818e2a0cec9de6f7b27c7b153 to your computer and use it in GitHub Desktop.
A custom processor for the Sitecore.Analytics ParseReferrer pipeline, which is able to parse keywords from url fragments (ex. https://www.google.com/#q=test)
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;
namespace Hedgehog.SitecoreExtensions.Pipelines.ParseReferrer
{
using Sitecore.Analytics.Pipelines.ParseReferrer;
using Sitecore.Collections;
using Sitecore.Diagnostics;
using Sitecore.Extensions.StringExtensions;
using Sitecore.Xml;
public class ParseCustomSearchEngine : ParseReferrerBaseProcessor
{
private readonly SafeDictionary<string, string> map = new SafeDictionary<string, string>();
public virtual void AddHostFragmentName(XmlNode configNode)
{
Assert.ArgumentNotNull(configNode, "configNode");
string hostname = XmlUtil.GetAttribute("hostname", configNode);
string fragmentName = XmlUtil.GetAttribute("fragmentname", configNode);
try
{
map[hostname] = fragmentName;
}
catch (Exception exception)
{
Log.Error("Could not register host or fragment name. Host: " + hostname + ", FragmentName: " + fragmentName, exception, this);
}
}
public override void Process(ParseReferrerArgs args)
{
Assert.ArgumentNotNull(args, "args");
foreach (KeyValuePair<string, string> current in map)
{
string key = current.Key;
string value = current.Value;
if (ParseKeywordsFromFragment(args, key, value))
{
args.AbortPipeline();
break;
}
}
}
private bool ParseKeywordsFromFragment(ParseReferrerArgs args, string hostName, string fragmentName)
{
Uri urlReferrer = args.UrlReferrer;
string dnsSafeHost = urlReferrer.DnsSafeHost;
if (dnsSafeHost.IndexOf(hostName, StringComparison.CurrentCultureIgnoreCase) < 0)
{
return false;
}
// grab full url instead of just query string
string text = urlReferrer.OriginalString;
if (string.IsNullOrEmpty(text))
{
return false;
}
int fragmentIndex = text.IndexOf("#", StringComparison.InvariantCulture);
if (fragmentIndex >= 0)
{
text = text.Mid(fragmentIndex + 1);
}
int valueStartIndex = text.IndexOf('=');
if (valueStartIndex >= 0)
{
if (text.Left(valueStartIndex) == fragmentName)
{
string keywords = text.Mid(valueStartIndex + 1);
string decodedKeywords = HttpUtility.UrlDecode(keywords);
if (decodedKeywords != null)
{
keywords = decodedKeywords.Trim();
}
if (!string.IsNullOrEmpty(keywords))
{
args.Interaction.Keywords = keywords.ToLowerInvariant();
}
}
}
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment