Asynchronous calls with @Future

In this blog, I am going to how to make the asynchronous calls with @Future annotations .with the Future annotation you can make asynchronous Web service callout to an external service.A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time.

What is Asynchronous Process in Salesforce 

An asynchronous process is a process or function which does not require interaction with a user. It can be used to execute a task “in the background” without the user having to wait for the task to finish. Force.com features such as Asynchronous Apex (@future), Batch Apex, Bulk API, Reports and other features use asynchronous processing to efficiently process requests.Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.

Use Case: – Upon Creation of Account Record, you need to validate the billing address of account and update latitude and longitude values.

Solution: – Create a trigger of account on after insert and after update.  Invoke  an asynchronous Webservice call with @future annotation to validate the address against google API and return latitude and longitude

Trigger :- 

trigger AccountTriger on Account (after insert) {

    AccountUpdateAsync.updateAccountAddress(Trigger.new[0].Id);

}

Apex Class:-

 public class AccountUpdateAsync {
    @future(callout=true)
    public static void updateAccountAddress(String accId){
        Account acc = [Select Id , Name ,Location__Latitude__s  , Location__Longitude__s, 
                       BillingStreet ,BillingCity ,BillingState ,BillingPostalCode,
                       BillingCountry from Account where id =:accId Limit 1];

        String httpReqURI = 'https://maps.googleapis.com/maps/api/geocode/json?address='+
            acc.BillingStreet+','+acc.BillingCity+','
            +acc.BillingState+','+acc.BillingPostalCode+','+
            acc.BillingCountry
            +'&key=<API_KEY>';
        HttpResponse response = sendHttpReq(httpReqURI);

        if (response.getStatusCode() == 200) {
            JSONParser parser = JSON.createParser(response.getBody());
            Map <String, Object> root = (Map <String, Object>) JSON.deserializeUntyped(response.getBody());
            List <Object> childLevel = (List<Object>) root.get('results');
            for( Object o : childLevel){
                Map <String, Object> childLevel2 = (Map <String, Object>) o;
                Map <String, Object> grandChaildLevel= (Map <String, Object>) childLevel2.get('geometry');
                Object objFinal = grandChaildLevel.get('location');
                Map<String, Object> locs = (Map<String, Object>)objFinal;
                acc.Location__Latitude__s = (Decimal)locs.get('lat') ; 
                acc.Location__Longitude__s = (Decimal)locs.get('lng');
                update acc;
            }

        }

    }

    public static HttpResponse sendHttpReq(String url){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(url);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        return response;

    }

    public static  void parseJson(String json){

    }

}

Future method Considerations:- 

Below are the future method considerations

  1. Methods with the future annotation must be static methods and can only return a void type.
  2. The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. No sObjects or objects as arguments
  3. The future method does not necessarily execute in the same order it is called.
  4. Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  5. You cannot call a method annotated with future from a method that also has the future annotation
  6. future calls cannot be made from a batch job
  7. future calls can execute concurrently

 

Best Practices:-

future methods are having its own advantages.  Consider this below best practices while implementing the future calls

  1. Make @future  code is efficient as possible. Long execution times increase the chance of delays and extended delays.
  2.  Minimize the number of the asynchronous requests created to minimize the chance of delay and extended delays.
  3. Make sure you are not invoking too many future calls when you are invoking from the trigger . I would advice one future call for one trigger transaction.
  4. Avoid recursive behavior in future calls.Use a static variable to store the state of the trigger processing
  5. Consider using Batch Apex instead @future to process a large number of records asynchronously.
  6. asynchronous processing framework is queue-based, lower priority than real-time interaction Best practice – ensure @future requests execute as fast as possible and remember limits: 10 @futures each making at most 10 callouts.

 

Limits :-

Future calls have below limits

  1. No more than 10 @future method calls per Apex invocation.
  2. You’re limited to 50 future calls per Apex invocation, and there’s an additional limit on the number of calls in a 24-hour period.  The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. Still, all salesforce licenses are not applicable fo this limits . for examples chatter licenses are not part of this.  More limits you can refer in salesforce limits guide.

 

 

Salesforce Apex Managed Sharing

In this blog post, I am going to explain how to use apex managed sharing. Apex managed sharing allows developers to programmatically share custom objects. When you use Apex managed sharing to share the custom object, only users with the “Modify All Data” permission can add or change the sharing on the custom object’s record, and the sharing access is maintained across record owner changes.

Apex Manager sharing can be enabled on the object that is having private and public read-only access.

1.Apex Managed Sharing can not be enabled on public read-write objects
2.Each custom object is having its own sharing table with __share name if the object sharing is private or public read-only
3.Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.
4.Objects on the detail side of a master-detail relationship do not have an associated sharing object. The detail record’s access is determined by the master’s sharing object and the relationship’s sharing setting

Understanding Sharing Reason:-
the Reason field on a custom object specifies the type of sharing used for a record. This field is called rowCause in Apex or the Force.com API. you can use the Sharing reason in Force.com Managed Sharing, User Managed Sharing, Apex Managed Sharing

RowCause values depend on the type of sharing .its can be Owner, team, share, manual etc depends on the type of sharing the reason.

Access Levels:-
Access level is determining a user’s access to records. Most share objects support the following access levels: Supported Access levels are Private, Read Only, ReadWrite, Full Access
Every share object has the following properties:-
AccessLevel – Can be any of the Edit, Read, All
ParentID – The ID of the object
RowCause – The reason why the user or group is being granted access
UserOrGroupId – The user or group IDs to which you are granting access

User Managed Sharing Using Apex:-
Now we are going to create an apex class that is used to share the data based on sharing.It is possible to manually share a record to a user or a group using Apex or the SOAP API. If the owner of the record changes, the sharing is automatically deleted


public with sharing class DeliverySharingCls {
    public static void shareDelivery(list<Delivery__c> delivery){
        List<Delivery__Share> totalShares = new List<Delivery__Share>() ; 
        for( Delivery__c d : delivery){
            // Create new sharing object for the custom object Delivery__c.           
            Delivery__Share share = new Delivery__Share() ; 
            // Set the ID of record being shared.
            share.ParentId = d.Id ;
            // Set the ID of user or group being granted access. Insted of the heard coded user id , you need to create fetch the 
            // id dynaically 
            share.UserOrGroupId = '00541000000RlIa';
            // Set the access level.
            share.AccessLevel = 'Edit';
            // Set rowCause to 'manual' for manual sharing.
            share.RowCause = Schema.Delivery__Share.RowCause.Manual;
            totalShares.add(share); 
        }

        if(totalShares.size()>0){
            list<Database.SaveResult> saveres = Database.insert(totalShares) ; 

        }
    }

}

Invoke the above code from the trigger to share the data as shown below.


 trigger DeliveryShare on Delivery__c (after insert) {
    DeliverySharingCls.shareDelivery(trigger.new) ;

}

Creating Apex Managed Sharing:-

Apex managed sharing enables developers to programmatically manipulate sharing to support their application’s behavior through Apex or the SOAP API

Apex managed sharing must use an Apex sharing reason. Apex sharing reasons are a way for developers to track why they shared a record with a user or group of users.
Apex sharing reasons are defined on an object’s detail page.
To Create a Apex Managed Sharing reason on the custom Object
go to –> setup -> create ->object ->Delivery__c -> under Apex Managed Sharing Reason ->Click New and create a sharing reason as shown below .

Apex sharing reason name: Custom Sharing Model
In order to use it in the code, you have to use it as shown below
Schema.Delivery__share.rowCause.Custom_Sharing_Model__c
Now Update the above code with the rowCause as shown below.


public with sharing class DeliverySharingCls {
    public static void shareDelivery(list<Delivery__c> delivery){
        List<Delivery__Share> totalShares = new List<Delivery__Share>() ; 
        for( Delivery__c d : delivery){
            // Create new sharing object for the custom object Delivery__c.    
            Delivery__Share share = new Delivery__Share() ; 
            // Set the ID of record being shared.
            share.ParentId = d.Id ;
            // Set the ID of user or group being granted access. Insted of the heard coded user id , you need to create fetch the 
            // id dynaically 
            share.UserOrGroupId = '00541000000RlIa';
            // Set the access level.
            share.AccessLevel = 'Edit';
            // Set rowCause to 'Custom Sharing model' for manual sharing.
            share.RowCause = Schema.Delivery__Share.RowCause.Custom_Sharing_Model__c;
            totalShares.add(share); 
        }

        if(totalShares.size()>0){
            list<Database.SaveResult> saveres = Database.insert(totalShares) ; 

        }
    }

}

 

Apex Managed Sharing Recalculating

In This blog, I am going to explain how to use apex managed sharing recalculation. You can use apex managed sharing recalculation to update the custom object sharing based on your own business logic whenever custom object OWD is changed. You can associate these classes with a custom object on its detail page, and execute them if a locking issue prevents Apex from granting access to a user as defined by the application’s logic

Step 1: Create Batch Class to update sharing recalculation
You can also run sharing update programmatically using the Database.executeBatch method.
In addition, Salesforce automatically runs Apex recalculation classes defined for a custom object every time a custom object’s organization-wide sharing default access level is updated.
Now let’s see the batch class code to update the Sharing recalculation. the final code looks as shown below.

global class DeliverySharingRecalculation implements Database.Batchable<sObject> {

global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator([SELECT Id, Name FROM Delivery__c]);
}

global void execute(Database.BatchableContext BC, List<sObject> scope){
// In this case I am just simply sharing the data with one user. But you
//can adjust the data based on different conditions. Examples If Delivery mode is express you can assign to specific group id Delivery
// is normal you can assign to some other group
List<Delivery__Share> newDelivary = new List<Delivery__Share>();
List<Delivery__c> deli =(List<Delivery__c>)scope ;

for(Delivery__c de : deli){
Delivery__Share delSH = new Delivery__Share();
// Assign it to user or group
delSH.UserOrGroupId = '00541000000RlIa';
//Access level to read
delSH.AccessLevel = 'Read';
// Record Id
delSH.ParentId = de.Id;
// Row Cause
delSH.RowCause = Schema.Delivery__Share.RowCause.Custom_Sharing_Model__c;
newDelivary.add(delSH);
// You can add new sharing and delete the existing sharing based on requirementts
}
Database.SaveResult[] lsr = Database.insert(newDelivary,false);

}

global void finish(Database.BatchableContext BC){
}

}

Step 2: Invoking the batch

You can run the above batch class in different ways like you can schedule the class or run it as the one-time batch.

Another way is to go to Custom object –> Apex Sharing Recalculation –> Click New -> Update the above batch class as shown below.


Limitations :-

When working with Apex sharing recalculations, note the following.The apex code that extends the sharing recalculation can process a maximum of five million records. If this apex code affects more than five million records, the job fails immediately.
You can monitor the status of apex sharing recalculations in the apex job queue.
You can associate a maximum of five Apex sharing recalculations per custom object.
You cannot associate Apex sharing recalculations with standard objects
The class you choose must implement the Database.Batchable interface. You cannot associate the same Apex class multiple times with the same custom object.