web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Service.Update Failure on SalesOrder

(0) ShareShare
ReportReport
Posted on by 1,589

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. 

I have the same question (0)
  • Verified answer
    Wahaj Rashid Profile Picture
    11,321 on at

    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

  • ACECORP Profile Picture
    1,589 on at

    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

  • ACECORP Profile Picture
    1,589 on at

    Yes. The logical name is "salesorder".

    My problem is solved! Thanks so much!

  • Wahaj Rashid Profile Picture
    11,321 on at

    You are welcome :)

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
#ManoVerse Profile Picture

#ManoVerse 93

#1
Siv Sagar Profile Picture

Siv Sagar 93 Super User 2025 Season 2

#3
Martin Dráb Profile Picture

Martin Dráb 62 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans