Skip to main content

Notifications

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Service.Update Failure on SalesOrder

Posted on by 1,579

I have a plugin registered on quote that when a quote is re-set to draft, any previously created orders will be cancelled.

My problem is the plugin is failing on the cancellation of the orders. 

The relevant portion of the code is shown below. 

I basically pass it the entity collection which contains all the orders that need to be updated with statecode 2. 

The service.update portion is failing.

An unexpected error occurred from ISV code. 
(ErrorType = ClientError) Unexpected exception from plug-in (Execute): 
ACEQuoteCleanUp.CleanOrdersOnClosedQuotes.PostOperationquoteUpdate: 
System.Exception: Error in top level UPDATE at TRY: Error in IF/TRY Failed to Update Entities: 
Error converting attribute value to Property: Attribute [statuscode], 
Attribute type [status] of Entity [salesorder] 
with value of type [System.Int32]: [System.InvalidCastException: 
Unable to cast object of type 'System.Int32' to type 'Microsoft.Xrm.Sdk.OptionSetValue'. 
at Microsoft.Crm.BusinessEntities.StatusPropertyConverter.InternalFromEntity(ICrmConversionContext 
conversionContext, AttributeMetadata attributeMetadata, 
Object value, String formattedValue) at Microsoft.Crm.BusinessEntities.PropertyConverterBase.<>c__DisplayClass7_0.b__0() 
at Microsoft.Crm.BusinessEntities.PropertyConverterBase.InternalConvertFrom[T](Guid orgId, 
AttributeMetadata attributeMetadata, Object value, F

Any help or guidance would be greatly appreciated. 

  protected void Update_ReturnedOrders(IPluginExecutionContext ContextReturnedOrders, IOrganizationService OrgSvcReturnedOrders, ITracingService TracingSvc, LocalPluginContext ReturnedOrdersContext, EntityCollection ReturnedOrdersEntityCollection, string StateCodeFieldNameToUpdate, int NewVal)
        {
            ContextReturnedOrders = ReturnedOrdersContext.PluginExecutionContext;
            OrgSvcReturnedOrders = ReturnedOrdersContext.OrganizationService;
            TracingSvc = ReturnedOrdersContext.TracingService;

            TracingSvc.Trace("StateCodeFieldNameToUpdate: "   StateCodeFieldNameToUpdate);
            TracingSvc.Trace("Int Value of OptionSet: "   NewVal);
            if (ContextReturnedOrders.InputParameters.Contains("Target") && ContextReturnedOrders.InputParameters["Target"] is Entity)
            {
                TracingSvc.Trace("Entered Final If Statement.");
                try
                {
                    TracingSvc.Trace("Entered Final Try Statement.");
                    foreach (Entity e in ReturnedOrdersEntityCollection.Entities)
                    {
                        TracingSvc.Trace("Tracelog Entry Immediately Pre-Ceeding The Update");
                        e[StateCodeFieldNameToUpdate] = (int)(NewVal);
                        OrgSvcReturnedOrders.Update(e);

                    }
                    

If I change the code from this:

 e[StateCodeFieldNameToUpdate] = (int)(NewVal);

to this:

e[StateCodeFieldNameToUpdate] = new OptionSetValue(NewVal);
 

I get this:

An unexpected error occurred from ISV code. 
(ErrorType = ClientError) Unexpected exception from plug-in (Execute): 
ACEQuoteCleanUp.CleanOrdersOnClosedQuotes.PostOperationquoteUpdate: 
System.Exception: Error in top level UPDATE at TRY: 
Error in IF/TRY Failed to Update Entities: 
Error converting attribute value to Property: 
Attribute [quoteid], Attribute type [lookup] of Entity [salesorder] with value of type [Microsoft.Xrm.Sdk.OptionSetValue]: 
[System.InvalidCastException: Unable to cast object of type 'Microsoft.Xrm.Sdk.OptionSetValue' to type 
'Microsoft.Xrm.Sdk.EntityReference'. at Microsoft.Crm.BusinessEntities.LookupPropertyConverter.InternalFromEntity(ICrmConversionContext conversionContext, 
AttributeMetadata attributeMetadata, 
Object value, String formattedValue) at Microsoft.Crm.BusinessEntities.PropertyConverterBase.<>c__DisplayClass7_0.b__0() 
at Microsoft.Crm.BusinessEntities.PropertyConverterBase.InternalConvertFrom[T]
(Guid orgId, AttributeMetadata attributeMetadata, Object value, Func`1 converterFunction)]

Based on the content of the error messages, it appears the following code is the actual problem. 

e[StateCodeFieldNameToUpdate]

What do I need to do to get this working? 

Any advice or recommendations would be greatly appreciated. 

  • Wahaj Rashid Profile Picture
    Wahaj Rashid 11,319 on at
    RE: Service.Update Failure on SalesOrder

    You are welcome :)

  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: Service.Update Failure on SalesOrder

    Yes. The logical name is "salesorder".

    My problem is solved! Thanks so much!

  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: Service.Update Failure on SalesOrder

    Getting close.... but still have an error.

    An unexpected error occurred from ISV code. 
    (ErrorType = ClientError) Unexpected exception from plug-in (Execute): 
    ACEQuoteCleanUp.CleanOrdersOnClosedQuotes.PostOperationquoteUpdate: 
    System.Exception: Error in top level UPDATE at TRY: 
    Error in IF/TRY Failed to Update Entities: 
    The entity with a name = 'order' with namemapping = 'Logical' 
    was not found in the MetadataCache. 
    MetadataCacheDetails: ProviderType=Dynamic, StandardCache=True, 
    IsLoadedInStagedContext = False, Timestamp=24618337, 
    MinActiveRowVersion=24618337, MetadataInstanceId=59725993, 
    LastUpdated=2021-02-08 05:37:14.223
    Error code: 0x80040265

    Should the logical name be "salesorder"?

    8787.Error.png

  • Verified answer
    Wahaj Rashid Profile Picture
    Wahaj Rashid 11,319 on at
    RE: Service.Update Failure on SalesOrder

    Hi,

    Thank you for your query.

    There are 2 issues in the code:

    1. StateCode is an optionset but your setting it as INT.
    2. Second, to change the status using Organization Service you must use SetStateRequest instead of Update.

    Here is an example:

    //Update Status
    SetStateRequest setStateRequest = new SetStateRequest()
    {
       EntityMoniker = new EntityReference
       {
           Id = orderId, //Order GUID
           LogicalName = "order", //Order Entity Logical Name
       },
       State = new OptionSetValue(2), // Status: Cancelled
       Status = new OptionSetValue(4)  //Status Reason: No money
    };
    
    orgService.Execute(setStateRequest);

    To summarize, you need to use SetStateRequest instead of Update, and in the request you need to Pass new Status and Status Reason.

    You can see following post for further help:

    https://thomasthankachan.wordpress.com/2011/10/06/plugin-usage-of-setstate-and-statestatedynamicentity-message/

    Here is a list of statecode and statuscodes (including order):

    https://www.tpein.dk/?page_id=210

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans