locked
crm plugin error - Error in return product Plug-in:EntityState must be set to null, Created (for Create message) or Changed (for Update message) RRS feed

  • Question

  • Hello All,

    Greeting!!

    Below is my crm 2011 plugin code

      protected void ExecutePostOrderProductUpdate(LocalPluginContext localContext)
            {
                if (localContext == null)
                {
                    throw new ArgumentNullException("localContext");
                }

                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
                var ServiceContext = new OrganizationServiceContext(service);
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity OP = (Entity)context.InputParameters["Target"];

                    string orderId = "", orderDetailId = "", orderName = "", fetchOrderDetails="";
                    int oStatus;
                    string orderAutoId="";
                    Guid tId = new Guid();
                    try
                    {
                        Guid _OPId = new Guid(OP.Id.ToString());
                        string opid = OP.Id.ToString();

                        var res = from c in ServiceContext.CreateQuery("salesorderdetail")
                                  //  where (c["new_vendorproductid"].Equals("SHP1") && c["quoteid"].Equals(quote.Id.ToString()))  
                                  where (c["salesorderdetailid"].Equals(OP.Id.ToString()))
                                  select c;

                        foreach (var odR in res)
                        {
                            if (odR.Attributes.Contains("salesorderdetailid"))
                            {
                                orderDetailId = ((Guid)odR.Attributes["salesorderdetailid"]).ToString();

                                if (odR.Attributes.Contains("new_orderstatus"))
                                {
                                    // oStatus = odR.Attributes["new_orderstatus"].ToString();
                                    oStatus = ((OptionSetValue)(odR.Attributes["new_orderstatus"])).Value;
                                    /*
                                     * check the order attached return is availble
                                     * if not create one
                                     *
                                     * */

                                    if (oStatus == 862410000)
                                    {
                                        Entity Return = new Entity("cse_return");

                                        //order

                                        if (odR.Attributes.Contains("salesorderid"))
                                        {
                                            Return["cse_order"] = odR.Attributes["salesorderid"];
                                            orderId = ((EntityReference)odR.Attributes["salesorderid"]).Id.ToString();
                                        }
                                        //order
                                       
                                        string orderIdQ = "{" + orderId + "}";
                                        fetchOrderDetails = @"<fetch mapping='logical'>
                                                <entity name='salesorder'><all-attributes/>
                                                    <filter type='and'>
                                                            <condition attribute='salesorderid' uitype='salesorder' operator='eq' value='" + orderIdQ + "'/></filter></entity></fetch>";
                                        EntityCollection resultOrder = service.RetrieveMultiple(new FetchExpression(fetchOrderDetails));
                                        Entity vOrder = resultOrder.Entities[0];

                                        if (!String.IsNullOrEmpty(vOrder.Attributes["ordernumber"].ToString()))
                                        orderAutoId = vOrder.Attributes["ordernumber"].ToString();
                                        if (!String.IsNullOrEmpty(vOrder.Attributes["customerid"].ToString()))
                                        {
                                            Return["new_customer"] = vOrder.Attributes["customerid"];
                                        }
                                         if (!String.IsNullOrEmpty(vOrder.Attributes["name"].ToString()))
                                         orderName = vOrder.Attributes["name"].ToString();

                                         Return["new_name"] = orderName;
                                         Return["new_orderid"] = orderAutoId;
                                         tId =  service.Create(Return);
                                       

    // error here while updating

                                         odR["new_return"] = new EntityReference("new_return", tId );

                                         service.Update(odR);                                    
                                         
                                      
                                    }
                                }

                            }
                         
                        }


                    }
                    catch (Exception ex)
                    {
                        throw new InvalidPluginExecutionException("Error in return product  Plug-in:" + ex.Message );
                    }
                }

    After creating a return entity record when i try to update the order product with new return record i am getting the following error

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Error in return product  Plug-in:EntityState must be set to null, Created (for Create message) or Changed (for Update message)

    Detail:
    <OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
      <ErrorCode>-2147220891</ErrorCode>
      <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
        <KeyValuePairOfstringanyType>
          <d2p1:key>CallStack</d2p1:key>
          <d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">   at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
       at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
       at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
       at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
       at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion)
       at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, UserAuth userAuth, Guid targetUserId, Boolean traceRequest, OrganizationContext context, Boolean returnResponse)
       at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
       at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)</d2p1:value>
        </KeyValuePairOfstringanyType>
        <KeyValuePairOfstringanyType>
          <d2p1:key>OperationStatus</d2p1:key>
          <d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">0</d2p1:value>
        </KeyValuePairOfstringanyType>
      </ErrorDetails>
      <Message>Error in return product  Plug-in:EntityState must be set to null, Created (for Create message) or Changed (for Update message) </Message>
      <Timestamp>2014-03-04T11:03:59.082937Z</Timestamp>
      <InnerFault i:nil="true" />
      <TraceText>

    [Return.ReturnProduct: Return.ReturnProduct.PostOrderProductUpdate]
    [730944fd-a5a2-e311-8d01-00155d059e08: PostOrderProductUpdate]
    Entered Return.ReturnProduct.PostOrderProductUpdate.Execute(), Correlation Id: 90d5df0d-6bfd-45be-bf20-4143fb27a30e, Initiating User: 43e28b45-b8ae-e011-abc2-00155d14c502
    Return.ReturnProduct.PostOrderProductUpdate is firing for Entity: salesorderdetail, Message: Update, Correlation Id: 90d5df0d-6bfd-45be-bf20-4143fb27a30e, Initiating User: 43e28b45-b8ae-e011-abc2-00155d14c502
    Exiting Return.ReturnProduct.PostOrderProductUpdate.Execute(), Correlation Id: 90d5df0d-6bfd-45be-bf20-4143fb27a30e, Initiating User: 43e28b45-b8ae-e011-abc2-00155d14c502

    </TraceText>
    </OrganizationServiceFault>

    Please suggest me how to rectify this issue. The plugin is registered in Update message   post- operation pipeline.

    Many Thanks,

    Rand

    Tuesday, March 4, 2014 11:30 AM

All replies

  • In your query for salesorderdetail records you have not specified the attributes to return. I assume the query is therefore returning all attributes, including some that are not ValidForUpdate, so you get the error when you try passing one of the returned records to the Update method. You should change the query to only include the fields you need, or create a new Entity instance with just the Id and the new_return attributes set, and pass that to the Update method

    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Tuesday, March 4, 2014 6:29 PM
    Moderator