Tag Archives: Apex

Get Salesforce Org Limits Using Apex

Sample Code:

Map<String, System.OrgLimit> orgLimitMap = OrgLimits.getMap();
System.debug('OrgLimitMap-' + orgLimitMap);

for(String olName :orgLimitMap.keySet()) {
    System.OrgLimit orgLimit = orgLimitMap.get(olName);
    System.debug('Org Limit Name: ' + olName);
    System.debug('Org Limit Used:' + orgLimit.getValue());
    System.debug('Org Limit Available:' + orgLimit.getLimit());
}

Salesforce Apex TriggerOperation Enum

The System.TriggerOperation enum has the following values:

  • BEFORE_INSERE
  • AFTER_INSERT
  • BEFORE_UPDATE
  • AFTER_UPDATE
  • BEFORE_DELETE
  • AFTER_DELETE
  • AFTER_UNDELETE

The new Trigger context variable Trigger.operationType will return System.TriggerOperation enum during trigger context.

If you combine this new context variable and the new Apex switch feature, trigger code becomes much easy to implement and understand.

Sample Switch and enum in Triggers:

trigger AccountTrigger on Account(before insert, after insert, before update, after update, before delete, after delete, after undelete) {
    
    switch on Trigger.operationType {
        
        when BEFORE_INSERT {
            //Invoke before insert trigger handler
            system.debug('Before Insert');
        }
        when AFTER_INSERT {
            //Invoke after insert trigger handler
            system.debug('After Insert');
        }
        when BEFORE_UPDATE {
            //Invoke before update trigger handler
            system.debug('Before Update');
        }
        when AFTER_UPDATE {
            //Invoke after update trigger handler
            system.debug('After Update');
        }
        when BEFORE_DELETE {
            //Invoke before delete trigger handler
            system.debug('Before Delete');
        }
        when AFTER_DELETE {
            //Invoke after delete trigger handler
            system.debug('After Delete');
        }
        when AFTER_UNDELETE {
            //Invoke after undelete trigger handler
            system.debug('After Undelete');
        }
    }
}

Salesforce User Logout Event Trigger

  • Salesforce has introduced LogoutEventStream in Summer’18 release, to get the User logout events.
  • It is a beta feature and to make it available in your org, you need to contact Salesforce Support.
  • After it will available in your Org, you can enable LogoutEventStream.
  • After enabled LogoutEventStream, Salesforce publishes logout events when users log out from the UI.
  • You can add an Apex trigger to subscribe to those events, where you can implement our custom logic during logout.

Enable Logout Events Stream :
Go to Setup | Event Manager (Enter Event Manager in Quick Find) | Click on Logout Event link and click on Update Event on right coroner button and select Enable Streaming.

After enable Logout Events Stream, I have created an Apex trigger on LogoutEventStream object, where I’m saving the User Logout Event information in a Custom Object.

Custom Object:

Apex Trigger:

trigger LogoutEventTrigger on LogoutEventStream (after insert) {
    
    List<LogoutEventInfo__c> leInfoList = new List<LogoutEventInfo__c>();
    
    for(LogoutEventStream les : Trigger.new){
        LogoutEventInfo__c leInfo = new LogoutEventInfo__c();
        leInfo.EventIdentifier__c = les.EventIdentifier;
        leInfo.UserId__c = les.UserId;
        leInfo.Username__c = les.Username;
        leInfo.EventDate__c = les.EventDate;
        leInfo.RelatedEventIdentifier__c = les.RelatedEventIdentifier;
        leInfo.SessionKey__c = les.SessionKey;
        leInfo.LoginKey__c = les.LoginKey;
        leInfo.ReplayId__c = les.ReplayId;
        leInfo.SessionLevel__c = les.SessionLevel;
        leInfo.SourceIp__c = les.SourceIp;
        leInfoList.add(leInfo);
    }
    Insert leInfoList;
}

Now, you can Logout and Login again to check the Logout Event information in Custom Object.

Salesforce Custom Object to Save Logs

As a Salesforce developer sometimes we face different scenarios, where we need to track production error logs or failed records. To save custom logs, here I have created an object Log__c and a helper class LogHandler, which will help to save custom logs for future references.

Object (Log__c) Fields:

Field Label Field API Name Field Type
Class Class__c Text(255)
Method Method__c Text(255)
Description Description__c Long Text Area(32768)
Line Number Line_Number__c Number(8, 0)
HTTP Response HTTP_Response__c Long Text Area(32768)
HTTP Status Code HTTP_Status_code__c Number(6, 0)
Object Object__c Text(255)
Record Id Record_Id__c Text(255)
Type Type__c Picklist(Success, Error, Information)

Apex Class:

public class LogHandler
{
    //Save information log
    public static void logInformation(String className, String methodName, String description){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Information';
        Insert log;
    }
    
    //Save success log
    public static void logSuccessData(String className, String methodName, String description){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Success';
        Insert log;
    }
    
    //Save exception log
    public static void logException(String className, String methodName, String description, Integer lineNumber){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Error';
        log.Line_Number__c = lineNumber;
        Insert log;
    }
    
    //Save HTTP response log
    public static void logHTTPResponse(String className, String methodName, String description, HttpResponse response){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Information';
        if(response != null){
            log.HTTP_Response__c = response.getBody();
            log.HTTP_Status_code__c = response.getStatusCode();			
        }
        Insert log;
    }
    
    //Save result log
    public static void logSaveResult(String className, String methodName, List<Database.SaveResult> saveResultList){
        List<Log__c> logList = new List<Log__c>();
        for (Database.SaveResult sr: saveResultList) {        
            if (sr.isSuccess()) {                    
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Success';
                if(sr.getId() != null){
                    log.Object__c = sr.getId().getSObjectType().getDescribe().getName();
                    log.Record_Id__c = sr.getId();
                }
                logList.add(log);                    
            }else{
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Error';
                log.Description__c = String.valueOf(sr.getErrors()[0].getMessage());
                logList.add(log);  
            }
        }
        if(!logList.isEmpty()){
            Insert logList;
        }	
    }
    
    //Upsert result log
    public static void logUpsertResult(String className, String methodName, List<Database.UpsertResult> upsertResultList){
        List<Log__c> logList = new List<Log__c>();
        for (Database.UpsertResult ur: upsertResultList) {        
            if (ur.isSuccess()) {                    
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Success';
                if(ur.getId() != null){
                    log.Object__c = ur.getId().getSObjectType().getDescribe().getName();
                    log.Record_Id__c = ur.getId();
                }
                logList.add(log);                    
            }else{
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Error';
                log.Description__c = String.valueOf(ur.getErrors()[0].getMessage());
                if(ur.getId() != null){
                    log.Object__c = ur.getId().getSObjectType().getDescribe().getName();
                    log.Record_Id__c = ur.getId();
                }
                logList.add(log);  
            }
        }
        if(!logList.isEmpty()){
            Insert logList;
        }	
    }
}