Skip to main content

Sitecore 9 Forms: Robot detection

Sitecore 9 Forms: Robot detection


As you know Sitecore 9 does not provide “Update Contact details” out of box but Sitecore is providing code for that which you can find from here

In my current project, I am using Sitecore 9.0.2 and using the same code which Sitecore is providing for Update Contact. Recently I faced an issue where the form is getting spammed. 

After some investigation, I found IsRobot function which is a helper method of Sitecore.Analytics.Pipelines.ClassificationStrategy.ContactClassification class.  This helper methods take the contact classification as a parameter and return a Boolean value which indicates whether the contact is a robot or not.

 public static bool IsRobot(int classification);  

Below is a code of UpdateContact:

 namespace Sitecore.ExperienceForms.Samples.SubmitActions  
 {  
   /// <summary>  
   /// Submit action for updating <see cref="PersonalInformation"/> and <see cref="EmailAddressList"/> facets of a <see cref="XConnect.Contact"/>.  
   /// </summary>  
   /// <seealso cref="Sitecore.ExperienceForms.Processing.Actions.SubmitActionBase{UpdateContactData}" />  
   public class UpdateContact : SubmitActionBase<UpdateContactData>  
   {  
     /// <summary>  
     /// Initializes a new instance of the <see cref="UpdateContact"/> class.  
     /// </summary>  
     /// <param name="submitActionData">The submit action data.</param>  
     public UpdateContact(ISubmitActionData submitActionData) : base(submitActionData)  
     {  
     }  
     /// <summary>  
     /// Gets the current tracker.  
     /// </summary>  
     protected virtual ITracker CurrentTracker => Tracker.Current;  
     /// <summary>  
     /// Executes the action with the specified <paramref name="data" />.  
     /// </summary>  
     /// <param name="data">The data.</param>  
     /// <param name="formSubmitContext">The form submit context.</param>  
     /// <returns><c>true</c> if the action is executed correctly; otherwise <c>false</c></returns>  
     protected override bool Execute(UpdateContactData data, FormSubmitContext formSubmitContext)  
     {  
       if (CurrentTracker == null && Tracker.Enabled)  
       {  
         Tracker.StartTracking();  
       }  
       if (Tracker.Current?.Session?.Contact?.System != null)  
       {  
         if (Analytics.Core.ContactClassification.IsRobot(Tracker.Current.Session.Contact.System.Classification) && Analytics.Configuration.AnalyticsSettings.Robots.IgnoreRobots)  
         {  
           var manager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as Analytics.Tracking.ContactManager;  
           manager.SaveContactToCollectionDb(Tracker.Current.Session.Contact);  
           manager.RemoveFromSession(Tracker.Current.Session.Contact.ContactId);  
           return false;  
         }  
       }  
       var firstNameField = GetFieldById(data.FirstNameFieldId, formSubmitContext.Fields);  
       var lastNameField = GetFieldById(data.LastNameFieldId, formSubmitContext.Fields);  
       var emailField = GetFieldById(data.EmailFieldId, formSubmitContext.Fields);  
       if (firstNameField == null && lastNameField == null && emailField == null)  
       {  
         return false;  
       }  
       using (var client = CreateClient())  
       {  
         try  
         {  
           var source = "Subcribe.Form";  
           var id = CurrentTracker.Contact.ContactId.ToString("N");  
           CurrentTracker.Session.IdentifyAs(source, id);  
           var trackerIdentifier = new IdentifiedContactReference(source, id);  
           var expandOptions = new ContactExpandOptions(  
             CollectionModel.FacetKeys.PersonalInformation,  
             CollectionModel.FacetKeys.EmailAddressList);  
           Contact contact = client.Get(trackerIdentifier, expandOptions);  
           SetPersonalInformation(GetValue(firstNameField), GetValue(lastNameField), contact, client);  
           SetEmail(GetValue(emailField), contact, client);  
           client.Submit();  
           return true;  
         }  
         catch (Exception ex)  
         {  
           Logger.LogError(ex.Message, ex);  
           return false;  
         }  
       }  
     }  
     /// <summary>  
     /// Creates the client.  
     /// </summary>  
     /// <returns>The <see cref="IXdbContext"/> instance.</returns>  
     protected virtual IXdbContext CreateClient()  
     {  
       return SitecoreXConnectClientConfiguration.GetClient();  
     }  
     /// <summary>  
     /// Gets the field by <paramref name="id" />.  
     /// </summary>  
     /// <param name="id">The identifier.</param>  
     /// <param name="fields">The fields.</param>  
     /// <returns>The field with the specified <paramref name="id" />.</returns>  
     private static IViewModel GetFieldById(Guid id, IList<IViewModel> fields)  
     {  
       return fields.FirstOrDefault(f => Guid.Parse(f.ItemId) == id);  
     }  
     /// <summary>  
     /// Gets the <paramref name="field" /> value.  
     /// </summary>  
     /// <param name="field">The field.</param>  
     /// <returns>The field value.</returns>  
     private static string GetValue(object field)  
     {  
       return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;  
     }  
     /// <summary>  
     /// Sets the <see cref="PersonalInformation"/> facet of the specified <paramref name="contact" />.  
     /// </summary>  
     /// <param name="firstName">The first name.</param>  
     /// <param name="lastName">The last name.</param>  
     /// <param name="contact">The contact.</param>  
     /// <param name="client">The client.</param>  
     private static void SetPersonalInformation(string firstName, string lastName, Contact contact, IXdbContext client)  
     {  
       if (string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(lastName))  
       {  
         return;  
       }  
       PersonalInformation personalInfoFacet = contact.Personal() ?? new PersonalInformation();  
       if (personalInfoFacet.FirstName == firstName && personalInfoFacet.LastName == lastName)  
       {  
         return;  
       }  
       personalInfoFacet.FirstName = firstName;  
       personalInfoFacet.LastName = lastName;  
       client.SetPersonal(contact, personalInfoFacet);  
     }  
     /// <summary>  
     /// Sets the <see cref="EmailAddressList"/> facet of the specified <paramref name="contact" />.  
     /// </summary>  
     /// <param name="email">The email address.</param>  
     /// <param name="contact">The contact.</param>  
     /// <param name="client">The client.</param>  
     private static void SetEmail(string email, Contact contact, IXdbContext client)  
     {  
       if (string.IsNullOrEmpty(email))  
       {  
         return;  
       }  
       EmailAddressList emailFacet = contact.Emails();  
       if (emailFacet == null)  
       {  
         emailFacet = new EmailAddressList(new EmailAddress(email, false), "Preferred");  
       }  
       else  
       {  
         if (emailFacet.PreferredEmail?.SmtpAddress == email)  
         {  
           return;  
         }  
         emailFacet.PreferredEmail = new EmailAddress(email, false);  
       }  
       client.SetEmails(contact, emailFacet);  
     }  
   }  
 }   

Comments

Popular posts from this blog

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

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 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