Search code examples
c#dynamics-crmdynamics-crm-2011

How to set the Opportunity Status - Dynamics CRM?


I'm trying to update the status of open opportunity by using the WinOpportunityRequest & LoseOpportunityRequest API provided in the MSDN. I've followed the code which was given in the MSDN & I even referred to stackoverflow's Set Opportunity Status

But, When I run this following code for the open opportunity it throws error stating that

LoseOpportunityRequest req = new LoseOpportunityRequest();
Entity opportunityClose = new Entity("opportunityclose");
opportunityClose.Attributes.Add("opportunityid", new EntityReference(OptyEntityName, new Guid("xxxx-xxx")));
opportunityClose.Attributes.Add("subject", "Lost the Opportunity!");
req.OpportunityClose = opportunityClose;
// 4 = Cancelled and 5 = Out-Sold
req.Status = new OptionSetValue(4);
LoseOpportunityResponse resp = (LoseOpportunityResponse)_serviceProxy.Execute(req);

Error -

4 is not a valid status code on opportunity with Id(Guid)

When I tried to change the status of the closed opportunity it says that opportunity is already closed.

One more thing to consider is this status in my CRM has a padlock icon that means it is locked.

So is it possible to change the status or not and is it based on the role?


Solution

  • For an open opportunity, we can change the status to either win or lose. So we will use the WinOpportunityRequest and LoseOpportunityRequest in here.

    So, we need to change the value to -1 so that CRM can load the default status code.

    req.Status = new OptionSetValue(4);
    

    after changing to -1 it doesn't throw any exception.

    req.Status = new OptionSetValue(-1);
    

    once the execute call is performed. The opportunity value will be changed to lost. The opportunity will be closed.

    To re-open the closed opportunity, we can use the SetStateRequest class. The code would be as follows.

                    var stateRef = new EntityReference("optyname", new Guid("optyid"));
                    SetStateRequest req = new SetStateRequest();
                    req.State = new OptionSetValue(0);
                    req.Status = new OptionSetValue(2);
                    req.EntityMoniker = stateRef;
                    SetStateResponse stateSet = (SetStateResponse)_serviceProxy.Execute(req);
    

    After the execute call is performed the opportunity status is set back to open and the status is displayed as open.

    state code is different from status. state code can have open, win or close. status can have multiple values. detailed info is provide at msdn.