Plugin C# Code for Retrieve Multiple Concept

  1. Here on update of customerphone_number(parent).. all the powerbills(child) records need to update with the latest phone number
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace PluginRetrieveMultiple4
{
    public class PluginRetrieveMultiple : 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));
            // ✅ Depth check to avoid infinite loop
            if (context.Depth > 1)
            {
                return;
            }
            // 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.  --- Here in this object user entered data is saved
                Entity sourceRecordInfo = (Entity)context.InputParameters["Target"];

                // Obtain the IOrganizationService instance which you will need for  
                // web service calls.  
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    //Requiremnt: If customer_phone_number updated in CustomerInformation(Parent Entity)...Then we need to update all associated powerbills(Child Entity)

                    //Step-1: Fetch the XML of Child Records that need to update..add GUID Dynamically...here we can use fetch xml or query expression
                    string strFetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                       "<entity name='sdc_powerbills'>" +
                                       "<attribute name='sdc_powerbillsid'/>" +
                                       "<attribute name='sdc_name'/>" +
                                       "<attribute name='createdon'/>" +
                                       "<order attribute='sdc_name' descending='false'/>" +
                                       "<filter type='and'>" +
                                       "<condition attribute='sdc_customer' operator='eq' value='"+sourceRecordInfo.Id.ToString()+"'/>" +
                                       "</filter>" +
                                       "</entity>" +
                                       "</fetch>";
                    //Step-2: Syntax
                    //What we have fetched in the Step1.. here create entitycollection object and store those values
                    EntityCollection entBills = service.RetrieveMultiple(new FetchExpression(strFetch));

                    //Step-3
                    for (int i=0; i < entBills.Entities.Count; i++)
                    {
                        //Here Taking 1st power bill... to take single record we use entity keyword
                        Entity entBill = entBills.Entities[i];
                        //Update the above record
                        Entity entBillUpdate = new Entity();
                        entBillUpdate.LogicalName = entBill.LogicalName;
                        entBillUpdate.Id = entBill.Id;


                        
                        // GET phone from sourceRecordInfo
                        if (sourceRecordInfo.Contains("sdc_phonenumber") && sourceRecordInfo["sdc_phonenumber"] != null)
                        {
                            entBillUpdate["sdc_customerphoneplugin"] = sourceRecordInfo["sdc_phonenumber"];
                        }
                        service.Update(entBillUpdate);

                    }
                }

                catch (Exception ex)
                {
                    //--add plugin class name here
                    tracingService.Trace("PopulateFullName: {0}", ex.ToString());
                    throw;
                }
            }
        }
    }
}

2. On update of customer_phone number in BajajCustomer(Parent Entity)……All the associated Records in Customer_Purchased_Products(Child Entity) Need to Update

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace PluginRetrieveMultiple4
{
    public class BajajcustomerRetrieveMultiple : 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));
            // ✅ Depth check to avoid infinite loop
            if (context.Depth > 1)
            {
                return;
            }
            // 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.  --- Here in this object user entered data is saved
                Entity sourceRecordInfo = (Entity)context.InputParameters["Target"];

                // Obtain the IOrganizationService instance which you will need for  
                // web service calls.  
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    //Requiremnt: If customer_phone_number updated in BajajCustomer(Parent Entity)...Then we need to update all associated Customerpurchasedproducts(Child Entity) records

                    //Step-1: Fetch the XML of Child Records that need to update..add GUID Dynamically...here we can use fetch xml or query expression
                    string strFetch = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                        <entity name='sdc_customerpurchasedproducts'>
                                            <attribute name='sdc_customerpurchasedproductsid'/>
                                            <attribute name='sdc_name'/>
                                            <attribute name='createdon'/>
                                            <order attribute='sdc_name' descending='false'/>
                                            <filter type='and'>
                                                <condition attribute='sdc_customer' operator='eq' value='" + sourceRecordInfo.Id.ToString() + @"'/>
                                            </filter>
                                        </entity>
                                        </fetch>";
                    //Step-2: Syntax
                    //What we have fetched in the Step1.. here create entitycollection object and store those values
                    EntityCollection entCustomerPProducts = service.RetrieveMultiple(new FetchExpression(strFetch));
                    
                    //Step-3
                    for (int i = 0; i < entCustomerPProducts.Entities.Count; i++)
                    {
                        //Here Taking 1st Customer_Puchased_Product... to take single record we use entity keyword
                        Entity entCustomerPurchaseProduct = entCustomerPProducts.Entities[i];
                        //Update the above record
                        Entity entCppUpdate = new Entity();
                        entCppUpdate.LogicalName = entCustomerPurchaseProduct.LogicalName;
                        entCppUpdate.Id = entCustomerPurchaseProduct.Id;



                        // GET phone from sourceRecordInfo
                        if (sourceRecordInfo.Contains("sdc_phonenumber") && sourceRecordInfo["sdc_phonenumber"] != null)
                        {
                            entCppUpdate["sdc_customerphoneplugin"] = sourceRecordInfo["sdc_phonenumber"];
                        }
                        service.Update(entCppUpdate);

                    }
                }

                catch (Exception ex)
                {
                    //--add plugin class name here
                    tracingService.Trace("PopulateFullName: {0}", ex.ToString());
                    throw;
                }
            }
        }
    }
}

Leave a Comment