Skip to main content

Create a Custom Page View Event for Interactions

Create a custom page view event for interactions

Once the user visit with the website, Sitecore creates new contact into "[website_Xdb.Collection.Shard0].[xdb_collection].[Contacts]" or "[website_Xdb.Collection.Shard1].[xdb_collection].[Contacts]". Contact could be known or unknown.




 When the user will interact with the website all interactions will be saved into "[website_Xdb.Collection.Shard0].[xdb_collection].[Interactions]" or "[website_Xdb.Collection.Shard1].[xdb_collection].[Interactions]" for particular contact as you can see ContactId in Interactions table.


For each interaction, it is mandatory to have one event. All events you can see in the "Events" field inside the interaction table in JSON format.



In the event JSON, out of the box, the page view event looks like the below JSON:


In this case, if you want to create your custom PageViewEvent and want to add more fields then you can follow the below steps:

Create a Custom Facet Model
Create a class CustomPageViewEvent. I have given DefaultFacetKey as "
CustomPageViewEvent" and EventDefinitionId id you can give either the existing or create new event. I have added a new field like the Number field. 
  [Serializable]  
   [FacetKey(DefaultFacetKey)]  
   public class CustomPageViewEvent : Event  
   {  
     public CustomPageViewEvent(DateTime timestamp, Guid itemId, int itemVersion, string itemLanguage, string dataKey, string data, string number)  
      : base(EventDefinitionId, timestamp)  
     {  
       this.ItemId = itemId;  
       this.ItemVersion = itemVersion;  
       this.ItemLanguage = itemLanguage;  
       this.DataKey = dataKey;  
       this.Data = data;  
       this.Number = number;        
     }  
     public const string DefaultFacetKey = "CustomPageViewEvent";  
     public static Guid EventDefinitionId { get; } = new Guid("CD52B756-21B4-4028-8BA5-E981B8A96F95");  
     public string ItemLanguage { get; set; }  
     public int ItemVersion { get; set; }  
     public string Url { get; set; }  
     public string Number { get; set; }  
   }  
Register the Custom Facet Model
Create a CustomPageViewEventModel class to register your custom facet model.
  public static class CustomPageViewEventModel  
   {  
     public static XdbModel Model { get; } = BuildModel();  
     private static XdbModel BuildModel()  
     {  
       var modelBuilder = new XdbModelBuilder("CustomPageViewEventModel", new XdbModelVersion(1, 0));  
       modelBuilder.DefineEventType<CustomPageViewEvent>(true);  
       return modelBuilder.BuildModel();  
     }  
   }  
Deploy custom Facet model to XDB
In the console application, generate a JSON file of your model and paste it to the below two locations:

<x-connect root path>\App_data\Models
<x-connectroot path>\App_data\jobs\continuous\IndexWorker\App_data\Models
 class Program  
   {  
     static void Main(string[] args)  
     {  
       var serlizableModel = XdbModelWriter.Serialize(CustomPageViewEventModel.Model);  
File.WriteAllText(CustomPageViewEventCollectionModel.Model.FullName + ".json", serlizableModel); } }

Add Custom Facet Model to Configuration
Now create a patch file and paste the below code:
 <?xml version="1.0"?>  
 <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">  
  <sitecore>  
   <xconnect>  
    <runtime type="Sitecore.XConnect.Client.Configuration.RuntimeModelConfiguration,Sitecore.XConnect.Client.Configuration">  
     <schemas hint="list:AddModelConfiguration">  
      <schema name="customageviewomodel" type="Sitecore.XConnect.Client.Configuration.StaticModelConfiguration,Sitecore.XConnect.Client.Configuration" patch:after="schema[@name='collectionmodel']">  
       <param desc="modeltype">Website.CustomPageViewEventModel, Website</param>  
</schema> </schemas> </runtime> </xconnect> </sitecore> </configuration>
Create a Custom Event
Create a new class ConvertPageEventDataToCustomPageViewEvent and override ConvertPageEventDataToEventBase class.
  public class ConvertPageEventDataToCustomPageViewEvent : ConvertPageEventDataToEventBase  
   {  
     protected override bool CanProcessPageEventData(Sitecore.Analytics.Model.PageEventData pageEventData)  
     {  
       if (pageEventData.PageEventDefinitionId == Guid.Parse("{CD52B756-21B4-4028-8BA5-E981B8A96F95}"))  
       {  
         return true;  
       }  
       return false;  
     }  
     protected override Event CreateEvent(Sitecore.Analytics.Model.PageEventData pageEventData)  
     {  
       var number = pageEventData.CustomValues["Number"]?.ToString();  
       CustomPageViewEvent ev = new CustomPageViewEvent(pageEventData.DateTime, pageEventData.ItemId, 1, "en", pageEventData.DataKey, pageEventData.Data, number);  
       return ev;  
     }  
   }  
Create a Patch File
 <?xml version="1.0"?>  
 <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/"  
   xmlns:env="http://www.sitecore.net/xmlconfig/env/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">  
      <sitecore>  
           <pipelines>  
                <convertToXConnectEvent>  
                     <processor patch:after="processor[@type='Sitecore.Analytics.XConnect.DataAccess.Pipelines.ConvertToXConnectEventPipeline.ConvertPageEventDataToGoal, Sitecore.Analytics.XConnect']" type="Website.ConvertPageEventDataToCustomPageViewEvent, Website"/>  
                </convertToXConnectEvent>  
           </pipelines>  
      </sitecore>  
 </configuration>  
Register Event
Now you can register your event wherever you want and you can pass CustomValues as I pass Number.
  var ev = Tracker.MarketingDefinitions.PageEvents[new Guid("{CD52B756-21B4-4028-8BA5-E981B8A96F95}")];  
         if (ev != null && !string.IsNullOrEmpty(model.Number))  
{ var pageData = new Sitecore.Analytics.Data.PageEventData(ev.Alias, ev.Id); pageData.CustomValues.Add("Number", model.Number); Tracker.Current.CurrentPage.Register(pageData); }
Now once you will hit the page or click any button where you have registered for this event, it will store in the Interactions table in the Events field just like below:
 {  
      "@odata.type": "#Website.CustomPageViewEvent",  
      "CustomValues": [],  
      "DefinitionId": "cd52b756-21b4-4028-8ba5-e981b8a96f95",  
      "ItemId": "2a00b93f-dab9-4536-b1d2-8ee3e832c7da",  
      "Id": "a7816c4f-b7b5-4fac-aca2-08ac17b26cc4",  
      "ParentEventId": "c6b1b479-8378-4311-b4b2-4231937399cc",  
      "Timestamp": "2023-06-08T13:38:04.9040878Z",  
      "ItemLanguage": "en",  
      "ItemVersion": 1,  
      "Number": "6OEVv0sFCjZ0OASiQcpvuDYg18o9lH94CQOWgmyGkeahLxXzlfckSwMXrT999tr4zrHN3a9r91BUFNEnQpQ2",       
 }  

Comments

Popular posts from this blog

Azure AD Integration with Sitecore 10.2

 Azure AD Integration with Sitecore 10.2 Sitecore identity server that comes with Sitecore 9.1 allows you to log in through an external identity provider like Azure Active Directory, Facebook, Apple, or Google. It is built on Federation Authentication. What is Federation Authentication? Federation authentication is a technology to allows users to access multiples application, tools, and domains using one credential. Using one set of credential user can access multiple applications, and resources after authentication.  Federation authentication consists of two systems, the Identity provider and the Service provider. Identity providers that maintain/create/manage identity information like name, email address, device, and location. Some examples of identity providers are Azure AD, Google, Facebook, and Apple. Service providers basically refer to a website, software, or app that the user is trying to access and SP basically relies on the identity provider to authenticate the user and provi

Sitecore 10.2 - “Failed to start service ‘Sitecore Marketing Automation Engine’” on Windows 11

Sitecore 10.2 - “Failed to start service ‘Sitecore Marketing Automation Engine' ” on Windows 11 Today I started to install Sitecore 10.2 using Sitecore Instance Manager on Windows 11 and I got this issue “Failed to start service ‘Sitecore Marketing Automation Engine' ” . Error : On event viewer it was showing the below error: I also tried to run ‘ Sitecore.MAEngine.exe ’ like this C:\Windows\system32>C:\inetpub\wwwroot\sclocal102xconnect.dev.local\App_Data\jobs\continuous\AutomationEngine\Sitecore.MAEngine.exe Which was throwing below error: Starting Marketing Automation Engine... 2022-01-29 22:21:11 ERR Error initializing XConnect client. System.AggregateException: One or more errors occurred. ---> Sitecore.XConnect.XdbCollectionUnavailableException: An error occurred while sending the request. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected err

Sitecore CDP Certification - Tips and Tricks

Sitecore CDP Certification - Tips and Tricks Recently I completed Sitecore CDP (Customer Data Platform) certification. In this blog, I will share my personal experience and the steps I took to successfully complete the Sitecore CDP certification. Before diving into the certification journey, I researched various resources to plan my preparation effectively: CDP Certificate Competency  Competency 1: Customer Data Platform Competency 2: Real-time Behavior Data Ingestion Competency 3: Interactive API Competency 4: Batch Data Ingestion Competency 5: Audience Sync and Batch Segments Official Documentation https://doc.sitecore.com/cdp/en/users/sitecore-cdp/index-en.html   https://doc.sitecore.com/cdp/en/developers/api/index-en.html#UUID-980f86cc-d900-1d49-3523-030e16d197a2  https://doc.sitecore.com/cdp/ https://learning.sitecore.com/pages/66/sitecore-learning-home CDP & Personalize Mind Map A highly beneficial resource you can discover is the Mind Map . Exam Details The Sitecore CDP Cert