Tag: Single Method

  • Learn About All the Different Interfaces in Salesforce Apex Class

    Learn About All the Different Interfaces in Salesforce Apex Class

    Need for @future Methods  

    @future need resources for a longer time to make an API callout, an external web service to perform bulk data operation (batch apex) 

    Governer limits to avoid mixed DML operation.

    execute:class name.method name  

    database.batchable== interface 

    start,execute,finish 

    database.batchableContext== 

    grtJobId,getChildJobId() 

    dont miss out iconDon’t forget to check out: Salesforce Apex Tutorial for beginners | Apex Salesforce Tutorial

    SETUP OBJECTS: ex-userRole, if changes are made on u, u r going to affect the permissions on the database

    NON-SETUP OBJECTS: ex-account, no impact on permissions within a single method, you cannot create setup and non-setup objects in a single transaction for knowing status  

    list<asyncapexjob> jobs=[select id,status,Jobtype from AsyncApexJob]; 

    50 future method queue can be called within a queue but a future cannot be called within a future.sequence with asynchronous process chaing of job available in the queue. 

    Support sObjects gives record id, the id of the job  

    Database.stateful interface 

    In Batch apex Changes made by one execute do not transfer to the other execute, so we need to implement “Database.Stateful” if the batch process needs information that is shared across transactions. 

    In other words, If you want to transfer the state of the data from one batch to another batch we need to implement “Database.Stateful” interface. 

    If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions. Maintaining state is useful for counting or summarizing records as they’re processed. For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed. 

    If you don’t specify Database.Stateful, all static and instance member variables are set back to their original values. 

    To use Batch Apex, we must implement Database.Batchable interface, below are the methods which we use: 

    1. Start 
    2. Execute 
    3. Finish 

    dont miss out iconCheck out anther amazing blog by Navdita here: Multi-Factor Authentication in Salesforce – A Short Guide

    Start:

    This method is called at the beginning of the batch apex job. This method will return either an object or type Database.QueryLocator or an iterable that contains the records or objects passed to the job. This method will collect records on which the operation will be performed.  

    These records are divided into batches and passed to execute method. 

    Execute:

    This method contains the set of instructions which we want to perform on those records which we retrieved from the Start method.        

    Finish:

    This method gets executed after all the batches are processed. We use this method to send emails to inform them about the job completion. 

    Below is an example: 

    global class AccountBatchUpdate implements Database.Batchable<sObject> 
    { 
        global Database.QueryLocator start(Database.BatchableContext BC) 
        { 
            String query = ‘SELECT Id,Name FROM Account’; 
            return Database.getQueryLocator(query); 
        } 
       global void execute(Database.BatchableContext BC, List<Account> scope) 
        { 
           for(Account a : scope) 
           { 
               a.Name = a.Name + ‘******’; 
           } 
           update scope; 
       }  
       global void finish(Database.BatchableContext BC) { } 
    }
  • How Does a Post Install Script Work? – Salesforce Developer Guide

    How Does a Post Install Script Work? – Salesforce Developer Guide

    Post-Install Script is the same as other apex classes. And the apex class which is executed when a managed package is installed or upgraded. This class executes the InstallHandler interface. 

    global interface InstallHandler {
      void onInstall(InstallContext context)
    }
    

    This interface contains a single method named onInstall which determines what is to be performed on installation. And the onInstall method takes a context object as an argument, which gives you these informations:

    • Organization Id of the org in which the package installation occurs.
    • User Id of the user who started the installation.
    • Version Number
    •  Installation is an update or not.
    •  Installation is pushed or not.
    global interface InstallContext { 
      ID organizationId();
      ID installerId();
      Boolean isUpgrade();
      Boolean isPush(); 
      Version previousVersion();
    }
    

    dont miss out iconDon’t forget to check out: DML Statements vs Database Methods in Salesforce

    System.version: The method of this class is used to fetch the version of a managed package and comparison version of the package. Let’s discuss the package version, It is a no. that recognizes the set of segments/components transferred in a managed package.

    Format of the version number: majorNumber.minorNumber.patchNumber Example: (1.2.0). When non-patch releases major and minor numbers will increase to a selected value. And patch number of zero is used to increase the major and minor numbers.

    Let’s compare the recent version with the specified version. This will return the following information:

    • Zero, If both versions are equivalent.
    • Returns greater than zero, if the specified version is smaller than the current package version.
    • It returns less than zero if the specified version is greater than the current package version.

    If you want to compare the two-section version with the three-section version then patch number is ignored and this comparison only depends on the major and minor numbers.

    Example of Post Install Script:

    Let’s take an example of Post Install Script for a better understanding of this.

    global class PostInstallScriptExample implements Messaging.inboundEmailHandler{
        global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                               Messaging.InboundEnvelope envelope ) 
        {
            Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
            List<Contact> conList  =  new List <contact>();
            List<Lead> leadList = new List <lead>();
            String mySubject = email.subject.toLowerCase();
            String s = 'PostInstallScriptExample';
            Boolean bool;
            bool = mySubject.contains(s);
            if(bool == true){
                try{
                    for(Contact con : [select Id, Name, Email, HasOptedOutOfEmail
                                       From Contact
                                       where Email = :envelope.fromAddress
                                       AND hasOptedOutOfEmail = false
                                       LIMIT 100]) {
                                           con.hasOptedOutOfEmail = true;
                                           conList.add(con);
                                       }
                    update conList;
                }
                catch (System.QueryException e) {
                    System.debug('Contact Query Issue: ' + e);
                } 
                try {           
                    for (Lead leads : [select Id, Name, Email, HasOptedOutOfEmail from lead
                                   where Email =: envelope.fromAddress and isConverted = false and hasOptedOutOfEmail = false
                                   limit 100]) {   
                                       leads.hasOptedOutOfEmail = true;
                                       leadList.add(leads);
                                       System.debug('Lead Records: ' + leads);   
                                   } 
                    update leadList;
                }
                
                catch (System.QueryException e) {
                    System.debug('Lead Query Issue: ' + e);
                }   
                
                System.debug('Found the postInstallScriptExample word in the subject line.');
            } 
            else {
                System.debug('No postInstallScriptExample word found in the subject line.' );
            }
            // Return True and exit.
            result.success = true;
            return result;
        }
    }
    

    dont miss out iconCheck out another amazing blog by Shweta here: System Mode and User Mode in Salesforce

    Let’s write a test class for the above PostInstallScripteExample class:

    @isTest
    private class PostInstallScripteExampleTest{
        static testMethod void test1() {
            // Create a new email and envelope object.
            Messaging.InboundEmail email = new Messaging.InboundEmail() ;
            Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
            Lead l = new lead(firstName='John', 
                              lastName='Smith',
                              Company='Salesforce', 
                              Email='user@acme.com', 
                              HasOptedOutOfEmail=false);
            insert l;
            Contact c = new Contact(firstName='john', 
                                    lastName='smith', 
                                    Email='user@acme.com', 
                                    HasOptedOutOfEmail=false);
            insert c;
            email.subject = 'test Post Install Script';
            env.fromAddress = 'user@acme.com';
            PostInstallScripteExample Obj = new PostInstallScripteExample();
            Obj.handleInboundEmail(email, env );
        }
    }
    

    Reference: salesforce.stackexchange