Friday, March 17, 2023

With sharing & Without sharing keywords in APEX

With sharing & Without sharing keywords in APEX


With sharing Keyword:

This keyword enforces sharing rules that apply to the current user. If absent, code is run under default system context. Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. Use With Sharing when the User has access to the records being updated via Role, Sharing Rules, Sales Teams – any sort of sharing really.

Example:

public with sharing class sharingClass {

// Code here

}

Without sharing keyword:

Ensures that the sharing rules of the current user are not enforced. Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example, you may want to explicitly turn off sharing rule enforcement when a class acquires sharing rules when it is called from another class that is declared using with sharing. Without Sharing is reserved for cases where the User does not have access to the records, but there is a need to update them based on user input.

public without sharing class noSharing {

// Code here

}

Some things to note about sharing keywords:

  • The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced.
  • If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that the class doesn’t enforce sharing rules except if it acquires sharing rules from another class. For example, if the class is called by another class that has sharing enforced, then sharing is enforced for the called class.
  • Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods.
  • Inner classes do not inherit the sharing setting from their container class.
  • Classes inherit this setting from a parent class when one class extends or implements another.

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

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

Mostly Viewed