locked
CRM 2011: Update Plugin - option set values are not saved to database RRS feed

  • Question

  • Hi All,

    Requirement:

    Update option set value of entity B based on the option set value of entity A

    Problem:

    I was able to update the values as required but.... looks like that the value is not written/saved to the database. In other words, I can see that the entity B option set value has changed but it is not committed to the database (If i update some other field in entity B and hit "SAVE" - only then the value is saved/committed to database).

    More Inputs:

    There is another plugin which runs against the entity B's specific option set value when updated.

    Assumptions:

    I strongly feel that this is something to do with the "plugin event pipeline stage" and maybe with the code too

    I'm using pre-operation stage, sync plugin - update message

    Existing code:

    entityA= (Entity)context.InputParameters[EntityMessages.TargetMessage];
    
                                    if (entityA.Attributes.Contains(entityAMessage.Status1) && ((OptionSetValue)entityA.Attributes[entityAMessage.Status1]).Value == 1)
                                    {
    
                                Entity entityA= null;
                                QueryExpression qe = new QueryExpression("entity_b");
                                qe.Criteria.AddCondition("lookupfield", ConditionOperator.Equal, context.PrimaryEntityId);
    
                                EntityCollection results = service.RetrieveMultiple(qe);
                                        Entity b = new Entity("entity_b");
                                        b.Id = ((Entity)context.InputParameters["Target"]).Id;                                   
                                                                            
                                        results.Entities.ToList().ForEach(a =>
                                        {
                                           
                                          b.Id = a.Id;
                                          b["status2"] = new OptionSetValue(2); // Insert the value here                                                                            
                                          service.Update(b);
                                       
                                        });
                                     }

    I dont know what am i missing here, can anyone help!

    Thx,

    Matt

    Wednesday, July 22, 2015 1:21 PM

All replies

  • Hello,

    Your code looks correct.

    Could you provide code of nested plugin - that is triggered onchange of status2 field of entityb?


    Dynamics CRM MVP
    My blog

    Wednesday, July 22, 2015 2:36 PM
    Moderator
  • Thanks for looking into it Andriy, and sorry for the delay in response.

    Below, i have included the complete code of the nested plugin.

    By the way: the plugin  is triggered on  post-operation  - update message. 

    using System;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Crm.Sdk.Messages;
    
    namespace Plugins2
    {
        public class ApprovedPurchaseItem : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                try
                {
                    ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                    if (tracingService == null)
                    {
                        throw new InvalidPluginExecutionException(EntityMessages.TracingFailedMessage);
                    }
                    // Obtain the execution context from the service provider.           
                    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                    if (context.InputParameters.Contains(EntityMessages.TargetMessage))
                    {
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        tracingService.Trace(EntityMessages.CreationMessageServiceObjectMessage, DateTime.Now.ToString());
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                        if (context.MessageName == EntityMessages.UpdateMessageName)
                        {
    
                            if (context.Depth > 1)
                            {
                                return;
                            }
    
                            // Obtain the target entity from the input parmameters.
                            Entity targetEntity = (Entity)context.InputParameters[EntityMessages.TargetMessage];
                            if (targetEntity == null)
                            {
                                return;
                            }
                            tracingService.Trace(EntityMessages.TargetEntityContextMessage, DateTime.Now.ToString());
                            if (targetEntity.LogicalName == entityBEntityMessage.LogicalName)
                            {
                                Entity entityB = null;
                                //EntityReference entityBRef = null;
                                if (context.InputParameters.Contains(EntityMessages.TargetMessage) && context.InputParameters[EntityMessages.TargetMessage] is Entity)
                                {
    
                                    // Code for Item Names to get Budget Remaining Amount
                                    decimal actualRemainingAmount = 0;
                                    decimal budgetRemainingAmount = 0;
                                    entityB = (Entity)context.InputParameters[EntityMessages.TargetMessage];
                                    if (entityB.Attributes.Contains(entityBEntityMessage.Status2) && ((OptionSetValue)entityB.Attributes[entityBEntityMessage.Status2]).Value == 2)
                                    {
                                        string itemNameID = string.Empty;
                                        Entity entityC = null;
                                        ColumnSet cols = new ColumnSet(new String[] { entityBEntityMessage.TotalAmount, entityBEntityMessage.ItemNames });
                                        entityB = service.Retrieve(entityB.LogicalName, entityB.Id, cols);
    
                                        if (entityB.Attributes.Contains(entityBEntityMessage.ItemNames))
                                        {
                                            EntityReference entRefItemName = (EntityReference)entityB.Attributes[entityBEntityMessage.ItemNames];
                                            cols = new ColumnSet(new String[] { entityCMessage.ActualRemainingAmount });
                                            entityC = service.Retrieve(entityCMessage.LogicalName, entRefItemName.Id, cols);
                                            itemNameID = entRefItemName.Id.ToString();
                                            if (entityC != null && entityC.Attributes.ContainsKey(entityCMessage.ActualRemainingAmount))
                                            {
                                                actualRemainingAmount = ((Money)entityC.Attributes[entityCMessage.ActualRemainingAmount]).Value;
                                            }
                                        }
                                        // Code for Total Amount
                                        decimal totalAmount = 0;
                                        if (entityB.Attributes.Contains(entityBEntityMessage.TotalAmount))
                                        {
                                            totalAmount = ((Money)entityB.Attributes[entityBEntityMessage.TotalAmount]).Value;
                                        }
    
                                        actualRemainingAmount = actualRemainingAmount - totalAmount;
    
    
    
                                        // Update Item Name with Budgt Remaining Entity
                                        if (string.IsNullOrEmpty(itemNameID) == false)
                                        {
                                            if (entityC != null)
                                            {
                                                ((Money)entityC.Attributes[entityCMessage.ActualRemainingAmount]).Value = actualRemainingAmount;
                                                service.Update(entityC);
                                            }
    
                                        }
                                    }
                                    
    
    
                                }
    
    
    
                            }
                        }
                    }
    
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(ex.Message + " " + ex.StackTrace, ex);
                }
    
            }
        }
    }
    
    Your help is greatly appreciated!. Thanks.

    Wednesday, July 22, 2015 4:15 PM
  • Forgot to mention, this plugin (the nested one) triggers and works fine too. Only problem is, the trigger is not happening automatically (As it should)
    Wednesday, July 22, 2015 4:23 PM
  • Any inputs, please?
    Thursday, July 23, 2015 5:31 AM