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 Certification Sample Questions

Sitecore Certification Sample Questions I have completed the Sitecore 9 certification in 2019 and Sitecore 8.2 Certification in 2018. Let me tell you if you have some knowledge about Sitecore then it will be easier for you to understand questions and clear certification exam. Your main focus should be to understand the questions and answers carefully because it is too confusing There will be two options to give the exam: Install the software in your laptop (Laptop should have mic and webcam) Authorized training Center If you have proper Internet, then you can choose option 1 otherwise option 2 is a good choice. Disclaimer : Please note that the below question is only for information purpose only. Below question does not claim the accuracy of the content. Sample Questions: Question 1: What is the name of Component architecture guideline of Sitecore? Answer : Helix Question 2 : What is horizontal scaling and vertical scaling? Answer :  https://doc.

Sitecore 9 Forms: Google reCaptcha field

Sitecore 9 Forms: Google reCaptcha field  Re-Captcha is the most important part of any form’s submission. Google reCaptcha run internet bot detector and determined whether a user is a bot or not.  Sitecore Forms does not provide Google reCaptcha field, which was available in WFFM before, so I have created my custom Google reCaptcha.   Below you can find step by step process to create Google reCaptcha field. Create patch config for reCaptcha Sitekey and SecretKey <?xml version="1.0"?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/"> <sitecore> <settings> <setting name="ReCaptchaSiteKey" value="site-key" /> <setting name="ReCaptchaSecretKey" value="secret-key" /> </settings> </sitecore> </configuration> Create new viewmodel class RecaptchaViewMode

Create Sitecore Custom Admin Page

Create Sitecore Custom Admin Page Sitecore provides you lots of Admin pages just like ShowConfig.aspx, cache.aspx, Logs.aspx, howServicesConfig.aspx, etc. which you can check from here http://<yoursite>/sitecore/admin/. All Sitecore Admin pages is available in this folder “sitecore/admin/*” Sometimes there can be requirement that you want to create custom Admin page which will be accessible to Admin/Non-Admin user. Here is an example: Create aspx page “CustomAdminPage.aspx” inside “<root>/sitecore/admin” folder <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomAdminPage.aspx.cs" Inherits="Namespace.CustomAdminPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Custom Admin Page</title> <link rel="stylesheet" type="text/css" href="/sitecore/she