Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM forum
Suggested answer

Plugin errors while creating an entity and trying to increment the value of an attribute by default

Posted on by 355

Hi,

I created a plugin which is triggered by a "Create" event and should assign a value to the "code" attribute by incrementing the code number of the last target entity created.
The code attribute is a whole number, and it's set as unique key.

When the plugin was triggered I got two different errors, this was the first one:

A record that has the attribute values Code already exists. The entity key Movie Code requires that this set of attributes contains unique values. Select unique values and try again.

The second one was a different business process error.

I downloaded both error log files and debugged in exception mode and realized that the last instructions have not be hit: could you please help me to understand if the issue depends on a wrong implementation? This is my Plugin code:

public void Execute(IServiceProvider serviceProvider)
        {
            var context = new PluginContext(serviceProvider);
            var service = context.CrmServiceSystem;
            var trace = context.TracingService;
            var target = context.GetTarget();

            var currentEntity = (Entity)context.InputParameters["Target"];

                          // query to retrieve all entities of the selected type:
            QueryExpression query = new QueryExpression("Target");
            query.ColumnSet = new ColumnSet("code");

                          // retrieve the last movie created:
            query.AddOrder("createdon", OrderType.Descending);
            query.TopCount = 1;
            var latestRecord = service.RetrieveMultiple(query).Entities.FirstOrDefault();

                          // retrieve the code of the retrieved entity
            var latestRecordCode = (int)latestRecord.Attributes["code"];

                          // increment the code by 1 and assign it to the current entity
            latestRecordCode++;
            currentEntity.Attributes["code"] = latestRecordCode;
        }

While debugging in exception mode, I realized that the variable latestRecord was given the correct value, but the instruction at line 23 ("latestRecordCode++") wasn't reached, I then changed the previous instruction as below:

Int32 latestRecordCode = Convert.ToInt32(latestRecord.Attributes["code"].ToString());

but I got a different issue: the instruction "latestRecordCode++;" is reached now, but the variable latestRecord is null.


Also, on the Plugin Registration Tool I looked for the profiles that should have been created when the plugin was triggered (instead than uploading the error log file) but I could not find any profile, are they supposed to be there?

  • Joel D Profile Picture
    Joel D 355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Manish,

    thank you for your tips.

    I changed line 14 but got the same errors.

    Yes, "code" is the logical name ("Name" column, in the crm solution) for both entities.

    As regard to querying both entities for max code, I actually need the code of the last record of the target entity (and it's already supposed to be the max code) not the maximum value in absolute. For example, when the plugin is triggered by the Create operation of a movie, if the max code value from Movies is 10, the code of the new record will be 11. If I trigger the plugin while creating a collection, as the max code value from all the collections is 5, the code value of the new one will be 6.

  • Manish Sonar Profile Picture
    Manish Sonar 40 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Joel,

    Can you try changing line number 14 to below:

    QueryExpression query = new QueryExpression(currentEntity.LogicalName);

    Please make sure that "code" is a logical name for respective field. Also as you said you are using same Code logic for for two different entities, in that case you might have to query both entities for max code and consider max from those two.

    In case  query expression still doesn't work you can try FetchExpression as a replacement. Refer below url:

    https://docs.microsoft.com/en-us/powerapps/developer/data-platform/use-fetchxml-construct-query

    Let me know if this solves your issue..

  • Joel D Profile Picture
    Joel D 355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Manish, yes, sure:

    public class IncrementCode : IPlugin
    {
            public void Execute(IServiceProvider serviceProvider)
            {
                var context = new PluginContext(serviceProvider);
                var service = context.CrmServiceSystem;
                var trace = context.TracingService;
                var target = context.GetTarget();
    
                if (target == null)
                    return;
    
                Entity currentEntity = (Entity)context.InputParameters["Target"];
                QueryExpression query = new QueryExpression("Target");
                query.ColumnSet = new ColumnSet(true);
                query.Criteria.AddCondition("code", ConditionOperator.NotNull);
                query.AddOrder("createdon", OrderType.Descending);
                query.TopCount = 1;
    
                var recordList = service.RetrieveMultiple(query);
                int latestRecordCode = 0;
    
                if (recordList.Entities.Count > 0)
                {
                    Entity latestRecord = recordList[0];
                    if (latestRecord.Attributes.Contains("code") == true)
                    {
                        latestRecordCode = (int)latestRecord.Attributes["code"];
                        currentEntity.Attributes["code"] = latestRecordCode  ;
                    }
                }           
            }
    
    }

  • Manish Sonar Profile Picture
    Manish Sonar 40 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Joel,

    Can you post you updated code here?

  • Joel D Profile Picture
    Joel D 355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi,

    thank you for replying.

    Something anomalous happened when I triggered the plugin from another entity (the plugin is associated both to Movies and the Notebook entity): the first time I tried to save a new Notebook, it was saved successfully, but the code was given the value of the last Movie incremented by one (instead that of the last Notebook).

    The second time I tried to save another Notebook I got the same error as before, the first one ("A record that has the attribute values Code already exists...").

    The third time I got the other error, I then downloaded the error log file.

    While debugging in exception mode, the variable currentEntity is null (error CS0103: The name 'currentEntity' does not exist in the current context); the variable recordList is null too ("error CS0103: The name 'recordList' does not exist in the current context"). But the latestRecordCode has a value "9", which is equivalent to the code of the last Movie successfully saved (but I'm on the  Notebook  form, and the last code is 10)...

  • Suggested answer
    Manish Sonar Profile Picture
    Manish Sonar 40 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Joel,

    It seems service.RetrieveMultiple(query) is returning 0 entities in EntityCollection. Read "Code" field from "latestRecord" entity and set it in "latestRecordCode" if there is any entity retrieved from Query expression or else default value 0 will be used for "latestRecordCode". Your code should look like this:

    var latestRecordlist = service.RetrieveMultiple(query);

    int latestRecordCode = 0;

    if (latestRecordlist.Entities.Count > 0)

    {

       Entity latestRecord = latestRecord[0];

       if (latestRecord..Attributes.Contain("code"))

       {

           latestRecordCode = (int)latestRecord[0].Attributes["code"];

       }

    }

    // increment the code by 1 and assign it to the current entity

    currentEntity.Attributes["code"] = latestRecordCode++;

    Hope it helps.

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,313 Super User on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Regarding the check I thought of something like

    query.Criteria.AddCondition("code", ConditionOperator.NotNull);

    Regarding the "?" operator you can read here - docs.microsoft.com/.../member-access-operators

  • Joel D Profile Picture
    Joel D 355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hello,

    thank you for replying.

    I added the check condition as below (but I'm getting the same issues), did you mean the following?

    if(latestRecord.Attributes.Contains("code") != false)

    {
        (int)latestRecord.Attributes["code"];
        var latestRecordCode = latestRecord?.GetAttributeValue<int>("code");
        latestRecordCode++;
        currentEntity.Attributes["code"] = latestRecordCode;
    }
    else
    {
        throw new InvalidPluginExecutionException(OperationStatus.Failed, "The latest record was saved without a code");
    }

    Can you please explain to me the line of code you suggested:
    var latestRecordCode = latestRecord?.GetAttributeValue<int>("code");
    Is that "?" a ternary operator?

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,313 Super User on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hello,

    Here are few recommendations:

    1. Add the check condition to your query that "code" field is not null.

    2. Use following code to get latestRecordCode:

    var latestRecordCode = latestRecord?.GetAttributeValue<int>("code");

    if there is latestRecord or "code" is blank - modified code will not throw an error but will get latestRecordCode to int.Default that is 0.

Helpful resources

Quick Links

Replay now available! Dynamics 365 Community Call (CRM Edition)

Catch up on the first D365 Community Call held on 7/10

Community Spotlight of the Month

Kudos to Saurav Dhyani!

Congratulations to the June Top 10 community leaders!

These stars go above and beyond . . .

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 287,696 Super User

#2
Martin Dráb Profile Picture

Martin Dráb 225,490 Super User

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans