Site icon Horizontal Blog

Personalize Sitecore DMS using Referring Sites

Sitecore DMS does provide us with a lot of out of the box conditions which helps the content authors to personalize their websites. One of the most requested condition is “Referring Sites”. This post is aimed at writing a custom Sitecore DMS Condition which helps in personalizing the website using Referring Sites.

Create a Condition in Sitecore

Write Code in Visual Studio

[sourcecode language=”csharp”]
using System.Web;
using Sitecore.Rules;
using Sitecore.Rules.Conditions;
namespace SampleSite.Code.Conditions
{
public class ReferringSiteCondition : StringOperatorCondition where T : RuleContext
{
#region Properties
public string ReferringSiteValue { get; set; }
#endregion

#region Methods
protected override bool Execute(T ruleContext)
{
bool ReturnValue = false;
bool FoundExactMatch = false;
bool FoundCaseInsensitiveMatch = false;
bool FoundContains = false;
bool FoundStartsWith = false;
bool FoundEndsWith = false;

string RuleValue = this.ReferringSiteValue ?? string.Empty;

if (!string.IsNullOrWhiteSpace(RuleValue))
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
//Populated with Referring Site HOST
string referrer = HttpContext.Current.Request.UrlReferrer.Host;

if (referrer == RuleValue)
{
FoundExactMatch = true;
FoundCaseInsensitiveMatch = true;
FoundContains = true;
FoundStartsWith = true;
FoundEndsWith = true;
}
else if (referrer.ToLower() == RuleValue.ToLower())
{

FoundCaseInsensitiveMatch = true;
if (referrer.Contains(RuleValue))
{
FoundContains = true;
}
if (referrer.StartsWith(RuleValue))
{
FoundStartsWith = true;
}
if (referrer.EndsWith(RuleValue))
{
FoundEndsWith = true;
}
}
else if (referrer.Contains(RuleValue))
{

FoundContains = true;
if (referrer.StartsWith(RuleValue))
{
FoundStartsWith = true;
}
if (referrer.EndsWith(RuleValue))
{
FoundEndsWith = true;
}
}
}
}

switch (base.GetOperator())
{
case StringConditionOperator.Equals:
ReturnValue = FoundExactMatch;
break;
case StringConditionOperator.NotEqual:
ReturnValue = !FoundExactMatch;
break;
case StringConditionOperator.CaseInsensitivelyEquals:
ReturnValue = FoundCaseInsensitiveMatch;
break;
case StringConditionOperator.NotCaseInsensitivelyEquals:
ReturnValue = !FoundCaseInsensitiveMatch;
break;
case StringConditionOperator.Contains:
ReturnValue = FoundContains;
break;
case StringConditionOperator.StartsWith:
ReturnValue = FoundStartsWith;
break;
case StringConditionOperator.EndsWith:
ReturnValue = FoundEndsWith;
break;
default:
ReturnValue = false;
break;
}

return ReturnValue;
}
#endregion
}
}
[/sourcecode]

Test the New Condition

Once you have compiled the code and Build your solution, In Page editor Personalize the component of your choice and look for the new referring site condition (Click Here for Image Reference)

In order for testing in your Local Environments, URL spoofing tool like Spoofy can be very handy

Should you have any questions, Please comment below

Exit mobile version