Skip to main content

Notifications

Announcements

No record found.

Customer Service forum

Extract date of birth from Id Number

(0) ShareShare
ReportReport
Posted on by 65

Hi guys

Apologies, i could not find the dynamics 365 forum here. I am trying to extract a date of birth from an id number. My thoughts were to use calculated fields and extract in a similiar way to excel using the commands Left and Mid. This does not seem to work in a calculated field? 

For example an idea number could be 9503015057089 the date of birth would then need to be extracted automatically to pull 01/03/1995 in a field on the contact form.

Does anyone have any ideas on this?

Categories:
  • Michel van den Brink Profile Picture
    Michel van den Brink 4,697 on at
    RE: Extract date of birth from Id Number

    Any time, Sean! Here to help :-)

  • Sean Kelly 1994 Profile Picture
    Sean Kelly 1994 65 on at
    RE: Extract date of birth from Id Number

    Hi Michel

    Thanks so much for all your help - really appreciate it. I will give this a try and give you a shout if i need some assistance.

  • Suggested answer
    Michel van den Brink Profile Picture
    Michel van den Brink 4,697 on at
    RE: Extract date of birth from Id Number

    Hello Sean,

    To create plug-ins please take a look at this documentation:
    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/plugin-development

     

    A plugin can essentially be registered to different events happening on records. For your required scenario, I suggest using the 'Create' and/or 'Update' event messages on the record where the ID value and birth date are located, in my example below I assumed you're using 'contact' but, this can be any entity.

    Plugins can run on different stages of the application's pipeline:

    1. PreValidation - runs before CRM does any validation checks, you will get dirty data
    2. PreOperation - runs after CRM validation but, before anything is written to the database
    3. PostOperation - runs after everything is done and written to the database

    For your required scenario I suggest using 'PreOperation' as this allows you to run the code when a user saves the record but, just before it's actually been written to the database, so you can make a last-minute addition: extracting the birth date and adding it to the record.

      

    Take a look at these specific docs to get started:

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/write-plugin

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/understand-data-context-passed-plugin 

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/register-deploy-plugins

     

    Here's my example of a plug-in that does what you need, I kept it close to the JavaScript example.
    This code is not very optimized and could be improved but, I wrote it in a hopefully easy to understand manner for you to use as a starting point.

    If you prefer a code sample with syntax highlighting (colored and better readable), I added a highlighted copy here:
    https://gist.github.com/justlikeed/1433668720dc1717543ea1f2e920e898 

     

    using Microsoft.Xrm.Sdk;
    using System;
    using System.ServiceModel;
    
    namespace ExtractBirthdaySample
    {
        public class ExtractBirthdaySamplePlugin : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                //Extract the tracing service for use in debugging sandboxed plug-ins.
                ITracingService tracingService =
                    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                // Obtain the execution context from the service provider.
                IPluginExecutionContext context = (IPluginExecutionContext)
                    serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                // The InputParameters collection contains all the data passed in the message request.
                // "Target" is the entity the plugin started on
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];
    
                    // Verify that the target entity represents an contact and that a value was entered for new_nameofidfield
                    // Plugins (by default) only receive values for fields that have been changed
                    if (entity.LogicalName != "contact" ||
                        entity.Contains("new_nameofidfield"))
                    {
                        return;
                    }
                    try
                    {
                        // Read the current value of the ID field
                        string idValue = entity.GetAttributeValue<string>("new_nameofidfield");
    
                        //If there is any value and its length is 13 (assumption) continue, otherwise ignore it:
                        if (!string.IsNullOrWhiteSpace(idValue) && idValue.Length == 13)
                        {
                            // Define empty integers
                            int yy, mm, dd;
    
                            // From the idValue, use substr to get the parts - Substring is roughly the same as MID in Excel
                            // use int.TryParse to gracefully convert the strings to integers:
                            if (int.TryParse(idValue.Substring(0, 2), out yy) &&
                                int.TryParse(idValue.Substring(2, 2), out mm) &&
                                int.TryParse(idValue.Substring(4, 2), out dd))
                            {
    
                                // Avoiding a Y2K bug:
                                if (yy <= 30)
                                {
                                    yy += 2000; // << Assuming all years 00-30 are 2000-2030
                                }
                                else
                                {
                                    yy += 1900; // << Asusming all other years are 19xx
                                }
    
                                // Creating a real date object:
                                DateTime dateValue = new DateTime(yy, mm, dd); // No need to do mm-1 here!
                                entity["birthdate"] = dateValue;  // << setting the value to the attribute on the entity
    
                            }
    
                        }
                    }
                    catch (FaultException<OrganizationServiceFault> ex)
                    {
                        tracingService.Trace(ex.ToString());
                        throw new InvalidPluginExecutionException("An error occurred in " + nameof(ExtractBirthdaySamplePlugin) + ": " + ex.Message, ex);
                    }
    
                    catch (Exception ex)
                    {
                        tracingService.Trace(ex.ToString());
                        throw;
                    }
                }
            }
        }
    }
  • Sean Kelly 1994 Profile Picture
    Sean Kelly 1994 65 on at
    RE: Extract date of birth from Id Number

    Hi Michel

    Thanks so much for your great response! I did take a look at the java option, however you raise good points regarding the plug in. It would be great to get some assistance regarding this, if you are able to.

    Sean

  • Verified answer
    Michel van den Brink Profile Picture
    Michel van den Brink 4,697 on at
    RE: Extract date of birth from Id Number

    Hello,

    Calculated Fields are not suitable for this purpose, they are for literal calculating things like addition, subtraction and comparing numbers.

     

    There's two ways of going at this:

    1. JavaScript, which runs in the client (browser or app)
      This would require a user to have the Form of the record open for the extraction to work.

      This solution is the easiest but, the least robust as this script will never run when data is changed outside of the client, for example via a Workflow or a Portal.

      You would put a piece of JavaScript into a JS file and upload it to Dynamics as a 'WebResource' (under a Solution file)
      Then register an event on your form (like OnChange of ID Number) to run your script

      A very rough (and untested) example with a lot of assumptions about the real logic:
      function ExtractBirthday() {
      
          var idField = Xrm.Page.getAttribute('new_nameofidfield'); // << Get the attribute where the ID is stored from the Form
          var birthDateField = Xrm.Page.getAttribute('birthdate'); // << Get the attribute where the birthdate is stored from the Form
          var idValue = idField.getValue(); // << Read the current value of the ID field
      
          //If there is any value and its length is 13 (assumption) continue, otherwise ignore it:
          if (idValue && idValue.length == 13) {
      
              // From the idValue, use substr to get the parts - substr is roughly the same as MID in Excel:
              var yy = idValue.substr(0, 2) * 1, // << any string *1 is a quick way to convert to a number
                  mm = idValue.substr(2, 2) * 1,
                  dd = idValue.substr(4, 2) * 1;
      
              // Avoiding a Y2K bug:
              if (yy <= 20) {
                  yy += 2000; // << Assuming all years 00-20 are 2000-2020
              } else {
                  yy += 1900; // << Asusming all other years are 19xx
              }
      
              // Creating a real date object:
              var dateValue = new Date(yy, mm - 1, dd); // << Doing (mm - 1) because for JavaScript Jan = 0, Feb = 1, Mar = 3, etc.
              birthDateField.setValue(dateValue); // << setting the value to the attribute on the form
          }
      }
    2. Custom plug-in, written in C# (or VB.NET), which runs on the server

      A custom-plugin could trigger on any type of even on most entities, always being able to extract the date of birth automatically, regardless of user interaction or whether any Form is open or not.

      This solution is the most robust but, more difficult because you need to know how to code and create plug-ins for Dynamics 365.

      I can create a sample for this as well but, it might be a little too complex for your scenario to dive into plug-ins. If you do want to give it a go, get it touch!

     

    Hope my answer has given you a push in the right direction, let me know if you need any extra help :-)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,431 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,503 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans