Last active
September 26, 2016 08:06
-
-
Save daniiiol/3efc4c0f343a8bf68b016b5fc37e6445 to your computer and use it in GitHub Desktop.
Sitecore Client Tracker (SC 8.2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ComponentModel.DataAnnotations; | |
public class EventModel | |
{ | |
/// <summary> | |
/// Name of the page event to be registered. | |
/// </summary> | |
[Required] | |
public string EventName { get; set; } | |
/// <summary> | |
/// Unique identifier of the page event. | |
/// </summary> | |
public string DefinitionId { get; set; } | |
/// <summary> | |
/// Unique identifier of the page, datasource item or media asset containing the page event. | |
/// </summary> | |
[Required] | |
public string ItemId { get; set; } | |
/// <summary> | |
/// Custom data or other information related to the page event. | |
/// For example, in the Experience Profile the data field is used to retrieve search keywords | |
/// for search page events and campaign IDs for campaign page events. | |
/// </summary> | |
public string Data { get; set; } | |
/// <summary> | |
/// Text that describes the page event in a readable format. This text can be an error message or an information message. | |
/// </summary> | |
public string Text { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sample.Utils.Helper = { | |
postEvent: function ($eventName, $pageId, $dataTopic, $dataText) { | |
var postData = "EventName=" + $eventName + "&ItemId=" + $pageId + "&Data=" + $dataTopic + "&Text=" + $dataText; | |
var xhttp = new XMLHttpRequest(); | |
xhttp.onreadystatechange = function () { | |
if (this.readyState === 4 && this.status === 200) { | |
// if I like to change the world after a succeeded request... | |
} | |
}; | |
xhttp.open("POST", location.protocol + '//' + location.hostname + "/Analytics/Tracker/Events", true); | |
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
xhttp.send(postData); | |
}, | |
postOutcome: function ($outcomeDefinitionId) { | |
var postData = "OutcomeDefinitionId=" + $outcomeDefinitionId; | |
var xhttp = new XMLHttpRequest(); | |
xhttp.onreadystatechange = function () { | |
if (this.readyState === 4 && this.status === 200) { | |
// if I like to change the world after a succeeded request... | |
} | |
}; | |
xhttp.open("POST", location.protocol + '//' + location.hostname + "/Analytics/Tracker/Outcomes", true); | |
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
xhttp.send(postData); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void Application_PostAuthorizeRequest() | |
{ | |
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ComponentModel.DataAnnotations; | |
public class OutcomeModel | |
{ | |
/// <summary> | |
/// The Item ID of the outcome definition item in the Marketing Control Panel. | |
/// </summary> | |
[Required] | |
public string OutcomeDefinitionId { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RegisterWebApiRoute | |
{ | |
public void Process(PipelineArgs args) | |
{ | |
var config = GlobalConfiguration.Configuration; | |
config.Routes.MapHttpRoute("DefaultApiRoute", | |
"api/{controller}/{id}", | |
new {id = RouteParameter.Optional}); | |
config.Routes.MapHttpRoute("DefaultAnalyticsRoute", | |
"analytics/{controller}/{action}/{id}", | |
new { id = RouteParameter.Optional }); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Web.Http; | |
using System.Web.Http.ModelBinding; | |
using Sitecore.SharedSource.Api.Models.Events | |
using Sitecore.SharedSource.Api.Models.Outcomes; | |
using Sitecore.Analytics; | |
using Sitecore.Analytics.Data; | |
using Sitecore.Analytics.Outcome.Extensions; | |
using Sitecore.Analytics.Outcome.Model; | |
using Sitecore.Diagnostics; | |
namespace Sitecore.SharedSource.Api.Controllers.Analytics | |
{ | |
public class TrackerController : ApiController | |
{ | |
private readonly bool _analyticsActive; | |
public TrackerController() | |
{ | |
_analyticsActive = IsAnalyticsActive(); | |
} | |
private static bool IsAnalyticsActive() | |
{ | |
if (!Tracker.Enabled) | |
{ | |
return false; | |
} | |
if (Tracker.Current == null) | |
{ | |
Tracker.StartTracking(); | |
} | |
return Tracker.Current != null && Tracker.Current.Session != null && Tracker.Current.Session.Interaction != null && Tracker.Current.Session.Interaction.CurrentPage != null; | |
} | |
[HttpGet] | |
public HttpResponseMessage Goals() | |
{ | |
return !_analyticsActive ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new StringContent("Analytics Tracker is disabled") } : new HttpResponseMessage(HttpStatusCode.NoContent); | |
} | |
[HttpPost] | |
public HttpResponseMessage Goals(EventModel value) | |
{ | |
return Events(value); | |
} | |
[HttpPost] | |
public HttpResponseMessage Outcomes(OutcomeModel value) | |
{ | |
try | |
{ | |
if (!ModelState.IsValid) | |
{ | |
return CreateInvalidModelResponse(ModelState); | |
} | |
if (!_analyticsActive) | |
{ | |
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new StringContent("Analytics Tracker is disabled") }; | |
} | |
var outcomeId = Sitecore.Data.ID.NewID; | |
var outcomeDefinitionId = Sitecore.Data.ID.Parse(value.OutcomeDefinitionId); | |
var contactId = Sitecore.Data.ID.Parse(Tracker.Current.Contact.ContactId); | |
var outcome = new ContactOutcome(outcomeId, outcomeDefinitionId, contactId); | |
Tracker.Current.RegisterContactOutcome(outcome); | |
return new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent("Outcome registered.") }; | |
} | |
catch (Exception ex) | |
{ | |
Log.Error("Cannot register outcome", ex); | |
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Exception occured.") }; | |
} | |
} | |
[HttpPost] | |
public HttpResponseMessage Events(EventModel value) | |
{ | |
try | |
{ | |
if (!ModelState.IsValid) | |
{ | |
return CreateInvalidModelResponse(ModelState); | |
} | |
if (!_analyticsActive) | |
{ | |
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new StringContent("Analytics Tracker is disabled") }; | |
} | |
PageEventData pageData; | |
Guid definitionIdGuid; | |
if (!string.IsNullOrEmpty(value.DefinitionId) && Guid.TryParse(value.DefinitionId, out definitionIdGuid)) | |
{ | |
pageData = new PageEventData(value.EventName, definitionIdGuid); | |
} | |
else | |
{ | |
pageData = new PageEventData(value.EventName); | |
} | |
Guid itemIdGuid; | |
if (Guid.TryParse(value.ItemId, out itemIdGuid)) | |
{ | |
pageData.ItemId = itemIdGuid; | |
} | |
pageData.Data = value.Data; | |
pageData.Text = value.Text; | |
var interaction = Tracker.Current.Session.Interaction; | |
interaction.CurrentPage.Register(pageData); | |
return new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent("Goal/Event registered.") }; | |
} | |
catch (Exception ex) | |
{ | |
Log.Error("Cannot register event", ex); | |
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Exception occured.") }; | |
} | |
} | |
private HttpResponseMessage CreateInvalidModelResponse(ModelStateDictionary modelState) | |
{ | |
var allErrors = modelState.Values.SelectMany(v => v.Errors); | |
foreach (var modelError in allErrors) | |
{ | |
Log.Warn(string.Format("Invalid Data Model recieved: {0}", modelError.ErrorMessage), modelError.Exception); | |
} | |
return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Invalid Data Model") }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment