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?