Thursday, March 16, 2023

Understand Salesforce Integration and HTTP Methods

What is Salesforce Integration?

Salesforce integration is the process of merging the data and functionality of Salesforce with another application to provide users with a single unified experience. It allows you to provide your team with an ideal mix of features pertaining to both platforms.

These classes expose the HTTP request and response functionality.

Http Class: Use this class to initiate an HTTP request and response.

HttpRequest Class: Use this class to programmatically create HTTP requests like GET, POST, PATCH, PUT, and DELETE.

HttpResponse Class: Use this class to handle the HTTP response returned by HTTP.


Most common HTTP methods:

1. GET : The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.

2. POST : A POST request is used to send data to the server and create the record.

3. PUT : PUT is used to send data to a server to create/update a resource. Replaces all the current representations of the target resource with the uploaded content.

4. PATCH : PATCH is used to update partial resources. For instance, when you only need to update one field of the resource, PUTting a complete resource representation might be cumbersome and utilizes more bandwidth.

5. HEAD : HEAD is almost identical to GET, but without the response body. HEAD transfers the status line and the header section only.

6. DELETE : The DELETE method deletes the specified resource.

7. OPTIONS : The OPTIONS method describes the communication options for the target resource. 


public class AuthCallout {
    public void basicAuthCallout(){
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://www.yahoo.com');
    req.setMethod('GET');
    // Specify the required user name and password to access the endpoint
    // As well as the header and header information
    String username = 'myname';
    String password = 'mypwd';
    Blob hValue = Blob.valueOf(username + ':' + password);
    String authorizationHeader = 'Basic ' +EncodingUtil.base64Encode(hValue);
    req.setHeader('Authorization', authorizationHeader);
    // Create a new http object to send the request object
    // A response object is generated as a result of the request
    Http http = new Http();
    HTTPResponse res = http.send(req);
    System.debug(res.getBody());
    }
 }


Please share the blog and leave a comment about your thoughts.
Click here for more blogs.

Chain Batch Jobs in Salesforce

How to Chain Batch Jobs in Salesforce

First of all, we need to understand why do we need to chain the batch jobs?

Lets take an example:

We have two requirements to do in code. First we need to delete all the contacts and then insert the new contacts received from Integration. In this case, we can have two batch jobs. First job will delete the contacts and then second job will insert the new contacts.

In other words, Chaining jobs is useful if your process depends on another process to have run first. 

Call another batch in finish method so that all the processing of first job is completed and system will have the updated data before the second job.

global class MyBatchClass implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
        // collect the batches of records
    }
    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    }  
    global void finish(Database.BatchableContext bc){
        // call the other batch in finish method.    
        secondBatchJob obj = new secondBatchJob();    
        database.executeBatch(obj,<batch size>);
    }  
}    

Please share the blog and leave a comment about your thoughts.

Click here for more blogs

Monday, March 13, 2023

Iterable Batch Apex Salesforce

        Iterable Batch Example

If your logic is based on rows from an SObject then the Database.QueryLocator is the way to go as that allows the batchable to query very large numbers of records.

But sometimes you may want to do some work that isn't directly related to SObject rows. In that case the iterable object can simply be an array/list:

public class ExampleBatchApex implements Database.Batchable<String>{
public Iterable<String> start(Database.BatchableContext BC){
    return new List<String> { 'When', 'shall this' , 'quarantine be over' };
}
public void execute(Database.BatchableContext info, List<String> strList){
    //let’s do something with the string for fun
    String myStr = strList[0];
}
public void finish(Database.BatchableContext info) { }
}

// executing the batch apex
Id jobId = Database.executeBatch(new ExampleBatchApex());

Monday, March 6, 2023

Resolve Error 'Unable to lock row' in Salesforce

How to Resolve Unable to lock row error in Salesforce

When a record is being updated or created, Salesforce places a lock on that record to prevent another operation from updating the record at the same time and causing inconsistencies on the data.

Record locking errors is a common source of headache for people coding Data Migrations or Integrations with Salesforce. The good news is that most of the time It's our own integration code that is causing self-contention as opposed to some other user locking the record on us (because we are plowing too many conflicting updates at once, usually in an effort to improve performance). It can also be caused by Salesforce code that is triggered by our updates that require the locks, and then, when not getting them, ultimately fail. Then, that error bubbles up and our updates fail.

Lets walk through an example:

  1. User A imports a task via the data loader and assigns it to an existing account record. When the task is inserted, the apex trigger is fired.
  2. Just 2 seconds after User A starts the insert via the data loader, User B is manually editing the same account record the task is related to.
  3. When User B clicks Save, internally we attempt to place a lock on the account, but the account is already locked so we cannot place another lock. The account had already been locked by the creation of the Task.
The 2nd transaction then waits for the lock to be removed. Because the task takes about 14 seconds to be created, the lock is held for 14 seconds. The second transaction (from User B) times out, as it can only wait for a maximum of 10 seconds.

To prevent this, you can do either of the following:

  • Reduce the batch size
  • Process the records in Serial mode instead of parallel, that way one batch is processed at a time.
  • Sort main records based on their parent record, to avoid having different child records (with the same parent) in different batches when using parallel mode. 
  • Check for overlapping schedules, 2 schedules updating the same object should not start at the same time if possible.

Please share the blog and leave a comment about your thoughts.

Click here for more blogs

How to cover code for catch block in Apex

Sometime developer needs to cover the catch part in the Apex Class.

Code Snippet:

try{
    Account acc = new Account();    
    acc.Name = 'Test';    
    Database.insert (tempList,false);
}
catch(exception e){
    LogObj obj = new LogObj();
    obj.error = e.getMessage();
    insert obj;
}

To cover the catch, we can modify the code as shown:

try{
    boolean allOrNone = false;
    Account acc = new Account();    
    acc.Name = 'Test';    
    Database.insert (tempList, allOrNone );
    if(Test.isRunningTest()){
        Database.insert (tempList, 0);
    }
}
catch(exception e){
    LogObj obj = new LogObj();
    obj.error = e.getMessage();
    insert obj;
}

In this case, code will run the Database.insert (tempList, 0); line and will eventually fail and code will go to catch block.

Please share the blog and leave a comment about your thoughts.

Click here for more blogs

Mostly Viewed