Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Answered

How to cancel a SalesOrder using WEB API action CancelSalesOrder?

Posted on by 30

How to cancel a SalesOrder using WEB API action CancelSalesOrder

My Code is :

var parameters = {};
var orderclose = {};
orderclose["salesorderid"] = "84fb9b1f-7e5e-ea11-a811-000d3aa087c4"; //Delete if creating new record 
orderclose["@odata.type"] = "Microsoft.Dynamics.CRM.salesorder";
parameters.OrderClose = orderclose;
parameters.Status = 3;

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/CancelSalesOrder", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            //Success - No Return Data - Do Something
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(parameters));

but it return with

{
	"error": {
		"code": "0x80040216",
		"message": "An unexpected error occurred.",
		"innererror": {
			"message": "An unexpected error occurred.",
			"type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
			"stacktrace": "   at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext, Dictionary`2 optionalParameters)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Execute(OrganizationRequest request, ExecutionContext executionContext)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.ExecuteOperation(CrmODataExecutionContext context, EdmOperation edmOperation, Dictionary`2 parameters, Dictionary`2 boundParameters)\r\n   at Microsoft.Crm.Extensibility.OData.ActionController.ProcessOperationRequest(String operationName, Dictionary`2 operationParameters, EntityReference entityReference, String boundEntityName, String boundEntityType)\r\n   at Microsoft.Crm.Extensibility.OData.ActionController.<>c__DisplayClass9_0.b__0()\r\n   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
		}
	}
}

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: How to cancel a SalesOrder using WEB API action CancelSalesOrder?

    Query which is being executed is missing the key attributes or having the wrong attributes value as mentioned below.

    • odata.bind is also required for salesorderid property.

    • odata.type should equals to Microsoft.Dynamics.CRM.orderclose.

    • Status reason should equal to 4.

    Once these changes will be done, query will be executed successfully without any error and will cancel the sales order.

    Example:

    var orderclose = {};

    orderclose["salesorderid"] = "84fb9b1f-7e5e-ea11-a811-000d3aa087c4"; //Delete if creating new record

    orderclose["@odata.type"] = "Microsoft.Dynamics.CRM.salesorder";

    parameters.OrderClose = orderclose;

    parameters.Status = 3;

  • Suggested answer
    H V Profile Picture
    H V 347 on at
    RE: How to cancel a SalesOrder using WEB API action CancelSalesOrder?

    Hi,

    Please use below code to cancel sales order:

        var objSalesorder = {};
    	    objSalesorder.statecode = 2;
    	    objSalesorder.statuscode = 4;
    	    var stringJSONSalesOrder = JSON.stringify(objSalesorder);
    	    
    	    var query = Xrm.Utility.getGlobalContext().getClientUrl()   "/api/data/v9.0/salesorders(4a6e9193-337e-ea11-a811-000d3a300e5b)";
        
                var req = new XMLHttpRequest();
                req.open("PATCH", encodeURI(query), true);
                req.setRequestHeader("OData-MaxVersion", "4.0");
                req.setRequestHeader("OData-Version", "4.0");
                req.setRequestHeader("Accept", "application/json");
                req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                req.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        req.onreadystatechange = null;
                        if (this.status === 204 || this.status === 200) {
                            alert("success");
                        } else {
                            alert("Error");
                        }
                    }
                };
                req.send(stringJSONSalesOrder);

  • Verified answer
    cloflyMao Profile Picture
    cloflyMao 25,198 on at
    RE: How to cancel a SalesOrder using WEB API action CancelSalesOrder?

    Hi Flex Xuan,

    1. odata.bind is also required for salesorderid property.

    2. odata.type should equals to Microsoft.Dynamics.CRM.orderclose.

    3. Status reason should equals to 4.

    Try excute code below, I got success from it:

    var parameters = {};
    var orderclose = {};
    orderclose["salesorderid@odata.bind"] = "/salesorders(xxxx)"; //Delete if creating new record 
    orderclose["@odata.type"] = "Microsoft.Dynamics.CRM.orderclose";
    parameters.OrderClose = orderclose;
    parameters.Status = 4;
    
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/CancelSalesOrder", true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function() {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 204) { alert("Ok!!");
                //Success - No Return Data - Do Something
            } else {
                Xrm.Utility.alertDialog(this.response);
            }
        }
    };
    req.send(JSON.stringify(parameters));

    A previous thread which has same issue as yours.

    https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/227813/error-500-when-calling-cancelsalesorder-action-using-webapi-javascript?pifragment-97030=1

    Regards,

    Clofly

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!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans