• Robert Wambold
  • NEWBIE
  • 10 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 16
    Replies

Hello All,

I developed a simple Invocable APEX class and with my test class acheived 100% code coverage.

So...I decided to change the name and now I cannot get above 72%. The only differnce is the name of the classes. What am I doing wrong?

Thanks,

Bob

  

 

Hello All,

I am trying to write Batch APEX Class to Join Lead with User.

I have added fields to the User object to hold the ID of the who the user was replaced by (Replaced_By_ID__c).

The scenario is an AE (User) leaves the company and is replaced by a new AE (User).

In my APEX Class I want to find the Leads that were owned by the departed AE (User)  by joining to User where User.Replaced_By_ID__c <> '' and User.Accounts_Traansferred__c = FALSE.

If I find a match I want to update Lead.OwnerID with User.Replaced_By_ID__c.

Unfortunately,  User.Replaced_By_ID__c and User.Accounts_Traansferred__c are unavailble.

Compile Error: Variable does not exist: Replaced_By_ID__c at line 14 column 25

Can someone help me? Please.

Here is my dumb code.

global class LeadTransferTEST04 implements Database.Batchable<sObject>{

    global integer recordsProcessed = 1;
    string NoValue = ' ';
    
    global Database.QueryLocator start(Database.BatchableContext bc){
       return Database.getQueryLocator('SELECT ID, OwnerID, Replaced_By_ID__c from Lead where OwnerID IN (SELECT ID FROM User WHERE Accounts_Transferred__c = FALSE and Replaced_By_ID__c <> NoValue)');
    }
        
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l : scope){
      
            l.OwnerID = Replaced_By_ID__c;
        }
        update scope;        
    }
          
    global void finish(Database.BatchableContext bc){
     System.debug(recordsProcessed + ' records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
       // EmailUtils.sendMessage(a, recordsProcessed);
       // Send an email to the Apex job's submitter notifying of job completion.
       // Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       // String[] toAddresses = new String[] {CreatedBy.Email};
       // mail.setToAddresses(toAddresses);
       // mail.setSubject('Apex Lead Transfer Job ' + a.Status);
       // mail.setPlainTextBody
       // ('Apex Lead Transfer Job has been completed. There were total of ' + a.TotalJobItems 
       //       + ' batches with ' + successCounter + ' success and ' + failureCounter
       //       + ' failures.');
       // Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }     
}

 

 

Hello All,

I got my code to work in the Developer Console but how to make it a schedulable APEX Class? Basically, my code should create a CSV file from TASK table based upon ActivityDate. For the life of me I cannot fiqure out to get my Developer Console code to schedulable APEX Class.

Can anyone help?

With thanks in advnce.

Bob

Here's my code:


DateTime Extract_date = system.now();
String FormattedExtract_date=Extract_date.format('MM/dd/yyyy');
DateTime Deletable_date = system.now().addDays(-1065);
String FormattedDeletable_date=Deletable_date.format('MM/dd/yyyy');
String MyFileName='Task Extract ' + FormattedExtract_date + ' for Activity thru ' + FormattedDeletable_date + '.csv';

String csv = 'AccountId, ActivityDate, Activity_Cost__c, Associated_Campaign__c, CallDisposition, CallDurationInSeconds, CallObject, CallType, Call_Notes__c, Call_Type__c, Call_SubType__c, CreatedById, CreatedDate, Description, Disposition__c, Go_Forward_Secured__c, Id, IsArchived, IsClosed, IsDeleted, IsHighPriority, IsRecurrence, IsReminderSet, LastModifiedById, LastModifiedDate, Next_Go_Forward_Date__c, Next_Go_Forward_Goal__c, OwnerId, Planned__c, Priority, RecurrenceActivityId, RecurrenceDayOfMonth, RecurrenceDayOfWeekMask, RecurrenceEndDateOnly, RecurrenceInstance, RecurrenceInterval, RecurrenceMonthOfYear, RecurrenceRegeneratedType, RecurrenceStartDateOnly, RecurrenceTimeZoneSidKey, RecurrenceType, ReminderDateTime, SystemModstamp, Type, User_Days_Worked__c, WhatCount,    WhatId, WhoCount, WhoId, Status, Subject, TaskSubtype\n';

for ( List<Task> tasks : [ SELECT AccountId, ActivityDate, Activity_Cost__c, Associated_Campaign__c, CallDisposition, CallDurationInSeconds, CallObject, 
CallType, Call_Notes__c, Call_Type__c, Call_SubType__c, CreatedById, CreatedDate, Description, Disposition__c, Go_Forward_Secured__c, Id, IsArchived, IsClosed, IsDeleted, IsHighPriority,
IsRecurrence, IsReminderSet, LastModifiedById, LastModifiedDate, Next_Go_Forward_Date__c, Next_Go_Forward_Goal__c, OwnerId, Planned__c, Priority,
RecurrenceActivityId, RecurrenceDayOfMonth, RecurrenceDayOfWeekMask, RecurrenceEndDateOnly, RecurrenceInstance, RecurrenceInterval, RecurrenceMonthOfYear,    
RecurrenceRegeneratedType, RecurrenceStartDateOnly, RecurrenceTimeZoneSidKey, RecurrenceType, ReminderDateTime, SystemModstamp, Type,
User_Days_Worked__c, WhatCount,    WhatId, WhoCount, WhoId,
Status, Subject, TaskSubtype 
FROM Task
Where Deletable__c = TRUE] )
{
 for ( Task T : tasks )
 {
  csv +=
   T.AccountId + ',' + T.ActivityDate + ',' + T.Activity_Cost__c + ',' + T.Associated_Campaign__c + ',' + T.CallDisposition + ',' + T.CallDurationInSeconds + ',' + 
   T.CallObject + ',' + T.CallType    + ',' + T.Call_Notes__c + ',' + T.Call_Type__c + ',' + T.Call_SubType__c + ',' + T.CreatedById + ',' + T.CreatedDate + ',' +
   T.Description + ',' + T.Disposition__c + ',' + T.Go_Forward_Secured__c + ',' + T.Id + ',' + T.IsArchived + ',' + T.IsClosed + ',' + T.IsDeleted + ',' + T.IsHighPriority + ',' +
   T.IsRecurrence + ',' + T.IsReminderSet + ',' + T.LastModifiedById + ',' + T.LastModifiedDate + ',' + T.Next_Go_Forward_Date__c + ',' + T.Next_Go_Forward_Goal__c + ',' +
   T.OwnerId + ',' + T.Planned__c + ',' + T.Priority + ',' + T.RecurrenceActivityId + ',' + T.RecurrenceDayOfMonth + ',' + T.RecurrenceDayOfWeekMask + ',' +
   T.RecurrenceEndDateOnly + ',' + T.RecurrenceInstance + ',' + T.RecurrenceInterval + ',' + T.RecurrenceMonthOfYear + ',' + T.RecurrenceRegeneratedType + ',' +    
   T.RecurrenceStartDateOnly + ',' + T.RecurrenceTimeZoneSidKey + ',' + T.RecurrenceType + ',' + T.ReminderDateTime + ',' + T.SystemModstamp + ',' + T.Type + ',' +
   T.User_Days_Worked__c + ',' + T.WhatCount + ',' + T.WhatId + ',' + T.WhoCount + ',' + T.WhoId + ',' +    
   T.Status + ',' + T.Subject + ',' + 
  T.TaskSubtype.escapeCsv() + '\n';
 }
}

ContentVersion file = new ContentVersion
(
      title = MyFileName,
      versionData = Blob.valueOf( csv ),
      pathOnClient = '/Task Extract 2018-08-16.csv'
);

insert file;
System.debug( file );

 

 

 

Hello All,

I have been struggling with my APEX code to delete Shipment records then send and email. The APEX code works correctly when tested and receive the email with results, however I cannot get above 66% Code Coverage when I test. Lines in BOLD are not code covered? I am losing my mind and my boss is angry. Please Help.

With thanks in advance.

Robert

 

/*
* Description   : This is Batch to Perform delete operation on Shipment Records.
*
*                 Shipments are Deletable when Shipment is 42 days or older.
*                 Formula "TODAY() > Date__c + 42" sets Deletable__c = TRUE

* Created By    : Robert Wambold
*
* Created Date  : 08/09/2018
*
* Version       : v1.0 - Create 
*/

//Batch Class
global class Batch_ShipmentDelete implements Database.Batchable<sObject>,Database.stateful {
  
  //Variable to count Success and Error Records
    public Integer successCounter = 0;
    public Integer failureCounter = 0; 
         
    //Start Method 
    global Database.QueryLocator start(Database.BatchableContext BC) { 
    
        //Query to Fetch Records
        return Database.getQueryLocator([SELECT ID FROM Shipment__c WHERE Deletable__c = TRUE]);
   
    }
    
    //Execute Method
    global void  execute(Database.BatchableContext BC, List<Shipment__C> scope) {
      
    //Delete the Records those are in Contexts
        Database.DeleteResult[] delresults = Database.delete((scope),false);
        
        //Loop through records going to be deleted
        for(Database.DeleteResult dr : delResults){
        
            //If record is not successfully deleted
            if(!dr.isSuccess()){
            
                //List to hold Error
                Database.Error[] errs = dr.getErrors();
                
                //Loop through list of Error
                for(Database.Error err : errs) {
                    
                    //Debug to get Error Status
                    System.debug('$#$#$#$' + err.getStatusCode() + ' - ' + err.getMessage());
                    
                    //Debug to get Error Message
                    System.debug('ErrorMessage##########'+ err.getMessage());
                }
                
                //Increase counter for Failure
                 failureCounter++;
            }
            
            else {
            
                successCounter++;
            }
        }      
    }
    
    //Finish Method
    global void finish(Database.BatchableContext BC){
      
      // Query the AsyncApexJob object to retrieve the current job's information.
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Shipment Delete Job ' + a.Status);
        mail.setPlainTextBody
        ('Apex Shipment Delete Job has been completed. There were total of ' + a.TotalJobItems 
              + ' batches with ' + successCounter + ' success and ' + failureCounter
              + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
}

 

My Test Code

@IsTest
public class Batch_ShipmentDeleteTEST
{
    //Database.Error[] errs = dr.getErrors();
 static testMethod void testMethod1()
 {    
     
    Test.startTest();
    Batch_ShipmentDelete obj = new Batch_ShipmentDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
 //Database.Error[] errs = dr.getErrors();
 static testMethod void testMethod2()
 {           
    Test.startTest();
    Batch_ShipmentDelete obj = new Batch_ShipmentDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
    
}

Hello all,

My code is working, however I cannot deploy because my Code Coverage is stuck at 66%. Can someone please take a look? 

Thank you.

Robert


Batch_DeleteQuote:

/*
* Description   : This is Batch job to perform Delete operation on Quote Records.

*                 Quotes are Deletable when Quote is 42 days or older.
*                 Formula "TODAY() > Date__c + 42" sets Deletable__c = TRUE
*
* Created By    : Robert Wambold
*
* Created Date  : 08/09/2018
*
* Version       : v1.0 - Create 
*/

//Batch Class
global class Batch_QuoteDelete implements Database.Batchable<sObject>,Database.stateful {
  
  //Variable to count Success and Error Records
    public Integer successCounter = 0;
    public Integer failureCounter = 0; 
         
    //Start Method 
    global Database.QueryLocator start(Database.BatchableContext BC) { 
    
        //Query to Fetch Records
        return Database.getQueryLocator([SELECT ID FROM Quote__c WHERE Deletable__c = TRUE]);
   
    }
    
    //Execute Method
    global void  execute(Database.BatchableContext BC, List<Quote__C> scope) {
      
    //Delete the Records those are in Contexts
        Database.DeleteResult[] delresults = Database.delete((scope),false);
        
        //Loop through records going to be deleted
        for(Database.DeleteResult dr : delResults){
        
            //If record is not successfully deleted
            if(!dr.isSuccess()){
            
                //List to hold Error
                Database.Error[] errs = dr.getErrors();
                
                //Loop through list of Error
                for(Database.Error err : errs) {
                    
                    //Debug to get Error Status
                    System.debug('$#$#$#$' + err.getStatusCode() + ' - ' + err.getMessage());
                    
                    //Debug to get Error Message
                    System.debug('ErrorMessage##########'+ err.getMessage());
                }
                
                //Increase counter for Failure
                 failureCounter++;
            }
            
            else {
            
                successCounter++;
            }
        }      
    }
    
    //Finish Method
    global void finish(Database.BatchableContext BC){
      
      // Query the AsyncApexJob object to retrieve the current job's information.
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Quote Delete Job ' + a.Status);
        mail.setPlainTextBody
        ('Apex Quote Delete Job has been completed. There were total of ' + a.TotalJobItems 
              + ' batches with ' + successCounter + ' success and ' + failureCounter
              + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
}

 

Test Class:

@IsTest
public class Batch_QuoteDeleteTEST
{
 static testMethod void testMethod1()
 {           
    Test.startTest();
    Batch_QuoteDelete obj = new Batch_QuoteDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
 
 static testMethod void testMethod2()
 {           
    Test.startTest();
    Batch_QuoteDelete obj = new Batch_QuoteDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
}

 

Hello,

Taking my first shot at APEX.

I have created a Custom Field on my Quote table that determines a when a Quote can be deleted. I need my code to delete Quote records, then send an email showing how many Successes or Errors when my job completes.

Could someone be so kind as to review my code...any suggestions or comments would be appreciated.

 

Kind regrds,

Robert

global class QuoteDeleteBatchJob implements Database.Batchable<sObject> 
{
    global Database.QueryLocator start(Database.BatchableContext BC) 
    {
        String query = +
        'SELECT Id, Name, Deletable__c +
         FROM Quote__c +
         WHERE Deletable = TRUE';  
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Quote__c> scope) 
    {
        for(Quote a : scope)
        {
            a.Name = a.Name + 'Deleted by QuoteDeleteBatchJob';
        }
        Delete scope;
    }
    global void finish(Database.BatchableContext BC) 
    
     AsyncApexJob a = [SELECT Id,Status,JobType,NumberOfErrors,JobItemsProcessed,TotalJobItems,CompletedDate,ExtendedStatus
     FROM AsyncApexJob WHERE Id =:BC.getJobId()];
     
     List<User> userList = new List<User>();
     userList = [SELECT Id,Email,IsActive FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = True] ;
          
     // Send an email to all active Admins notifying of job completion.     
     for(User u : userList)
     
     {           
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               
       //String[] toAddresses = new String[] {user.Id};
       //mail.setToAddresses(toAddresses);
       mail.setTargetObjectId(u.Id);
       mail.setSubject('QuoteDeleteBatchJob - ' + a.Status);
       mail.setSaveAsActivity(false);
       mail.setPlainTextBody
       ('The batch Apex job completed on  ' + a.CompletedDate + ',\n\n' +
        'Job Status : ' + a.Status + '\n'+
        'Total Job Items deleted : ' + a.TotalJobItems + '\n'+
        'Number of Job Items Deleted : ' + a.JobItemsProcessed + '\n' +
        'Number of Failures : '+ a.NumberOfErrors);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }  
          
}

 

Hello All,

I developed a simple Invocable APEX class and with my test class acheived 100% code coverage.

So...I decided to change the name and now I cannot get above 72%. The only differnce is the name of the classes. What am I doing wrong?

Thanks,

Bob

  

 

Hello All,

I am trying to write Batch APEX Class to Join Lead with User.

I have added fields to the User object to hold the ID of the who the user was replaced by (Replaced_By_ID__c).

The scenario is an AE (User) leaves the company and is replaced by a new AE (User).

In my APEX Class I want to find the Leads that were owned by the departed AE (User)  by joining to User where User.Replaced_By_ID__c <> '' and User.Accounts_Traansferred__c = FALSE.

If I find a match I want to update Lead.OwnerID with User.Replaced_By_ID__c.

Unfortunately,  User.Replaced_By_ID__c and User.Accounts_Traansferred__c are unavailble.

Compile Error: Variable does not exist: Replaced_By_ID__c at line 14 column 25

Can someone help me? Please.

Here is my dumb code.

global class LeadTransferTEST04 implements Database.Batchable<sObject>{

    global integer recordsProcessed = 1;
    string NoValue = ' ';
    
    global Database.QueryLocator start(Database.BatchableContext bc){
       return Database.getQueryLocator('SELECT ID, OwnerID, Replaced_By_ID__c from Lead where OwnerID IN (SELECT ID FROM User WHERE Accounts_Transferred__c = FALSE and Replaced_By_ID__c <> NoValue)');
    }
        
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l : scope){
      
            l.OwnerID = Replaced_By_ID__c;
        }
        update scope;        
    }
          
    global void finish(Database.BatchableContext bc){
     System.debug(recordsProcessed + ' records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
       // EmailUtils.sendMessage(a, recordsProcessed);
       // Send an email to the Apex job's submitter notifying of job completion.
       // Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       // String[] toAddresses = new String[] {CreatedBy.Email};
       // mail.setToAddresses(toAddresses);
       // mail.setSubject('Apex Lead Transfer Job ' + a.Status);
       // mail.setPlainTextBody
       // ('Apex Lead Transfer Job has been completed. There were total of ' + a.TotalJobItems 
       //       + ' batches with ' + successCounter + ' success and ' + failureCounter
       //       + ' failures.');
       // Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }     
}

 

 

Hello All,

I have been struggling with my APEX code to delete Shipment records then send and email. The APEX code works correctly when tested and receive the email with results, however I cannot get above 66% Code Coverage when I test. Lines in BOLD are not code covered? I am losing my mind and my boss is angry. Please Help.

With thanks in advance.

Robert

 

/*
* Description   : This is Batch to Perform delete operation on Shipment Records.
*
*                 Shipments are Deletable when Shipment is 42 days or older.
*                 Formula "TODAY() > Date__c + 42" sets Deletable__c = TRUE

* Created By    : Robert Wambold
*
* Created Date  : 08/09/2018
*
* Version       : v1.0 - Create 
*/

//Batch Class
global class Batch_ShipmentDelete implements Database.Batchable<sObject>,Database.stateful {
  
  //Variable to count Success and Error Records
    public Integer successCounter = 0;
    public Integer failureCounter = 0; 
         
    //Start Method 
    global Database.QueryLocator start(Database.BatchableContext BC) { 
    
        //Query to Fetch Records
        return Database.getQueryLocator([SELECT ID FROM Shipment__c WHERE Deletable__c = TRUE]);
   
    }
    
    //Execute Method
    global void  execute(Database.BatchableContext BC, List<Shipment__C> scope) {
      
    //Delete the Records those are in Contexts
        Database.DeleteResult[] delresults = Database.delete((scope),false);
        
        //Loop through records going to be deleted
        for(Database.DeleteResult dr : delResults){
        
            //If record is not successfully deleted
            if(!dr.isSuccess()){
            
                //List to hold Error
                Database.Error[] errs = dr.getErrors();
                
                //Loop through list of Error
                for(Database.Error err : errs) {
                    
                    //Debug to get Error Status
                    System.debug('$#$#$#$' + err.getStatusCode() + ' - ' + err.getMessage());
                    
                    //Debug to get Error Message
                    System.debug('ErrorMessage##########'+ err.getMessage());
                }
                
                //Increase counter for Failure
                 failureCounter++;
            }
            
            else {
            
                successCounter++;
            }
        }      
    }
    
    //Finish Method
    global void finish(Database.BatchableContext BC){
      
      // Query the AsyncApexJob object to retrieve the current job's information.
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Shipment Delete Job ' + a.Status);
        mail.setPlainTextBody
        ('Apex Shipment Delete Job has been completed. There were total of ' + a.TotalJobItems 
              + ' batches with ' + successCounter + ' success and ' + failureCounter
              + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
}

 

My Test Code

@IsTest
public class Batch_ShipmentDeleteTEST
{
    //Database.Error[] errs = dr.getErrors();
 static testMethod void testMethod1()
 {    
     
    Test.startTest();
    Batch_ShipmentDelete obj = new Batch_ShipmentDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
 //Database.Error[] errs = dr.getErrors();
 static testMethod void testMethod2()
 {           
    Test.startTest();
    Batch_ShipmentDelete obj = new Batch_ShipmentDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
    
}

Hello,

Taking my first shot at APEX.

I have created a Custom Field on my Quote table that determines a when a Quote can be deleted. I need my code to delete Quote records, then send an email showing how many Successes or Errors when my job completes.

Could someone be so kind as to review my code...any suggestions or comments would be appreciated.

 

Kind regrds,

Robert

global class QuoteDeleteBatchJob implements Database.Batchable<sObject> 
{
    global Database.QueryLocator start(Database.BatchableContext BC) 
    {
        String query = +
        'SELECT Id, Name, Deletable__c +
         FROM Quote__c +
         WHERE Deletable = TRUE';  
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Quote__c> scope) 
    {
        for(Quote a : scope)
        {
            a.Name = a.Name + 'Deleted by QuoteDeleteBatchJob';
        }
        Delete scope;
    }
    global void finish(Database.BatchableContext BC) 
    
     AsyncApexJob a = [SELECT Id,Status,JobType,NumberOfErrors,JobItemsProcessed,TotalJobItems,CompletedDate,ExtendedStatus
     FROM AsyncApexJob WHERE Id =:BC.getJobId()];
     
     List<User> userList = new List<User>();
     userList = [SELECT Id,Email,IsActive FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = True] ;
          
     // Send an email to all active Admins notifying of job completion.     
     for(User u : userList)
     
     {           
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               
       //String[] toAddresses = new String[] {user.Id};
       //mail.setToAddresses(toAddresses);
       mail.setTargetObjectId(u.Id);
       mail.setSubject('QuoteDeleteBatchJob - ' + a.Status);
       mail.setSaveAsActivity(false);
       mail.setPlainTextBody
       ('The batch Apex job completed on  ' + a.CompletedDate + ',\n\n' +
        'Job Status : ' + a.Status + '\n'+
        'Total Job Items deleted : ' + a.TotalJobItems + '\n'+
        'Number of Job Items Deleted : ' + a.JobItemsProcessed + '\n' +
        'Number of Failures : '+ a.NumberOfErrors);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }  
          
}

 

I have two custom objects [access.log & trans.log] who receive daily updates [New Records] from an external system. After 31 days we don't need them anymore and we would like to delete them. Both objects have a date field on the record 'Log_date__c'.

I know that you can make a job that deletes these records on a daily basis.

My question;

- How do I write a code that deletes the right records? (Log_date__c older than 31 days)
- How/where do I put in SFDC? (Apex Class or Trigger! - Both!)

Are there any who can help me progress. In which case it will be my first code in SFDC.