web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Suggested Answer

Plugin to calculate age from birthday C#

(0) ShareShare
ReportReport
Posted on by

Hi, I want to know the code to do this, i'm learning CRM by myself and I am a little loss, the basic code in C# is like this:

DateTime birthdate = new DateTime(1991, 9, 05);
DateTime today = DateTime.Today;
int age = today.Year - birthdate.Year;;

Console.WriteLine(age);

I want to know how would it be to get the attribute birthday in a plugin and calculate age from that, and then set the new value. 

I already did it with JavaScript, now I want to do it with C# (plugin).

Thanks in advance!

I have the same question (0)
  • Suggested answer
    LeoAlt Profile Picture
    16,331 Moderator on at

    Hi partner,

    If you want to use C# to do this, you could refer to my code here.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    namespace plugin2._0
    {
        public class Birthday : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                // Obtain the tracing service
                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. 
                if (context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters. 
                    Entity entity = (Entity)context.InputParameters["Target"];
                    // Obtain the organization service reference which you will need for 
                    // web service calls. 
                    IOrganizationServiceFactory serviceFactory =
                        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                    try
                    {
                        var birthday = entity["new_birthday1"].ToString();
                        var dateBirthday = Convert.ToDateTime(birthday);
                        var now = DateTime.Now;
                        int age = now.Year - dateBirthday.Year;
                        entity["new_age"] = age;
                        service.Update(entity);
                    }
                    catch (FaultException<OrganizationServiceFault> ex)
                    {
                        throw new InvalidPluginExecutionException(ex.InnerException.ToString(), ex);
                    }
                    catch (Exception ex)
                    {
                        tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                        throw;
                    }
                }
            }
        }
    }

    You could register this plugin in pre-operation or post-operation update the record. 

    For more description about plug-in, please refer to the following links.

    https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/org-service/entity-operations-update-delete

    https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/org-service/samples/basic-followup-plugin

    Hope it helps.

    Best Regards,

    Leo

  • Community Member Profile Picture
    on at

    Thank you very much, but are you getting the birthday attribute from the contact's field? Because it seems that you are creating a new one:

    try

                   {

                       var birthday = entity["new_birthday1"].ToString();

                       var dateBirthday = Convert.ToDateTime(birthday);

                       var now = DateTime.Now;

                       int age = now.Year - dateBirthday.Year;

                       entity["new_age"] = age;

                       service.Update(entity);

                   }

    Or should I put birthdate instead of "new_birthday1"?

    Again, thank you very much!

  • Community Member Profile Picture
    on at

    @Leo Zhang

    Thank you very much, but are you getting the birthday attribute from the contact's field? Because it seems that you are creating a new one:

    try

                  {

                      var birthday = entity["new_birthday1"].ToString();

                      var dateBirthday = Convert.ToDateTime(birthday);

                      var now = DateTime.Now;

                      int age = now.Year - dateBirthday.Year;

                      entity["new_age"] = age;

                      service.Update(entity);

                  }

    Or should I put birthdate instead of "new_birthday1"?

    Again, thank you very much!

  • LeoAlt Profile Picture
    16,331 Moderator on at

    Hi partner,

    The "new_birthday1" was a new custom field created by myself. You should replace the correct field name in your instance.

    Best Regards,

    Leo

  • Suggested answer
    LeoAlt Profile Picture
    16,331 Moderator on at

    Hi partner,

    Sorry that the last answer I provided may casue some issues.

    I've updated the code here.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Discovery;
    namespace plugin2._0
    {
        public class UpdateFax : 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));
                // Get a reference to the Organization service.
                IOrganizationServiceFactory factory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                IOrganizationServiceFactory servicefactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService client = servicefactory.CreateOrganizationService(context.UserId);

                // The InputParameters collection contains all the data passed in the message request.
                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 account.
                    // If not, this plug-in was not registered correctly.
                    if (context.Depth > 1) return;
                    if (entity.LogicalName == "account")
                    {
                        try
                        {
                            string birthday = string.Empty;
                            if (entity.Attributes.Contains("new_birthday1"))
                            {
                                birthday = entity.GetAttributeValue<DateTime>("new_birthday1").ToString();
                            }
                            var dateBirthday = Convert.ToDateTime(birthday);
                            var now = DateTime.Now;
                            int age = now.Year - dateBirthday.Year;
                            entity["new_age"] = age;
                        }
                        catch (Exception e)
                        {
                            tracingService.Trace("accountPlugin: {0}", e.ToString());
                            throw new InvalidPluginExecutionException(e.Message);
                        }
                    }
                    else
                        return;
                }

            }
        }
    }

    pastedimage1575883245938v1.png

    pastedimage1575883278355v2.png

    Hope it helps.

    Best Regards,

    Leo

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Martin Dráb Profile Picture

Martin Dráb 51 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 38 Super User 2025 Season 2

#3
#ManoVerse Profile Picture

#ManoVerse 31

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans