• Robert Berkeley
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 3
    Replies
Hello
I have pulled together a Batchable APEX class below that generates missing Contacts from a list of Accounts:
global class GenerateContacts implements 
    Database.Batchable<sObject>, Database.Stateful{

   global final String Query;
   global integer count;
  
   global GenerateContacts(String q){Query=q;
     count = 0;
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
   
    global void execute(Database.BatchableContext BC,List<sObject> scope){
        Integer sp;
        String ln;
        String fn;
        for(sObject s : scope){
            Account a = (Account)s;
            if(a.Contacts.isEmpty()){
                System.debug('email: ' + a.Email_2__c);
                System.debug('name: ' + a.Name);
                sp = a.Name.LastIndexOf(' ');
                if (sp > 0) {
                    ln = a.Name.substring(sp);
                    fn = a.Name.substring(0, sp);
                }
                sObject ct = new Contact(AccountId = a.Id, Email = a.Email_2__c, FirstName = fn, LastName = ln);
                insert ct;
            }
            else
                count=count+1;
        }
    }

    global void finish(Database.BatchableContext BC){
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob WHERE Id = :BC.getJobId()];
    
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'me@mydomain.net'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Contacts Generation ' + a.Status);
        mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures. Count was: '+count);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

My problem is with generating a Test class with greater than 75% coverage.  Here is my Test class:
@isTest
private class Test_Generate_Contacts {
 
    static testMethod void test_GenerateContacts() {
        String Query = 'Select a.Id, Email_2__c, First_Name__c, Last_Name__c, Name, (Select Id From Contacts limit 1) from Account a LIMIT 1';

        test.startTest();
        GenerateContacts gen=new GenerateContacts(Query); 
        String jobid = Database.executeBatch(gen);
        test.stopTest();
    }
}

This one only gives me 64%.  How can I get it higher?
Hi, I'm trying to send an email when a client's Account is 'opened'.  I have a button on the Account page with a Javascript call beneath it:
sforce.apex.execute("AccountOpenEmail","SendEmail", {id:"{!Account.Id}"});

In the APEX class being called above I then try to load a Visual Force email template to merge fields from the Account object into its HTML for the email.
global class AccountOpenEmail
{
    WebService static void SendEmail(string id) {
      Account acc = Database.query('SELECT Account.Name, (SELECT Contact.Id FROM Account.Contacts) FROM Account WHERE id = ' + id);

      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();   
      
      email.setTargetObjectId(acc.Contacts[0].Id);
      email.setTemplateId('00X11000000DkqK');
      email.setBccSender(true);
    
      Messaging.SendEmailResult [] r = Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});      
      for ( Messaging.sendEmailResult result : r ) {
           if ( !r[0].isSuccess () ) {
               System.debug ( result  );
           } else{
               ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Email Sent Successfully' );
               ApexPages.addMessage(msg);
           }
      }
    }
}

The system was telling me that I could not use an Account.Id for the setTargetObjectId call, so I got the idea to try to get the Contact.Id from the Account record.  Am I on the right tracks?

I now get the error:
{faultcode:'soapenv:Client', faultstring:'System.QueryException: unexpected token: 'IfLgJ'

Class.AccountOpenEmail.SendEmail: line 4, column 1', }


Hello
I have pulled together a Batchable APEX class below that generates missing Contacts from a list of Accounts:
global class GenerateContacts implements 
    Database.Batchable<sObject>, Database.Stateful{

   global final String Query;
   global integer count;
  
   global GenerateContacts(String q){Query=q;
     count = 0;
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
   
    global void execute(Database.BatchableContext BC,List<sObject> scope){
        Integer sp;
        String ln;
        String fn;
        for(sObject s : scope){
            Account a = (Account)s;
            if(a.Contacts.isEmpty()){
                System.debug('email: ' + a.Email_2__c);
                System.debug('name: ' + a.Name);
                sp = a.Name.LastIndexOf(' ');
                if (sp > 0) {
                    ln = a.Name.substring(sp);
                    fn = a.Name.substring(0, sp);
                }
                sObject ct = new Contact(AccountId = a.Id, Email = a.Email_2__c, FirstName = fn, LastName = ln);
                insert ct;
            }
            else
                count=count+1;
        }
    }

    global void finish(Database.BatchableContext BC){
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob WHERE Id = :BC.getJobId()];
    
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'me@mydomain.net'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Contacts Generation ' + a.Status);
        mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures. Count was: '+count);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

My problem is with generating a Test class with greater than 75% coverage.  Here is my Test class:
@isTest
private class Test_Generate_Contacts {
 
    static testMethod void test_GenerateContacts() {
        String Query = 'Select a.Id, Email_2__c, First_Name__c, Last_Name__c, Name, (Select Id From Contacts limit 1) from Account a LIMIT 1';

        test.startTest();
        GenerateContacts gen=new GenerateContacts(Query); 
        String jobid = Database.executeBatch(gen);
        test.stopTest();
    }
}

This one only gives me 64%.  How can I get it higher?
Hi, I'm trying to send an email when a client's Account is 'opened'.  I have a button on the Account page with a Javascript call beneath it:
sforce.apex.execute("AccountOpenEmail","SendEmail", {id:"{!Account.Id}"});

In the APEX class being called above I then try to load a Visual Force email template to merge fields from the Account object into its HTML for the email.
global class AccountOpenEmail
{
    WebService static void SendEmail(string id) {
      Account acc = Database.query('SELECT Account.Name, (SELECT Contact.Id FROM Account.Contacts) FROM Account WHERE id = ' + id);

      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();   
      
      email.setTargetObjectId(acc.Contacts[0].Id);
      email.setTemplateId('00X11000000DkqK');
      email.setBccSender(true);
    
      Messaging.SendEmailResult [] r = Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});      
      for ( Messaging.sendEmailResult result : r ) {
           if ( !r[0].isSuccess () ) {
               System.debug ( result  );
           } else{
               ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Email Sent Successfully' );
               ApexPages.addMessage(msg);
           }
      }
    }
}

The system was telling me that I could not use an Account.Id for the setTargetObjectId call, so I got the idea to try to get the Contact.Id from the Account record.  Am I on the right tracks?

I now get the error:
{faultcode:'soapenv:Client', faultstring:'System.QueryException: unexpected token: 'IfLgJ'

Class.AccountOpenEmail.SendEmail: line 4, column 1', }