Win or Lose opportunity from code

Today, I needed to close an opportunity from a plug-in without having an early bound context. The following code sample shows a function to generate an OpportunityClose Entity:

[csharp]

public static Entity CreateOpportunityClose(Guid opportunityId, string subject)
{
var opportunityClose = new Entity("opportunityclose");
opportunityClose.Attributes.Add("opportunityid", new EntityReference("opportunity", opportunityId));
opportunityClose.Attributes.Add("subject", subject);
return opportunityClose;
}

[/csharp]

Using this function, we can generate either a WinOpportunityRequest or a LoseOpportunityRequest.

Won:

[csharp]
var opportunityWinRequest = new WinOpportunityRequest
{
OpportunityClose = CreateOpportunityClose(opportunity.Id, "Reason for this win"),
    Status = new OptionSetValue(3)  // Status won
};
[/csharp]

Lost:

[csharp]
var opportunityLoseRequest = new LoseOpportunityRequest
{
    OpportunityClose = CreateOpportunityClose(opportunity.Id, "Reason for this loss."),
    Status = new OptionSetValue(4)  // cancelled (or your own status)
};
[/csharp]

Finally, you will have to execute the request using the IOrganizationService.Execute Method.

Leave a Reply