Qualify a Lead in C#

Usually we'd turn to SetStateRequest, but qualifying a lead isn't quite that straightforward in C#.

Apr 24th 2017ยท2 min read
dog lead

Typically, when we want to deactivate a record in a plugin or a workflow, we turn to SetStateRequest. Qualifying a Lead isn't quite as straightforward. If you've qualified a Lead through the CRM interface, you'll know that:

  • An Opportunity is created from the originating Lead.
  • You can select whether to create a Contact or Account from the originating Lead.
QualifyLeadRequest in the Microsoft.Crm.Sdk.Messages namespace provides us with a class which allows us to specify all of these options and more programatically.

The code snippet below creates a new QualifyLeadRequest, populating all of it's required properties.

var qualifyLeadRequest = new QualifyLeadRequest
    // The Lead record to qualify and its status once qualified.
    LeadId = new EntityReference(),
    Status = new OptionSetValue(2),

    // Specify whether or not to create an Account, Contact and/or Opportunity.
    CreateAccount = true,
    CreateContact = true,
    CreateOpportunity = true,

    // The currency to use for the Opportunity.
    OpportunityCurrencyId = new EntityReference(),

    // The Account or Contact that will be associated with the Opportunity.
    OpportunityCustomerId = new EntityReference(),

    // The source Campaign that will be associated with the Opportunity/
    SourceCampaignId = new EntityReference()

Replace all of my empty new EntityReference() objects with valid EntityReferences (which are instantiated by passing an entity name and an ID). Refer to the Microsoft documentation for information on other optional parameters which you can use.

The request is executed and its response stored in the qualifyLeadResponse:

var qualifyLeadResponse = (QualifyLeadResponse)service.Execute(qualifyLeadRequest);

The most interesting property of the response object is CreatedEntities. See the Microsoft documentation for information on other properties stored in the QualifyLeadResponse.

CreatedEntities contains a collection of EntityReferences, one for each entity created when qualifying the Lead. To get the Contact that was created, for example, iterate through the collection and query the LogicalName of each EntityReference:

foreach (var entity in qualifyLeadResponse.CreatedEntities)
    if (entity.LogicalName == "contact")
        // TODO.
Dave Clark IO