Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
5.9 kB
4
Indexable
Never
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;

public class UpdateContactsInVisitReport : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        try
        {
            if (context.MessageName.ToLower() == "update" && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity visitReport = (Entity)context.InputParameters["Target"];

                // Check if the appointmentlookup field is updated
                if (visitReport.Attributes.Contains("appointmentlookup"))
                {
                    // Retrieve the Appointment entity reference from the lookup
                    EntityReference appointmentRef = (EntityReference)visitReport["appointmentlookup"];

                    // Retrieve the Appointment entity to access requiredattendees and optionalattendees
                    Entity appointment = service.Retrieve(appointmentRef.LogicalName, appointmentRef.Id, new ColumnSet("requiredattendees", "optionalattendees"));

                    // Retrieve and process contacts from requiredattendees
                    RetrieveContactsFromParticipants(service, visitReport, appointment, "requiredattendees");

                    // Retrieve and process contacts from optionalattendees
                    RetrieveContactsFromParticipants(service, visitReport, appointment, "optionalattendees");
                }
            }
        }
        catch (Exception ex)
        {
            throw new InvalidPluginExecutionException($"Error in UpdateContactsInVisitReport plugin: {ex.Message}");
        }
    }

    private void RetrieveContactsFromParticipants(IOrganizationService service, Entity visitReport, Entity appointment, string participantsField)
    {
        if (appointment.Attributes.Contains(participantsField))
        {
            EntityCollection participants = (EntityCollection)appointment[participantsField];

            foreach (Entity participant in participants.Entities)
            {
                if (participant.Contains("partyid") && participant["partyid"] is EntityReference)
                {
                    EntityReference partyIdRef = (EntityReference)participant["partyid"];

                    // Determine the type of participant and retrieve the associated contact
                    Entity contact = null;
                    if (partyIdRef.LogicalName == "contact")
                    {
                        contact = service.Retrieve(partyIdRef.LogicalName, partyIdRef.Id, new ColumnSet("fullname", "contactid"));
                    }
                    else if (partyIdRef.LogicalName == "account")
                    {
                        // Retrieve the primary contact from the associated account
                        contact = RetrievePrimaryContactFromAccount(service, partyIdRef.Id);
                    }
                    else if (partyIdRef.LogicalName == "systemuser")
                    {
                        // Retrieve the related contact from the associated system user
                        contact = RetrieveContactFromSystemUser(service, partyIdRef.Id);
                    }

                    // Add the contact to the Visit Report subgrid
                    if (contact != null)
                    {
                        AddContactToVisitReportSubgrid(service, visitReport, contact);
                    }
                }
            }
        }
    }

    private Entity RetrievePrimaryContactFromAccount(IOrganizationService service, Guid accountId)
    {
        // Assuming there is a relationship named "primarycontactid" between Account and Contact
        QueryExpression query = new QueryExpression("contact");
        query.ColumnSet = new ColumnSet("fullname", "contactid");
        query.AddLink("account", "contactid", "primarycontactid", JoinOperator.Inner);
        query.LinkEntities[0].LinkCriteria.AddCondition("accountid", ConditionOperator.Equal, accountId);

        EntityCollection results = service.RetrieveMultiple(query);
        return (results.Entities.Count > 0) ? results.Entities[0] : null;
    }

    private Entity RetrieveContactFromSystemUser(IOrganizationService service, Guid systemUserId)
    {
        // Assuming there is a relationship named "new_relatedcontactid" between SystemUser and Contact
        QueryExpression query = new QueryExpression("contact");
        query.ColumnSet = new ColumnSet("fullname", "contactid");
        query.AddLink("systemuser", "contactid", "new_relatedcontactid", JoinOperator.Inner);
        query.LinkEntities[0].LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, systemUserId);

        EntityCollection results = service.RetrieveMultiple(query);
        return (results.Entities.Count > 0) ? results.Entities[0] : null;
    }

    private void AddContactToVisitReportSubgrid(IOrganizationService service, Entity visitReport, Entity contact)
    {
        // Assuming there is a relationship named "new_contact_visitreport" between Visit Report and Contact
        EntityReference contactRef = contact.ToEntityReference();
        service.Associate(visitReport.LogicalName, visitReport.Id, new Relationship("new_contact_visitreport"), new EntityReferenceCollection { contactRef });
    }
}
Leave a Comment