Untitled

mail@pastecode.io avatar
unknown
csharp
2 years ago
2.2 kB
4
Indexable
using Microsoft.Xrm.Sdk;
using ContactModel =  Norriq.Dataverse.Nva.XrmContexts.Models.Contact;
using Norriq.DataVerse.Plugins.BaseLayer;
using Norriq.Dataverse.Nva.XrmContexts.Models;

namespace Norriq.Dataverse.Nva.Plugins.NvaLayer.Contact
{
    public class CreateChangeDivisionLogEntry : BasePlugin
    {
        protected override void Execute(IPluginExecutionContext context, IOrganizationService service, ITracingService tracingService)
        {
            var target = _target.ToEntity<ContactModel>();
            var preImage = _preImage.ToEntity<ContactModel>();

            if (context.MessageName != MsgUpdate)
            {
                return;
            }

            if (!target.Contains("nrq_privateaddress_divisionid"))
            {
                return;
            }

            if (GetValue<EntityReference>("nrq_privateaddress_divisionid") == null)
            {
                return;
            }

            if (!preImage.Contains("nrq_privateaddress_divisionid"))
            {
                return;
            }

            var contactRef = target.ToEntityReference();
            var toDivisionRef = target.GetAttributeValue<EntityReference>("nrq_privateaddress_divisionid");
            var fromDivisionRef = target.GetAttributeValue<EntityReference>("nrq_privateaddress_divisionid");

            if (toDivisionRef.Id == fromDivisionRef.Id)
            {
                return;
            }

            var contact = "";
            var toDivision = "";

            
            if (contactRef != null)
            {
                contact = ContactModel.Retrieve(service, contactRef.Id, x => x.FullName).FullName;
            }

            if (toDivisionRef != null)
            {
                toDivision = nrq_memberrelocation.Retrieve(service, toDivisionRef.Id, x => x.nrq_Name).nrq_Name;
            }

            var memberRelocation = service.Create(new nrq_memberrelocation
            {

                nrq_Name = $"{contact} - {fromDivisionRef.Name} - {toDivision}",
                nrq_fromdivisionid = fromDivisionRef,
                nrq_todivisionid = toDivisionRef,
                nrq_contactid = contactRef
            });
        }


    }
}