Thursday, May 28, 2009

How to Convert lead to contact, account and/or opportunity programmatically

Sometime we need to convert a lead to a contact, account and/or opportunity programmatically. to achieve this we have to follow the below mentioned process:

it is a two step process. in the first step we need to disable the lead. This can be done by using the SetStateLeadRequest. In the second step we need to use the InitializeFromRequest and InitializeFromResponse classes. It's the InitializeFromRequest class in which we will need to set the EntityMoniker attribute to the lead which you just disabled in the first step. On the same request we'll need to set the target entityname to the name of the entity we wish to convert the lead into (contact, account or opportunity) and then we'll need to set the TargetFieldType. This would most likely be TargetFieldType.All. Now execute that request and here we go .

code example: in this example we will create a function to convert a lead into account programmatically


// <summary>
// Convert Lead To Account
// </summary>
// <param name="service">CrmService</param>
// <param name="leadID">Guid of the Lead that needs to be converted</param>
// <returns>Guid of ctreated account</returns>
public Guid convertLeadToAccount(CrmService service, Guid leadID)
{
//step one : qualify the lead
SetStateLeadRequest qualifier = new SetStateLeadRequest();
qualifier.EntityId = leadID;
qualifier.LeadState = LeadState.Qualified;
qualifier.LeadStatus = -1;
service.Execute(qualifier);
//Note: lead is qualified, but not converted to account yet

InitializeFromRequest req = new InitializeFromRequest();
// this is the very thing that does the job.
req.EntityMoniker = new Moniker();
req.EntityMoniker.Id = leadID;
req.EntityMoniker.Name = "lead";
req.TargetEntityName = EntityName.account.ToString();
req.TargetFieldType = TargetFieldType.All;
InitializeFromResponse rps = (InitializeFromResponse)service.Execute(req);
Guid AccountID = service.Create(rps.Entity);
return AccountID;
}

No comments: