Thursday, August 11, 2011

CRM 2011: Using the LoseOpportunityRequest request

private void LoseAllOpportunitiesForCustomerId(Guid customerId, IOrganizationService _service)
{
    // Instantiate an organization context so that we can use LINQ queries
    var orgContext = new YourOrganizationContext(_service);

    // Build query to retrieve the related opportunities (w/Active statecode)
    var opportunityIds = from o in orgContext.OpportunitySet
                         where o.CustomerId.Id == customerId && o.StateCode.Value == OpportunityState.Open
                         select o.OpportunityId.Value;

    foreach (var opportunityId in opportunityIds)
    {
        System.Diagnostics.Debug.WriteLine("Inactivating Opportunity Id: {0}.", opportunityId);

        OpportunityClose oppClose = new OpportunityClose();

        // Set the opportunityclose activity subject.
        oppClose.Subject = "Inactive customer.";

        // Create an entity reference to the opportunity being lost.
        oppClose.OpportunityId = new EntityReference(Opportunity.EntityLogicalName, opportunityId);

        // Create the LostOpportunityRequest request.
        LoseOpportunityRequest loseOppReq = new LoseOpportunityRequest();
        loseOppReq.OpportunityClose = oppClose;

        loseOppReq.Status = new OptionSetValue(-1);

        // Execute the request.
        _service.Execute(loseOppReq);
    }
}

0 comments: