Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Suggested answer

Plugin to calculate age from birthday C#

(0) ShareShare
ReportReport
Posted on by Microsoft Employee

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!

  • Suggested answer
    LeoAlt Profile Picture
    LeoAlt 16,331 on at
    RE: Plugin to calculate age from birthday C#

    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

  • LeoAlt Profile Picture
    LeoAlt 16,331 on at
    RE: Plugin to calculate age from birthday C#

    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

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plugin to calculate age from birthday C#

    @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!

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plugin to calculate age from birthday C#

    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!

  • Suggested answer
    LeoAlt Profile Picture
    LeoAlt 16,331 on at
    RE: Plugin to calculate age from birthday C#

    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

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

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,458 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans