Friday, April 13, 2012

Using Saleforce Assignment Rules from G4S or S4S

S4S and G4S can both utilize the Lead Assignment Rules from Salesforce when inserting a new record.

Essentially an AssignmentRuleHeader needs to be added to the Salesforce binding with the useDefaultRule property set to true. This is equivalent to checking "Assign using active assignment rule" at the end of the Lead creation process in the UI.

After the insertion is complete the AssignmentRuleHeader should be cleared from the binding so it doesn't affect subsequent calls from that Session.

[TestMethod]
public void CreateLeadWithActiveAssignmentRule()
{
 SalesforceSession salesforceSession = SessionTest.GetActiveSession();
 Lead lead = null;

 LeadService leadService = null;

 try
 {
  lead = new Lead();
  lead.FirstName = "John";
  lead.LastName = "Brown";
  lead.Company = "ABC Corporation";
  lead.LeadSource = "Web";

  // Setting the lead source for a pre-existing lead assignment rule. This  
  // rule was created outside of this test case and will assign any new leads 
  // to a user who is not the current session owner.

  // Create the assignment rule header and add it to the proxy binding 
  AssignmentRuleHeader arh = new AssignmentRuleHeader();
  // Use the current default rule. Equivalent to checking "Assign using active assignment rule"
  arh.useDefaultRule = true;

  // Every operation that results in a new or updated lead will use the 
  // specified rule until the header is removed from the proxy binding 
  salesforceSession.Binding.AssignmentRuleHeaderValue = arh;

  leadService = new LeadService(salesforceSession);

  SaveResult saveResult = leadService.Insert(lead);
  if (!saveResult.success)
  {
   Assert.Fail(saveResult.errors[0].message);
  }

  // The lead will now have an Id
  Assert.IsTrue(leadService.ValidEntityId(lead.Id));

  // This call effectively removes the header. The next lead will be assigned 
  // to the default lead owner. 
  salesforceSession.Binding.AssignmentRuleHeaderValue = null;

  // Check that the assignment rule has been applied and the owner is not the current user.
  leadService.Refresh(lead, Lead.Fields.OwnerId);

  Assert.AreNotEqual(salesforceSession.SalesforceUserId, lead.OwnerId, "AssignmentRule should have changed the OwnerId");
    
 }
 finally
 {
  if (leadService != null && lead != null && lead.Id != null)
  {
   try { leadService.DeleteEntity(lead); }
   catch (Exception) { }
  }
 }
}