Associate/Disassociate plugin messages in CRM


Sample Code –

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

            try
            {
                tracingService.Trace("start plugin execution: {0}", this.GetType().FullName);
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference && context.ParentContext == null)
                {
                    tracingService.Trace("Parent Context is null");
                    if (context.MessageName == "Associate")
                    {
                        if(context.InputParameters.Contains("Relationship") &&
                            ((Relationship)context.InputParameters["Relationship"]).SchemaName.Equals("schemaname"))
                        {
                            tracingService.Trace("Relationship Found");
                            if (context.InputParameters.Contains("RelatedEntities") && context.InputParameters["RelatedEntities"] is EntityReferenceCollection)
                            {                                
                                var primaryEntity= (EntityReference)context.InputParameters["Target"];
                                var  relatedEntities= context.InputParameters["RelatedEntities"] as EntityReferenceCollection;
                                                           
                            }                           
                        }  
                    }
                }

                tracingService.Trace("end plugin execution: {0}", this.GetType().FullName);
            }
            catch(InvalidPluginExecutionException)
            {
                throw;
            }
            catch (System.ServiceModel.FaultException<OrganizationServiceFault> ex)
            {
                tracingService.Trace(ex.Detail.Message);
                throw;
            }
            catch (Exception ex)
            {
                tracingService.Trace(ex.ToString());
                throw;
            }
        }

      
    }

Rajeev Pentyala's avatarRajeev Pentyala – Technical Blog on Power Platform, Azure and AI

In CRM, the Associate or Disassociate event happens

  • If you have a N:N relationship between two entities and when you try to associate or disassociate records either from Associated view or Sub grid.

Entity Associate View Entity Associate View

In Plugins, the Associate & Disassociate messages behave little different than other messages.

  • When you register a plugin on Associate message, you have to leave “Primary and Secondary” entities as ‘none’.

Associate Plugin Step Associate Plugin Step

  • Since we don’t provide entity names, the registered Plug-in step triggers on all “Associate” operations, so we have to check few conditions to let the “Association” trigger happen only between intended entities.

You can use the below code template for Associate or Disassociate plugins

            EntityReference targetEntity = null;

            string relationshipName = string.Empty;

            EntityReferenceCollection relatedEntities = null;

            EntityReference relatedEntity = null;

            if (context.MessageName == “Associate”) {

                // Get the “Relationship” Key from context

                if…

View original post 93 more words

Missing dependencies – You’ll need to import the following items to this environment error while importing the solution – Dynamics 365 / Dataverse


Recently while trying to import one of the solutions we got the below error

Missing dependencies. You’ll need to import the following items to this environment.

It was referring to one of the Managed Solutions – DynamicsMKT_PushNotification, managed by Microsoft, for Microsoft Dynamics 365 Marketing.

We realized that the source environment had a higher version installed than the destination environment.

Source – 1.1.25335.61 and destination environment – 1.1.22667.44

Initially, we thought the error is because the Dev had full marketing app configured i.e. both Solution and Services app configured and the destination had only Dynamics 365 Marketing Solution Only app.

The marketing apps –

After raising the Microsoft Support, we got guidance/advice from the Microsoft Support / Product team that the Dynamics 365 Marketing Solution Only app was not installed in the destination environment and it was a copy of some other environment that had marketing installed. They suggested installing the Dynamics 365 Marketing Solution Only app in the destination environment. After installing the app, we could see the version of the DynamicsMKT_PushNotification solution increased and were able to install our custom solution successfully.

Hope it helps..

 

Advertisements

Sample Code – Enable / Disable Plugin Step (sdkmessageprocessingstep) Dynamics 365 / Dataverse


Recently we had to disable plugin steps as part of data migration, below is the sample code we can use, either specify the name of the assembly, plugin, or plugin step as we are using the “begins with” condition or make changes as required.

 class Program
    {
        static void Main(string[] args)
        {

            const string ConnectionString = "AuthType = OAuth; " +
                                            "Username = Nishant.Rana@xyz.com; " +
                                            "Password = testxyz; " +
                                            "Url = https://orgname.crm6.dynamics.com;" +
                                            "AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;" +
                                            "RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;" +
                                            "LoginPrompt=Auto";


            CrmServiceClient svc = new CrmServiceClient(ConnectionString);

            if (svc.IsReady)
            {
                try
                {
                    // we can specify step / plugin / assembly name
                    var pluginStepAssemblyName = "MyD365.Plugins.Core.Plugin.AssignOwner";
                    // 0 for active and 1 for inactive
                    var pluginStateCode = 0;                   

                    var query = new QueryExpression("sdkmessageprocessingstep");
                    query.ColumnSet = new ColumnSet("name", "sdkmessageprocessingstepid");
                    query.Criteria.AddCondition(new ConditionExpression("name", ConditionOperator.BeginsWith, pluginStepAssemblyName));
                    var sdkMsgProcessStepCollection = svc.RetrieveMultiple(query);

                    foreach (var sdkMsgProcessStep in sdkMsgProcessStepCollection.Entities)
                    {
                        var setStateRequest = new SetStateRequest();
                        setStateRequest.EntityMoniker = new EntityReference("sdkmessageprocessingstep", sdkMsgProcessStep.Id);
                        setStateRequest.State = new OptionSetValue(pluginStateCode);
                        setStateRequest.Status = new OptionSetValue(-1);
                        svc.Execute(setStateRequest);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception Messainge : {0} ", ex.Message);
                }

            }
        }
    }

Hope it helps..

Advertisements

Fixed – 0x90000010 Can not retrieve view’s metadata (Dynamics 365)


We were recently getting the below error in one of the views in the Dashboard.

0x90000010 Can not retrieve view’s metadata

The issue occurred because we had converted that Dashboard from a personal to System / Public Dashboard using the below wonderful XrmToolbox Plugin, https://www.xrmtoolbox.com/plugins/Carfup.XTBPlugins.PersonalViewsMigration/, which converted it to System Dashboard successfully, however, this was one of the personal views inside that dashboard.

So we converted that personal view to the system view (using the same tool) and then updated the Dashboard to refer to the converted system view, which fixed the issue.

Hope it helps..

Advertisements

Set DefaultSelectedItems of Combobox on App OnStart – Custom Page -Power Apps (Dataverse)


Recently in one of our custom pages, we had to set the default value (DefaultSelectedItems) of the combo box based on one of the lookup fields on the record. We were opening the custom page from the ribbon button on the form.

Below is our function to pass the record’s GUID to the custom page from the button.


    openSearchCustomPage: function (primaryControl, firstPrimaryItemId) {
        var pageInputCustom = {
            pageType: 'custom',
            name: 'custom_searchproduct_570ed',
            entityName: 'lead',
            recordId: firstPrimaryItemId
        };

        var navigationOptions = {
            target: 2,
            position: 1,
            width: 1350
        };

        Xrm.Navigation.navigateTo(pageInputCustom, navigationOptions).then(
            function success(result) {
                console.log(result);
            },
            function error(error) {
                console.log(error);
            }
        );
    }

Next in App’s OnStart, we are setting the GUID of the record to a variable first, and than setting another variable to store the GUID of the Region lookup field on that record.

// text variable passed by the form / webresource/ ribbon
Set(varEnquiryIdWithoutCurlyBraces,GUID(Substitute(Substitute(Param("recordId"),"{",""),"}","")));

// get the Region Of Interest from the Lead / Enquiry ID
// If value present use it for prefiltering the Gallery Items
Set(varRegionOfInterest,LookUp(Enquiries,Lead=varEnquiryIdWithoutCurlyBraces, 'Region of Interest'));

And lastly, for the combo box (Items = Region (custom table)), we are setting the DefaultSelectedItems as follows

LookUp(Regions,Region=varRegionOfInterest.Region)

We also tried using the Filter option, but it was giving incorrect values.

The value on the form –

The value in the Custom Page –

Correct value populated for combo box Region, and incorrect for the one using Filter formula

Hope it helps..

Advertisements

Fixed – View Name as Blank in Dynamics 365 / Model-driven app


Recently we faced an issue where one of the views was not showing its Name in the app.

On selecting the View Selector, we were not getting the option to select that view.

Checking in a Vanilla CRM instance, we can see it is OOB My Activities view.

To fix it, we had to edit the App, Add Page >> Dataverse Table >> Select exiting table >> Activity


And add that view to that app and publish the changes.

The result –

Hope it helps..

Advertisements