Skip to main content

Prevent NULL inserts during updates

Recently, I had an issue that I needed to overcome.  The problem was that the Dynamics 365 instance I was working on, was integrated with multiple other systems with some long running external processes and possible old data in the UI when a record is open, overriding what the value was set to from the external processes.  What was happening is that on create of a contact, we can have a NULL e-mail.  This is normal behavior.  Our external process would be running and update the NULL e-mail field while the record was open in the UI.  Because the UI hadn't been refreshed and the user made other changes, the e-mail would be blanked out (NULL).  To make sure that the field once populated (yes, this is a business requirement) could not be cleared, I wrote a small pre-operation plugin that does the following:

  1. Check's the plugin context to see if we are trying to update the emailaddress1 or emailaddress2.  
  2. If we are trying to update either email address.  Than we check to see if context value is null, "" or string.empty.  We also double check to make sure that the field is in the context, since my first if is an OR statement.
  3. If there is a value, then we move on.  But, if we are trying to blank out the email address, I simply remove the attribute from the context.
Here is a code snippet:

 using Microsoft.Xrm.Sdk;  
 using System;  
 namespace ContactEmailValidation  
 {  
   public class ValidateEmail : IPlugin  
   {  
     public void Execute(IServiceProvider serviceProvider)  
     {  
       ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));  
       IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));  
       IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));  
       IOrganizationService service = factory.CreateOrganizationService(context.UserId);  
       //Convert context to entity to make it easier to work with.  
       Entity PreValidationData = (Entity)context.InputParameters["Target"];  
       //Check if email fields are in the context. If they are then we are trying to update them.  
       if(PreValidationData.Contains(ContactConstants.PrimaryEmail) || PreValidationData.Contains(ContactConstants.SecondaryEmail))  
       {  
         //Get current database contact data  
         using (OrganizationServiceContext context = new OrganizationServiceContext(service))  
         {  
           CurrentDatabaseData = (from c in context.CreateQuery("contact")  
                       where (Guid)c[contactid] == id  
                       select c).SingleOrDefault();  
         }  
         tracer.Trace($"Execution context does have either primary email or secondary email in it.");  
         //If primary email is trying to update to null, remove it from the context so we don't clear out the email.  
         if (PreValidationData.Contains(emailaddress1) && (PreValidationData[emailaddress1] == null || PreValidationData[emailaddress1].ToString() == "" || PreValidationData[emailaddress1].ToString() == string.Empty))  
         {  
           tracer.Trace($"Trying to update primary email to null. Removing from context...");  
           PreValidationData.Attributes.Remove("emailaddress1");  
         }  
         //If secondary email is trying to update to null, remove it from the context so we don't clear out the email.  
         if (PreValidationData.Contains(emailaddress2) && (PreValidationData[emailaddress2] == null || PreValidationData[emailaddress2].ToString() == "" || PreValidationData[emailaddress2].ToString() == string.Empty))  
         {  
           tracer.Trace($"Trying to update secondary email to null. Removing from context...");  
           PreValidationData.Attributes.Remove("emailaddress2");  
         }  
         //Update the plugin context that will be saved to the database.  
         tracer.Trace($"Setting target to new context values.");  
         context.InputParameters["Target"] = PreValidationData;  
       }  
     }  
   }  
 }  

Because this is a pre-operation removing the values from the context will prevent the value from being cleared out.  Also, this is a stripped down code snippet, so you will need to check it for any typo's or syntax errors.

Comments

Popular posts from this blog

Dynamics Set IFrame URL - D365 v8 vs. D365 v9

While doing client work, I came across a problem with setting an IFrame URL dynamically.  The underlying issue was that the sandbox instance is on v8 of Dynamics 365 and production is on v9 of Dynamics 365.  The reason for this was because this client was setup around the time that Microsoft rolled out v9.  Anyways, JavaScript that I wrote to dynamically set the URL of the IFrame wasn't working in the v9 instance.  This was because of changes that Microsoft made to how IFrames are loaded on the form and also changes to JavaScript. Here is my v8 setup: JavaScript runs OnLoad of contact form.  This works because of how IFrames are loaded in v8.  You can also run it on either a tab change (hide / show) or OnReadyStateComplete event of the IFrame.  Depending on your setup you will need to choose which is best for you.  For me in this case it was the OnLoad event. Here is the JavaScript: function OnLoad() { //Get memberid var value = Xrm.Page.data.entity.attri

CRM Portals OnChange Event For DateTime

Occasionally when working with CRM Portals you may run into the need to get the OnChange event for a date time field.  Because of the way that CRM Portals renders date time fields this is slightly more complicated then working with text boxes, check boxes and pick lists.  During my process I ended up reaching out to Microsoft for help on this and below are the steps they provided to help me with this problem: 1) Click on the date time control 2) Press F12 3) In console type $('div.control') and hit enter (this will give you a list of div controls) 4) Locate the div control for the date time field 5) Go to the entity form or web page in CRM and add the following code snippet (replace the 2 with the number your div control is located at): 1: $(document).ready(function () 2: { 3: var dpcontrol = $('div.control')[2]; 4: $(dpcontrol).on("dp.change", function (e) 5: { 6: alert("On chang

Validating User Input In CRM Portals With JavaScript

When we are setting up CRM Portals to allow customers to update their information, open cases, fill out an applications, etc. We want to make sure that we are validating their input before it is committed to CRM.  This way we ensure that our data is clean and meaningful to us and the customer. CRM Portals already has a lot validation checks built into it. But, on occasion we need to add our own.  To do this we will use JavaScript to run the validation and also to output a message to the user to tell them there is an issue they need to fix. Before we can do any JavaScript, we need to check and see if we are using JavaScript on an Entity Form or Web Page.  This is because the JavaScript, while similar, will be different.  First, we will go over the JavaScript for Entity Forms.  Then, we will go over the JavaScript for Web Pages.  Finally, we will look at the notification JavaScript. Entity Form: if (window.jQuery) { (function ($) { if (typeof (entityFormClientVali