PreImage and PostImage Plugin Senario in mscrm

PreImage and PostImage Plugin Senario in mscrm
PreImage  Plugin:
preimage plugin is used on account related contact having subgrid on Account related Contact Deleted.
Ex: Account has totalAmount field and Contact has Quantiy(Q) and CostPerUnit(CPU) fields.
account(TotalAmount)=1Con+2Con+3Con;
account(TotalAmount)= 1Con(Q*CPU)+3Con(Q*CPU)+2Con(Q*CPU);
PostImage Plugin:
PostImage Plugin is used on Account related Contact on having subgrid on Account related Contact and update the value either Quantiy(Q) and CostPerUnit(CPU) fields.
account(TotalAmount)=1Con+2Con+3Con;
account(TotalAmount)= 1Con(Q*CPU)+3Con(Q*CPU)+2Con(Q*CPU);
Register the Plugin on (Create and Delete)Updating the Contact on Quantity and CostPerUnit and ContactLookup fileds

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace CreateBookingMovementFromEnquiry
{
    public class RevenueCalculations : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            IOrganizationService service = serviceFactory.CreateOrganizationService(new Guid?(context.UserId));

            if (context.Depth > 1)
                return;

            if (context.MessageName.ToLower() == "create" || context.MessageName.ToLower() == "delete")
            {
                Entity carrierSupplEnt = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true));

                if (carrierSupplEnt != null)
                {
                    Guid enquiryId = carrierSupplEnt.Contains(EntityBaseClass.EnquiryNumber) ? carrierSupplEnt.GetAttributeValue<EntityReference>(EntityBaseClass.EnquiryNumber).Id : Guid.Empty;

                    if (enquiryId != Guid.Empty)
                    {
                        EntityCollection allCarriers = RetrieveCarriers(service, context.MessageName.ToLower(), enquiryId, carrierSupplEnt.Id);
                        EnquiryUpdate(service, enquiryId, allCarriers, carrierSupplEnt.Id);
                    }
                }
            }

            if (context.MessageName.ToLower() == "update")
            {
                Entity CarrierSupPreImg = context.PreEntityImages["PreImage"];
                Entity CarrierSupPostImg = context.PostEntityImages["PostImage"];
                Guid preEnqId = CarrierSupPreImg.Contains(EntityBaseClass.EnquiryNumber) ? CarrierSupPreImg.GetAttributeValue<EntityReference>(EntityBaseClass.EnquiryNumber).Id : Guid.Empty;
                Guid postEnqId = CarrierSupPostImg.Contains(EntityBaseClass.EnquiryNumber) ? CarrierSupPostImg.GetAttributeValue<EntityReference>(EntityBaseClass.EnquiryNumber).Id : Guid.Empty;
                if (preEnqId != Guid.Empty && postEnqId != Guid.Empty && preEnqId != postEnqId)
                {
                    EntityCollection preEnqCarries = RetrieveCarriers(service, context.MessageName.ToLower(), preEnqId, context.PrimaryEntityId);
                    EnquiryUpdate(service, preEnqId, preEnqCarries, context.PrimaryEntityId);
                    EntityCollection postEnqCarries = RetrieveCarriers(service, context.MessageName.ToLower(), postEnqId, context.PrimaryEntityId);
                    EnquiryUpdate(service, postEnqId, postEnqCarries, context.PrimaryEntityId);
                }
                else
                {
                    EntityCollection updateallCarries = RetrieveCarriers(service, context.MessageName.ToLower(), postEnqId, context.PrimaryEntityId);
                    EnquiryUpdate(service, postEnqId, updateallCarries, context.PrimaryEntityId);
                }

            }
        }

        //Update Totalcost in enquiry entity
        public void EnquiryUpdate(IOrganizationService service, Guid id, EntityCollection result, Guid currentRecordId)
        {
            decimal total = 0;
            if (result.Entities.Count > 0)
            {
                foreach (Entity reqEntity in result.Entities)
                {
                    decimal totalCostProvidedPerUnit = reqEntity.Contains(EntityBaseClass.CostProviderPerUnit) ? reqEntity.GetAttributeValue<Money>(EntityBaseClass.CostProviderPerUnit).Value : 0;
                   
                    int totalQuantity = reqEntity.Contains(EntityBaseClass.Quantity) ? reqEntity.GetAttributeValue<int>(EntityBaseClass.Quantity) : 0;

                    total += totalCostProvidedPerUnit * totalQuantity;
                }
            }

            Entity enqEnt = new Entity(EntityBaseClass.Enquiry);
            enqEnt.Id = id;
            enqEnt[EntityBaseClass.TotalCosts] = new Money(Math.Round(total, 2));
            service.Update(enqEnt);
        }

        //Retrieve All carrier supplier records
        public EntityCollection RetrieveCarriers(IOrganizationService service, string messageName, Guid enquiryId, Guid currentRecId)
        {
            string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
            fetchXml += "<entity name='apy_carriersupplierraterequest'>";
            fetchXml += "<attribute name='apy_carriersupplierraterequestid' />";
            fetchXml += "<attribute name='apy_name' />";
            fetchXml += "<attribute name='createdon' />";
            fetchXml += "<attribute name='apy_costprovidedperunit' />";
            fetchXml += "<attribute name='apy_quantity' />";
            fetchXml += "<order attribute='apy_name' descending='false' />";
            fetchXml += "<filter type='and'>";
            fetchXml += "<condition attribute='statecode' operator='eq' value='0' />";
            if (messageName == "delete")
                fetchXml += "<condition attribute='apy_carriersupplierraterequestid' operator='ne' uitype='apy_carriersupplierraterequest' value='{" + currentRecId + "}' />";
            fetchXml += "</filter>";
            fetchXml += "<link-entity name='apy_enquiry' from='apy_enquiryid' to='apy_enquirynumber' link-type='inner' alias='aa'>";
            fetchXml += "<filter type='and'>";
            fetchXml += "<condition attribute='apy_enquiryid' operator='eq' uiname='12' uitype='apy_enquiry' value='{" + enquiryId + "}' />";
            fetchXml += "</filter>";
            fetchXml += "</link-entity>";
            fetchXml += "</entity>";
            fetchXml += "</fetch>";

            EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));
            return result;
        }
    }
}

Comments

Popular posts from this blog

Meta Data Using WebApiRequest

Sample CRUD Operations Using C# in MSCRM

Basic Plugin Code in D365 using C#