Sample Register a page event

Abstract

Complete code samples for registering page events programmatically

After you have created a page event, you also need to register the page event programmatically. The code for registering page events ensures that when the event is triggered by a contact, it is registered in the Sitecore Experience Database (xDB). However, when a page event is triggered it is not stored in the xDB straight away, instead it is stored in the active session. This means that it is only saved to the xDB when the session ends. If the contact is classified as a robot, then the session and the page event are not saved to the xDB.

There are two code samples that you can use to register page events programmatically:

  • Standard registration code - full code for registering page events.

  • Registration code that prevents duplicate page events.

This code sample enables you to register page events:

    private void RegisterPageEvent(string name, Guid definitionId, Guid itemId, string data, string text)
    {
      Assert.IsNotNull(Tracker.Current, "Tracker.Current");
      Assert.IsNotNull(Tracker.Current.Session, "Tracker.Current.Session");
      var interaction = Tracker.Current.Session.Interaction;
      Assert.IsNotNull(interaction, "Tracker.Current.Session.Interaction");
      Assert.IsNotNull(interaction.CurrentPage, "Tracker.Current.Session.Interaction.CurrentPage");
      var pageEventData = new PageEventData(name, definitionId)
      {
        ItemId = itemId,
        Data = data,
        Text = text
      };
      interaction.CurrentPage.Register(pageEventData);
    }

There are two alternate ways to write an If statement to check for duplicates, using different LINQ statements.

Using the All LINQ extension:

      if (interaction.CurrentPage.PageEvents.All(pe => pe.PageEventDefinitionId != definitionId))

Using the Any LINQ extension:

      if (!interaction.CurrentPage.PageEvents.Any(pe => pe.PageEventDefinitionId == definitionId))

If the page event has not already been registered then it can now be registered.

Full code sample to avoid duplicate page events:

    private void RegisterUniquePageEvent(string name, Guid definitionId, Guid itemId, string data, string text)
    {
      Assert.IsNotNull(Tracker.Current, "Tracker.Current");
      Assert.IsNotNull(Tracker.Current.Session, "Tracker.Current.Session");
      var interaction = Tracker.Current.Session.Interaction;
      Assert.IsNotNull(interaction, "Tracker.Current.Session.Interaction");
      Assert.IsNotNull(interaction.CurrentPage, "Tracker.Current.Session.Interaction.CurrentPage");
      if (interaction.CurrentPage.PageEvents.All(pe => pe.PageEventDefinitionId != definitionId))
      {
        var pageEventData = new PageEventData(name, definitionId)
        {
          ItemId = itemId,
          Data = data,
          Text = text
        };
        interaction.CurrentPage.Register(pageEventData);
      }
    }