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

Sitecore Custom API Issue with Federation Authentication

Sitecore Custom API Issue with Federation Authentication In earlier segments, detailed in Part 1 and Part 2 of the blogs on Keycloak Integration with Sitecore, I introduced Keycloak functionality for CM login. Concurrently, I addressed a necessity to develop custom APIs for retrieving Sitecore users and roles. Following the development of custom APIs, during authentication failures, the API erroneously returned a status code of 200 instead of 401. The problem arose because API requests were being routed through the "owin.identityProviders" pipeline, which was not intended for API usage. Solution: When OWIN identifies a 401 response and the AuthenticationMode is set to "Active," it fails to capture the URL hash included in the request. Another choice is to activate the "Passive" AuthenticationMode, wherein OWIN refrains from actively intercepting 401 responses. In passive mode, your application needs to explicitly issue a Challenge to trigger the OWIN aut...

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