• RajSharan
  • NEWBIE
  • 0 Points
  • Member since 2009

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 4
    Replies

Ref: http://community.salesforce.com/sforce/board/message?board.id=Visualforce&view=by_date_ascending&message.id=15324

 

I'm facing the same problem. I've created an "Email to Lead" class. Due to Campaign constraints, I've had to hardcode that information.

 

My test class is not going past  33%.

 

/**
******************************************************************************
Name : EmailToLeadOrContactTask
Objective : Create Lead or Contact Activity
Input Parameter :
Output Parameter:
Calls :
Called from :
Contact : rsharan@navinet.net
Modification History :-
Created/Modified by Created/Modified Date Purpose
-----------------------------------------------------------------------------
1. Raj Sharan 2/24/2010 - Create class
-----------------------------------------------------------------------------
******************************************************************************
*/

/**
* Email services are automated processes that use Apex classes
* to process the contents, headers, and attachments of inbound
* email.
*/
global class EmailToLeadOrContactTask implements Messaging.InboundEmailHandler {

global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env) {

// Create an inboundEmailResult object for returning the result of the Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

// Default is Info

String strOwnerID = 'OwnerInfo'; //MASKED
String strCampaignID = 'CampaignInfo'; //MASKED

// Set CampaignID, UserID, etc. based on the To address

if(env.toAddress.compareTo('abc@123.in.salesforce.com') == 0) {
//System.debug('Compare: ' + env.toAddress.compareTo('abc@123.in.salesforce.com')); //MASKED
strOwnerID = 'Owner2'; //MASKED
strCampaignID = 'Campaign2'; //MASKED
}

// Try to lookup any contacts based on the email from address
Contact[] ContactList = [Select Id, Name, Email
From Contact
Where Email = :email.fromAddress
Limit 1];
if (ContactList.Size() > 0) {
for (Contact contact : ContactList){

// Add Contact to Campaign
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID,
ContactId = contact.Id);
// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// New Task object to be created
Task newTask = new Task(Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now() + 1,
WhoId = contact.Id,
OwnerId = strOwnerID);

// Insert the new Task
try {
insert newTask;
//System.debug('New Task Object: ' + newTask.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}
else {
// If no matching contact found, find if the lead already exists
Lead[] LeadList = [Select Id, Email, ConvertedContactId
From Lead
Where Email = :email.fromAddress
Limit 1];
if (LeadList.Size() > 0) {
for (Lead lead : LeadList){
// Add Lead to Campaign after checking if the Lead was already converted to a Contact
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID);
if(lead.ConvertedContactId != null) {
newCampaignMember.ContactId = lead.ConvertedContactId;
}
else {
newCampaignMember.LeadId = lead.Id;
}

// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// New Task object to be created - on Lead or on converted Contact
String recordID = null;
if(lead.ConvertedContactId != null) {
recordID = lead.ConvertedContactId;
}
else {
recordID = lead.Id;
}

Task newTask = new Task(Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now() + 1,
WhoId = recordID,
OwnerId = strOwnerID);


// Insert the new Task
try {
insert newTask;
//System.debug('New Task Object: ' + newTask.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}
else {
// Retrieves the sender's first and last names
String fName = email.fromname.substring(0,email.fromname.indexOf(' '));
//System.debug('First Name: ' + fName);
String lName = email.fromname.substring(email.fromname.indexOf(' '));
//System.debug('Last Name: ' + lName);

// Parse company name
String strCompany = email.fromAddress.substring(email.fromAddress.indexOf('@') + 1, email.fromAddress.indexOf('.', email.fromAddress.indexOf('@')));
//System.debug('Company Name: ' + strCompany);

Lead newLead = new Lead(Description = 'Subject: ' + email.subject + '\n\nBody:\n' + email.plainTextBody,
FirstName = fName,
LastName = lName,
Company = strCompany,
Email = email.fromAddress,
LeadSource = 'Inbound Email',
OwnerId = strOwnerID);

// Insert the new lead
try {
insert newLead;
//System.debug('New Lead Object: ' + newLead.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// Add Lead to Campaign
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID,
LeadId = newLead.Id);

// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}

// Set the result to true. No need to send an email back to the user
// with an error message

result.success = true;

// Return the result for the Apex Email Service
return result;
}
}

 

 

Test Class

 

static testMethod void emailToContactTaskTestMethod() {
Account aData = new Account(Name = 'Test1',
OfficeNID__c = '1316585');
insert aData;
System.assert(aData.Name == 'Test1');

Contact newContact = new Contact(LastName = 'TestContact',
AccountID = aData.Id,
Office_NID__c = aData.OfficeNID__c,
email = 'TestContact' + '@gmail.com');
insert newContact;
System.assert(newContact.Office_NID__c == '1316585');

// Create a new email, envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'TestForContact';
email.plainTextBody = 'Test';
env.fromAddress = 'TestContact@gmail.com';
env.toAddress = 'abc@123.in.salesforce.com';

EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask();
Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env);
System.assertEquals(result.success, true);
}

static testMethod void emailToLeadTestMethod() {

Lead newLead = new Lead(LastName = 'TestLead',
Company = 'TestCompany',
email = 'TestLead' + '@gmail.com');
insert newLead;
System.assert(newLead.Company == 'TestCompany');

Campaign aCampaign = new Campaign(Name = 'A Campaign');
insert aCampaign;
System.assert(aCampaign.Name == 'A Campaign');

// Create a new email, envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'TestForLead';
email.plainTextBody = 'Test';
env.fromAddress = 'TestLead@gmail.com';
env.toAddress = 'abc@123.in.salesforce.com';

EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask();
Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env);
System.assertEquals(result.success, true);
}

static testMethod void emailToNewLeadTestMethod() {
// Create a new email, envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'TestForNewLead';
email.plainTextBody = 'Test';
env.fromAddress = 'NewTestLead@gmail.com';
env.toAddress = 'abc@123.in.salesforce.com';

EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask();
Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env);
System.assertEquals(result.success, true);
}

 

I am new to Email Services and Apex and wanting to learn effective methods for testing classes that implement the Messaging.InboundEmailHandler.  Please refer me to any good material for learning test methods and best practices for conducting them.  Please see the class code (ProcessApplicant) and Initial Test method Apex Class.  I'm only getting 16% code coverage using the current test method.

 

Thanks,

SCR

/* * This class implements Message.InboundEmailHandler to accept inbound applications for a given position. * It results in a new Candidate (if one doesnt already exist) and Job Description record being created. * Any binary email attachments are automatically transfered to the Job Description as attachments on the Notes and Attachments related list. */ global class ProcessApplicant implements Messaging.InboundEmailHandler { private static final String PHONE_MATCH = 'Phone:'; global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope) { // Indicates if the message processes successfully, permits an error response to be sent back to the user. Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); try { // Obtain the applicants name and the position they are applying for from the email. String firstName = email.fromname.substring(0,email.fromName.indexOf(' ')); String lastName = email.fromname.substring(email.fromName.indexOf(' ')); String positionName = email.subject; String emailBody = email.plainTextBody; String emailFrom = envelope.fromAddress; // Process the email information. processApplicantEmail(firstName, lastName, positionName, emailBody, emailFrom, email.binaryAttachments); // Success. result.success = true; } catch (Exception e) { // Return an email message to the user. result.success = false; result.message = 'An error occured processing your message. ' + e.getMessage(); } return result; } public static void processApplicantEmail(String firstName, String lastName, String positionName, String emailBody, String emailFrom, Messaging.InboundEmail.BinaryAttachment[] binaryAttachments) { // Obtain the applicants Phone number from the message body. integer phoneMatchIdx = emailBody.indexOf(PHONE_MATCH); if(phoneMatchIdx==-1) throw new ProcessApplicantException('Please state your phone number following Phone: in your message.'); String phoneNumber = emailBody.substring(phoneMatchIdx+PHONE_MATCH.length()); // Resolve the Id of the Position they are applying for. Id positionId; try { // Lookup the Position they are applying for by name. Position__c position = [select Id from Position__c where name = :positionName limit 1]; positionId = position.Id; } catch (Exception e) { // Record not found. throw new ProcessApplicantException('Sorry the position ' + positionName + ' does not currently exist.'); } // Candidate record for the applicant sending this email. Candidate__c candidate; try { // Attempt to read an existing Candidate by email address. Candidate__c[] candidates = [select Id from Candidate__c where email__c = :emailFrom]; candidate = candidates[0]; } catch (Exception e) { // Record not found, create a new Candidate record for this applicant. candidate = new Candidate__c(); candidate.email__c = emailFrom; candidate.first_name__c = firstName; candidate.last_name__c = lastName; candidate.phone__c = phoneNumber; insert candidate; } // Create the Job Application record. Job_Application__c jobApplication = new Job_Application__c(); jobApplication.Position__c = positionId; jobApplication.Candidate__c = candidate.id; insert jobApplication; // Store any email attachments and associate them with the Job Application record. if (binaryAttachments!=null && binaryAttachments.size() > 0) { for (integer i = 0 ; i < binaryAttachments.size() ; i++) { Attachment attachment = new Attachment(); attachment.ParentId = jobApplication.Id; attachment.Name = binaryAttachments[i].Filename; attachment.Body = binaryAttachments[i].Body; insert attachment; } } // Confirm receipt of the applicants email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setToAddresses( new String[] { emailFrom }); mail.setSubject('Your job application has been received'); mail.setPlainTextBody('Thank you for submitting your resume. Your application will be reviewed to determine if an interview will be scheduled.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } /* * Represents errors that have occured interpretting the incoming email message */ class ProcessApplicantException extends Exception { } }

 

 

//The ProcessApplicant Test: public class ProcessApplicantTest { public static testMethod void ProcessApplicantTest(){ System.debug('Im starting a method'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); email.subject = 'test'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye'; envelope.fromAddress = 'user@acme.com'; // setup controller object ProcessApplicant catcher = new ProcessApplicant(); catcher.handleInboundEmail(email, envelope); } }

 

  • July 21, 2009
  • Like
  • 0

I'm doing my first major Apex scripting job to automatically create events based on a quantity # specified in Opportunity Products.  I'm not the best coder around, so please bear with me here :)

 

I'm trying to query PricebookEntry.Product2.Name but am finding that the output via Apex is the name of the field instead of the actual name specified for the related object.  This also happens with ProductCode as well.

 

For example:

 

PricebookEntry.Product.Name                             .....results in "Name"

Trigger.new[0].PricebookEntry.Product2.Name    .....results in "null"

 

I've been able to narrow down a SOQL query with other fields in the table, so I know it is possible.  Here's an example:

 

[select Id,OpportunityId,Quantity,PricebookEntry.Product2.Family from OpportunityLineItem where PricebookEntry.Product2.Family = 'Services' AND Opportunity.Id = :eachNewOpportunityLineItem.OpportunityId]

 

 

What am I missing?  Someone fill in the obvious for me :)

Hello,

 

Sorry if this has been covered, but I didn't find an answer for this via the search.

 

Is there a way to reset the data in a developer account back to what it was when the account was created?  After signing up with a developer account, there is some dummy data to use, but after a while it'd be nice to clean the slate and have things as they were initially.

 

Is there an option besides exporting the initial data and then re-importing it when I need it?

 

Thanks