Using addPreSearch with an asynchronous call to create the filter

Hello everyone;

Recently while answering questions on the Microsoft Forums a question was raised about how to filter the query of an addPreSearch lookup event based on values in a relationship.

The scenario we’re looking at is we have a table called “Collection”.  This table has a M:1 relationship with director and it has a 1:M relationship with a table called Movies. The Movies table has a M:1 relationship with the director table. 

The requirement is to have the Director lookup prefilter and only show a list of directors from movies related to the collection. In the picture below when we click on the Directors lookup we would expect to see 6 directors selectable based on the associated movies.

Collection Table Form

How we go about this is using three specific methods:

The addPreSearch allows you to specify what event will fire when a user clicks on the lookup. In this function you to pass in a function and it must then add a custom filter.
– formContext.getControl(arg).addPreSearch(myFunction)

The addCustomFilter function is an event that executes when you click on the lookup field and executes the filter or fetchxml filter passed into it.
– formContext.getControl(arg).addCustomFilter(filter, entityLogicaName)

The Xrm.WebApi.retrieveMultipleRecords is a method that allows us to retrieve multiple records but this is an asynchronous call which causes the issue of building the proper filter in this scenario.

What we need to do to achieve the goal of filtering the directors lookup based on the related movies to the collection are the following steps:

  1. Execute a Xrm.WebApi.retrieveMultipleRecords allowing us to build the filter statement with the proper directors.
  2. Once the filter statement has been completed we need to call the addCustomerFilter function.
  3. We need to have our function that calls the addPreSearch when the lookup event is changed using the filter statement.

Let’s dive into the code. I’ll post my full web resource file and we can discuss it in more detail below. This web resource file can also be found on github at https://github.com/jasoncosman/Collections/blob/master/jcmvp_collection.js.

 

    OnLoad: function (executionContext) {
        JCMVP.Collection.Form.getCollectionsMovies(executionContext);
    },


    filterMovieDirectors: function () {
        //https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addcustomfilter
        formContext.getControl("jcmvp_director").addCustomFilter(fetchDirectorFilter, "jcmvp_director");
    },


    getCollectionsMovies: function (executionContext) {
        formContext = executionContext.getFormContext();

        var collectionID = formContext.data.entity.getId().replace("{", "").replace("}", "");

        //https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webapi/retrievemultiplerecords
        Xrm.WebApi.retrieveMultipleRecords("jcmvp_movie", "?$select=_jcmvp_director_value&$filter=(_jcmvp_collection_value eq " + collectionID + ")").then(
            function success(result) {
                debugger;

                if (result.entities.length > 0) {
                    fetchDirectorFilter = "<filter type='and'> <condition attribute = 'jcmvp_directorid' operator = 'in' uitype='jcmvp_director'>";
                }

                for (var i = 0; i < result.entities.length; i++) {
                    //_jcmvp_director_value
                    fetchDirectorFilter += "<value>" + result.entities[i]._jcmvp_director_value + "</value>";
                    console.log(result.entities[i]);
                }
                if (result.entities.length > 0) {
                    fetchDirectorFilter += "</condition ></filter >";
                    //https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addcustomfilter
                    formContext.getControl("jcmvp_director").addPreSearch(JCMVP.Collection.Form.filterMovieDirectors);    
                }

            },
            function (error) {
                console.log(error.message);
                // handle error conditions
            }

            
        );

    }

We start with calling the getCollectionsMovies function on the form load event. This function will execute our query to get the related movies and director column filtering on the collection table id your currently on.
– Xrm.WebApi.retrieveMultipleRecords(“jcmvp_movie”, “?$select=_jcmvp_director_value&$filter=(_jcmvp_collection_value eq ” + collectionID + “)”).then(

This is an asynchronous call that when it completes it will work towards building our filter and storing it on our global variable “fetchDirectorFilter”. An example of the built filter statement looks like this:
“<filter type=’and’> <condition attribute = ‘jcmvp_directorid’ operator = ‘in’ uitype=’jcmvp_director’><value>889c9059-865d-eb11-a812-000d3a84f1a3</value><value>03fa2f78-865d-eb11-a812-000d3a84f1a3</value><value>889c9059-865d-eb11-a812-000d3a84f1a3</value><value>40d8e290-865d-eb11-a812-000d3a84f1a3</value><value>78d8e290-865d-eb11-a812-000d3a84f1a3</value><value>93034497-865d-eb11-a812-000d3a84f1a3</value><value>15920af3-6d5f-eb11-a812-000d3a84f1a3</value></condition ></filter >”.

After our filter statement has been created we’re going then go ahead and use the addPreSearch function. formContext.getControl(“jcmvp_director”).addPreSearch(JCMVP.Collection.Form.filterMovieDirectors);). This will allow for when the user clicks on the director lookup on the collection form it fires the filterMovieDirectors function.

When the user clicks on the director field it will execute the function filterMovieDiretors. This function will use our built filter and set it for the lookup. formContext.getControl(“jcmvp_director”).addCustomFilter(fetchDirectorFilter, “jcmvp_director”);

This code scenario is covering when the form loads or refreshes. What it doesn’t cover is updating the director list when a movie is added to the collection. I’ll work through this and post an additional blog post when I have that completed.

Don’t forget to upgrade assemblies for custom code in Dynamics 365 v9+ upgrade!

Upgrading to the latest platform is never something to underestimate with any product. With Dynamics 365 we’ve experienced such rapid platform changes over the past 8 years we should be all getting used to some of the pieces of an upgrade.

With the Dynamics 365 V9+ update we have to remember to upgrade our custom code assemblies. This should be fairly straight forward if your using NuGet packages in your projects. Microsoft has invested into lots of different packages like https://www.nuget.org/packages/Microsoft.CrmSdk.CoreAssemblies/ .

I use Visual Studio for my custom code components like plugins and custom workflow activities.  After opening the project I’ve selected manage NuGet packages and I get a screen like this:

This update process also helps resolve any dependencies and highlights any errors if they occur. A great example of this is I mentioned before I’m using FakeXrmEasy as my unit test framework. This will need to be updated as well; in this example FakeXrmEasy has dependencies displayed on the bottom for the CrmSdk.CoreAssemblies less then version 9.0.0.

Since we’re upgrading into Dynamics 365 V9+ we need to make sure our unit test framework is using the right assemblies. In this case FakeXrmEasy provides a separate NuGet package for Dynamics 365 V9+; we’d simply remove the FakeXrmEasy.365 NuGet package and then install the new one.

Of course after doing this and deploying your assemblies into Dynamics 365 you have to test like crazy.

The more you know!

My experience writing unit tests with FakeXRMEasy

Hello;

I thoroughly enjoy writing unit tests with FakeXRMEasy. It’s a framework that allows you to fake the Dynamics 365 services into the proper contexts and then use the messages against it. It can be found at https://dynamicsvalue.com/.

The positives I’ve found from using this framework are:

  • I’m able to debug the custom code without ever having to leave Visual Studio.
    • No more spending time getting plugins to debug properly through visual studio
  • I’m able to replicate a wide variety of scenarios through data in my unit tests without having to step through everyone within the Dynamics 365 platform itself.
  • Works with custom workflow activities, plugins, portals, javascript.

Let’s walk through a piece of code. The scenario is we are building a sports application in Dynamics 365; when a game ends a plugin triggers. This plugin updates the winning team with the win as well a point total; then adds a loss to the losing team. Let’s examine the plugin first.

        public void Execute(IServiceProvider serviceProvider)
        {
            
            
            if(serviceProvider ==null)
            {
                throw new ArgumentNullException("serviceProvider", "serviceProvider cannot be a null refrence");
            }

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

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            //Lets get the game information and update each teams record
            Entity target = (Entity)context.InputParameters["Target"];

            try
            {
                Entity aGame = null;

                tracingService.Trace("Let's get the game entity with all of it's columns. The ID is:" + target.Id.ToString());
                if(context.MessageName== "Update")
                {
                    aGame = (Entity)service.Retrieve(target.LogicalName, target.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));                
                }
                else
                {
                    throw new Exception("Plugin:EndGame - This plugin should only be executed against an update message not a create or delete.");
                }

                //Let's validate that it returned something
                if(aGame != null)
                {
                    EntityReference homeTeam = null;
                    if(aGame.Attributes.Contains("jmvp_hometeam"))
                    {
                        homeTeam = (EntityReference)aGame.Attributes["jmvp_hometeam"];
                    }

                    EntityReference awayTeam = null;
                    if (aGame.Attributes.Contains("jmvp_awayteam"))
                    {
                        awayTeam = (EntityReference)aGame.Attributes["jmvp_awayteam"];
                    }

                    OptionSetValue gameOutcome = null;
                    if (aGame.Attributes.Contains("jmvp_outcome"))
                    {
                        gameOutcome = (OptionSetValue)aGame.Attributes["jmvp_outcome"];
                        //Home - 492,470,000
                        //Away - 492,470,001
                        //Tie  - 492,470,002
                    }

                    Entity homeTeamEntity = getEntitywithFields(homeTeam, true, service);

                    Entity awayTeamEntity = getEntitywithFields(awayTeam, true, service);

                    switch(gameOutcome.Value)
                    {
                        //Home
                        case 492470000:
                            homeTeamEntity.Attributes["jmvp_winrecord"] = (int)homeTeamEntity.Attributes["jmvp_winrecord"] + 1;
                            homeTeamEntity.Attributes["jmvp_totalpoints"] = (int)homeTeamEntity.Attributes["jmvp_totalpoints"] + 2;
                            awayTeamEntity.Attributes["jmvp_lossrecord"] = (int)awayTeamEntity.Attributes["jmvp_lossrecord"] + 1;
                            service.Update(homeTeamEntity);
                            service.Update(awayTeamEntity);
                            break;
                        //Away
                        case 492470001:
                            awayTeamEntity.Attributes["jmvp_winrecord"] = (int)awayTeamEntity.Attributes["jmvp_winrecord"] + 1;
                            awayTeamEntity.Attributes["jmvp_totalpoints"] = (int)awayTeamEntity.Attributes["jmvp_totalpoints"] + 2;
                            homeTeamEntity.Attributes["jmvp_lossrecord"] = (int)homeTeamEntity.Attributes["jmvp_lossrecord"] + 1;

                            service.Update(awayTeamEntity);
                            service.Update(homeTeamEntity);
                            break;
                        //Tie
                        case 492470002:
                            break;   



                    }


                }



            }
            catch(Exception ex)
            {
                throw (ex);
            }

        }

        private Entity getEntitywithFields(EntityReference entityToRetrieve, Boolean columnSet, IOrganizationService service)
        {

            return service.Retrieve(entityToRetrieve.LogicalName, entityToRetrieve.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(columnSet));


        }
    }

As you can see it simple does a check on the jmvp_outcome field to determine who won and updates appropriately. Now using FakeXRMEasy let’s walk through two separate unit tests. The first one is where the home team wins the game.

[TestMethod()]
        public void HomeTeamWins()
        {
            

            var fakedContext = new XrmFakedContext();

            var team1 = new Entity("jmvp_sportsteam");
            team1.Id = Guid.NewGuid();
            team1["jmvp_name"] = "Canadiens";
            team1["jmvp_winrecord"] = 10;
            team1["jmvp_lossrecord"] = 8;
            team1["jmvp_totalpoints"] = 20;

            var team2 = new Entity("jmvp_sportsteam");
            team2.Id = Guid.NewGuid();
            team2["jmvp_name"] = "Maple Leafs";
            team2["jmvp_winrecord"] = 12;
            team2["jmvp_lossrecord"] = 6;
            team2["jmvp_totalpoints"] = 24;

            var game1 = new Entity("jvmp_game");
            game1.Id = Guid.NewGuid();
            game1["jvmp_name"] = "November 5th - Canadiens vs Maple Leafs";
            game1["jmvp_hometeam"] = new EntityReference(team1.LogicalName, team1.Id);
            game1["jmvp_awayteam"] = new EntityReference(team2.LogicalName, team2.Id);
            game1["jmvp_outcome"] = new OptionSetValue(492470000);

            fakedContext.Initialize(new List<Entity>()
            {
                team1, team2, game1, game2
            });


            

            ParameterCollection inputParameters = new ParameterCollection();
            inputParameters.Add("Target", game1);

            var plugCtx = fakedContext.GetDefaultPluginContext();
            plugCtx.MessageName = "Update";
            plugCtx.InputParameters = inputParameters;
            plugCtx.Depth = 1;

            var FakedPlugin = fakedContext.ExecutePluginWith<EndGame>(plugCtx);

            IOrganizationService service = fakedContext.GetOrganizationService();

            Entity updatedHomeTeam = service.Retrieve(team1.LogicalName, team1.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

            Entity updatedAwayTeam = service.Retrieve(team2.LogicalName, team2.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(((int)team1["jmvp_winrecord"] + 1), (int)updatedHomeTeam["jmvp_winrecord"]);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(((int)team1["jmvp_totalpoints"] + 2), (int)updatedHomeTeam["jmvp_totalpoints"]);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(((int)team2["jmvp_lossrecord"] + 1), (int)updatedAwayTeam["jmvp_lossrecord"]);


        }

Let’s dive a bit deeper into this unit test. First we create the entities and data set. Then we load it into the faked context “XrmFakedContext”.

            var fakedContext = new XrmFakedContext();

            var team1 = new Entity("jmvp_sportsteam");
            team1.Id = Guid.NewGuid();
            team1["jmvp_name"] = "Canadiens";
            team1["jmvp_winrecord"] = 10;
            team1["jmvp_lossrecord"] = 8;
            team1["jmvp_totalpoints"] = 20;

            var team2 = new Entity("jmvp_sportsteam");
            team2.Id = Guid.NewGuid();
            team2["jmvp_name"] = "Maple Leafs";
            team2["jmvp_winrecord"] = 12;
            team2["jmvp_lossrecord"] = 6;
            team2["jmvp_totalpoints"] = 24;

            var game1 = new Entity("jvmp_game");
            game1.Id = Guid.NewGuid();
            game1["jvmp_name"] = "November 5th - Canadiens vs Maple Leafs";
            game1["jmvp_hometeam"] = new EntityReference(team1.LogicalName, team1.Id);
            game1["jmvp_awayteam"] = new EntityReference(team2.LogicalName, team2.Id);
            game1["jmvp_outcome"] = new OptionSetValue(492470000);

            fakedContext.Initialize(new List<Entity>()
            {
                team1, team2, game1, game2
            });

Once we’ve  initialized our fakedContext we’re ready to setup the input parameters and define some information around this plugin. When setting up the plugin information we’re able to select the message name which allows us to handle all of messages; which means we can unit test against any of the events. We set the entity that’s trigger the plugin and how much data we want to pass into it. Then i’m setting the depth of the plugin which can be important. The last thing that needs to be done is to actually execute the plugin itself.

            ParameterCollection inputParameters = new ParameterCollection();
            inputParameters.Add("Target", game1);

            var plugCtx = fakedContext.GetDefaultPluginContext();
            plugCtx.MessageName = "Update";
            plugCtx.InputParameters = inputParameters;
            plugCtx.Depth = 1;

            var FakedPlugin = fakedContext.ExecutePluginWith<EndGame>(plugCtx);

The last thing that I do is to validate my expected outcomes. In this case I want to ensure team 1’s properly got the additional points and win record. As well team 2’s loss total has increased by one.

            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(((int)team1["jmvp_winrecord"] + 1), (int)updatedHomeTeam["jmvp_winrecord"]);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(((int)team1["jmvp_totalpoints"] + 2), (int)updatedHomeTeam["jmvp_totalpoints"]);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(((int)team2["jmvp_lossrecord"] + 1), (int)updatedAwayTeam["jmvp_lossrecord"]);

Although this is a very simple example of a unit test; I think it gives a good example of whats within the capability of mocking up the fakedContext.

Hope this helps!