Tuesday, February 23, 2021

Salesforce Lightning: Assign a record to yourself

Let's assume that you want to assign an account or multiple account records to yourself from the detail record view and the list view respectively. You can easily implement the same using only flows if you want to take up a declarative approach.

I have created an autolaunched flow which accepts both single and multiple record ids. Care should be taken that the name of the variables should be exactly id and ids respectively.

To call this flow, create a custom button each for detail and list page and add it on the layout pages. So for the detail page, set the id flow variable to be the account ID, and once the flow is completed, redirect the user to the same account detail page by providing the retURL parameter in the flow URL.

For the list view page, make sure that Display Checkboxes is selected. The ids variable is populated automatically when one or more records are selected in the list view page. The only caveat is that once the flow is completed, I couldn't find a declarative way to redirect the user to the same list view page from where the flow was executed (you can use a Visualforce page to redirect to the list view). So for the sake of simplicity, I am redirecting the user to the Recently Viewed Accounts page.

Next, we have to add these buttons. To add the button on the detail page layout,

and to add on the list view page,

You can get the flow and the associated custom buttons files from this repository.

Share This:    Facebook Twitter

Thursday, January 28, 2021

Salesforce Classic: Assign a record to yourself

Let's consider a use case where you want to assign a record (in this case, Workorder) to yourself. To implement this scenario, click on New Button or Link button. Enter the details as below:

and provide the below script:

{!REQUIRESCRIPT("/soap/ajax/49.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/49.0/apex.js")}

var __sfdcSessionId = '{!GETSESSIONID()}';
sforce.connection.sessionId = __sfdcSessionId;

var workOrder = new sforce.SObject("WorkOrder");
workOrder.Id = "{!WorkOrder.Id}";
workOrder.OwnerId = sforce.connection.getUserInfo().userId;
result = sforce.connection.update([workOrder]);
 
if (result[0].getBoolean("success")) {
    console.log(result[0].id + " updated");
} else {
    console.log("failed to update " + result[0]);
}
window.location.reload();

Now add this button on the page layout.

Share This:    Facebook Twitter

Sunday, January 3, 2021

Improving Salesforce Apex Performance

Improving CPU Time

In general, there are two ways to improve the CPU usage:

  • Work on a smaller amount of data (that is, do less work).
  • Operate on the data in a more efficient manner.
Faster for loops

In the following code snippet, we are using the SOQL for loop format to loop through the account records and a traditional iterator-style for loop:

List<Account> accs = AccountSelector.getAccounts();

Integer max = accs.size();
for (Integer i = 0; i < max; i++) {
   System.debug(accs[i].Name);
}
for (Account acc : AccountSelector.getAccounts()) {
   System.debug(acc.Name);
}

As per the tests, the iterator loop runs faster than the SOQL for loop. Therefore, we should use the iterator format for best performance in CPU time, though we do use a lot more heap size in the iterator.

This is an important example that highlights the fact that when optimizing for one governor limit, we will often impact another.

Using maps to remove and reduce looping

The simplest use case is when retrieving a list of records from a query and then putting them into a map so that you can retrieve a record using its ID.

Map<Id, Account> accsById = new Map<Id, Account>([SELECT Id, Name FROM Account]);
Account myAccount = accsById.get(myAccountId);
Reducing the use of expensive operations

If we wanted to retrieve the Name field of our account record and assign its value to a variable, we could do it in one of two ways. We could either call the Name field using a static reference or call the get method on the record, passing in the field name.

String accName = acc.Name;
String accountName = (String)acc.get('Name');

The second option is slower and more CPU intensive than the first one.

Another commonly used dynamic call is to the Schema class to retrieve information about metadata within the org. The simplest way to handle these situations is to cache values locally in variables for reuse. If you are making repeated calls to any of that describe information, you should work to cache these results in a local variable outside the loop, which will remove the need to make repeated calls and reduce your CPU time overall.

Reducing Heap Size Usage

The heap size is the amount of memory being used to store the various objects, variables, and state of the Apex transaction in memory as it is being processed. For synchronous operations, this is capped at 6 MB and is doubled to 12 MB for asynchronous processes.

Using scoping

We can either declare variables at a class level or within a code block (a method, loop, and so on) within Apex. Declaring a class-level variable means that the variable will be available in memory for the lifetime of the instance of that class, while variables declared in a code block will only be available for the scope of that block.

Structuring your code well into discrete functions with limited scope will help to ensure that your code avoids the heap size limit by allowing the Apex memory manager to handle memory effectively.

Removing unwanted items

Let’s refer the code snippet for the traditional iterator-style for loop we had used earlier. A simple action of setting the value of the accs variable to null reduces the heap size we are consuming.

List<Account> accs = AccountSelector.getAccounts();

Integer max = accs.size();
for (Integer i = 0; i < max; i++) {
   System.debug(accs[i].Name);
}
accs = null;

It can be useful therefore to remove any unwanted items from memory manually if you are working with large sets of data or the Blob data type and wish to free space to ensure that you do not hit the heap size limit. Combining this with scoping will help you ensure that the memory of your applications is well managed and, in most instances, you will have no concerns with the heap size limit.

Improving Query Selectivity

In order to achieve the best performance possible, we want to make our query as selective as possible to reduce the number of records returned.

The first thing that indicates selectivity is whether the field is indexed. The following types of field are indexed:

  • Standard primary keys (Id, Name, OwnerId)
  • Foreign key fields (CreatedById, LastModifiedById, lookup relationships, master-detail relationships)
  • Audit fields (CreatedDate, SystemModstamp)
  • Custom fields marked as unique or External Id

If a field is indexed, it will be considered for optimization. Following this, the optimizer then determines how many records are returned using that index. The following calculation is made to determine whether the number of records selected is below the following thresholds:

  • For standard indexes, 30 percent of the first million targeted records and 15 percent of the remaining records. The threshold is 1 million records.
  • For custom indexes, 10 percent of the first million targeted records and 5 percent of the remaining records. The threshold is 333,333 records.

If the indexed field meets these thresholds, it is considered selective and will be considered for optimization. Salesforce provides developers with the Query Plan tool in the Developer Console that will provide detailed information on whether a query is selective or not. To enable this in the Developer Console, open the Preferences menu and select the Enable Query Plan option. Once you have selected this option and saved, using the Query Editor pane, you can enter a query and use the Query Plan button to view metrics on the selectivity of a query. The statistics returned here inform us of which filter would be used (if any) and why. The columns presented have the following information:

  • Cardinality: The number of records returned by this operation.
  • Fields: The indexed fields used by the optimizer in this operation. This will be null if the field is not indexed.
  • Leading Operation Type: The primary operation used by the optimizer to optimize the query, one of either Index for an indexed field, Sharing for sharing rule-based control, TableScan if a full search of the object occurs, and Other if an internal Salesforce optimization is used.
  • Cost: This is a cost score for running the query. Any value over 1 is considered non-selective. We should always aim to have a query with a cost of 1 or less.
  • sObject Cardinality: The approximate, number of records on the object.
  • sObject Type: The object we are querying.

The other key practice when defining WHERE filters is to attempt to use positive/ inclusion operations (IN, =) rather than negative/exclusion operators (NOT, !=) as these exclusion operations are not optimizable, except when using != null and != boolean. It is a good practice therefore to ensure wherever possible that you use positive/inclusion operations to improve optimization chances.

Number of Queries

There are also a couple of simple ways in which you can reduce the number of queries you are running.

Retrieving child records with a sub query

If retrieving a record and you require child records, consider using a sub query where appropriate to help retrieve all the necessary data at once. This is not always necessarily a good practice; for example, when determining the Batch Apex scope, it is more performant to select the parent records in the batch scope and retrieve the child records in each batch. If you are working with a selective query on the parent record and retrieving a small set of data for each returned record, then this can help avoid additional loops, mapping, and queries.

Cache results

If the data is not expected to change during the transaction, a developer can use the singleton pattern to cache results that were retrieved. This is an extremely effective tool when retrieving setup-related objects (Profile, Holiday, Role) or custom metadata or custom settings. None of these items should change during the course of a transaction and are slow-moving data, making them comfortably cacheable for the duration of the transaction.

Platform Cache

Platform Cache is a powerful feature that can enhance the performance of applications when working at scale and requiring data to be retrieved in a regular fashion, but that does not change regularly. A free allocation of 10 MB of cache is provided for Enterprise Edition orgs, and 30 MB for Unlimited and Performance Edition, with a greater allowance available for purchase. If you are working in an environment where there is a set of data that is retrieved regularly but does not change, and you have available a Platform Cache allocation, then consider it as a possible enhancement to help improve your system's performance.

Share This:    Facebook Twitter

Sunday, December 27, 2020

Access Grant, Share and Maintenance Tables

Record Access Calculation

As there are many options for managing record level access, and as some of these options are affected by organizational dependencies, determining which records users can access can quickly become complicated. Rather than checking record access in real time, Salesforce calculates record access data only when configuration changes occur. The calculated results persist in a way that facilitates rapid scanning and minimizes the number of database table joins necessary to determine record access at runtime.

Access Grants

When an object has its OWD set to Private or Public Read Only, which is not the least restrictive option, Salesforce uses access grants to define how much access a user or group has to that object’s records. Each access grant gives a specific user or group access to a specific record, It also records the type of sharing tool: sharing rule, team, etc.

Salesforce uses 4 types of access grants:

Explicit grants:

Grants that occur when records are shared directly to users or groups. Examples:

  • A user or a queue becomes the owner of a record, as in Salesforce each record should have an owner, and whenever a record is owned by a user or a queue, an explicit share is used to grant access to the record for the owner or queue.
  • A sharing rule shares the record to a personal or public group, a queue, or a role.
  • An assignment rule shares the record to a user or a queue.
  • A territory assignment rule shares the record to a territory.
  • A user manually shares the record to a user, a personal or public group, a queue, or a role.
  • A user becomes a part of a team for an account, opportunity, or case.
  • A programmatic customization shares the record to a user, a group, or queue, or a role.
Group membership grants:

Grants that occur when a user, group, queue, role, or territory is a member of a group that has explicit access to the record. So as you know by now, an explicit share is used to grant access to group via sharing rules, manual sharing or Apex sharing, because of which all members of a group are granted access using the group membership access grant. For example, if a sharing rule grants the “Sales group” access to the Acme account record, and Bob is a member of the “Sales group”, Bob’s membership in the “Sales group” grants him access to the Acme account record.

Inherited grants:

Grants that occur when a user, group, queue, role, or territory inherits access through a role or territory hierarchy or is a member of a group that inherits access through a group hierarchy. For example, if a user Alice has a role that is higher in the role hierarchy than the role of another user Bob, then Alice can access the same records that Bob can access.

Implicit grants:

Grants that occur when non-configurable record-sharing behaviours built into Salesforce Sales, Service and Portal applications grant access to certain parent and child records. Examples:

  • Read-only access to the parent account for a user with access to a child record.
  • Access to child records for the owner of the parent account record.
  • Access to a community account and all associated contacts for all community users under than account
  • Access to data owned by community users associated with a sharing set for users member of the sharing set’s access group.

Object Share tables store the data that supports explicit and implicit grants.

SELECT Id, ParentId, UserOrGroup.Name, AccessLevel, RowCause FROM AccountShare

Group maintenance tables store the data that supports group membership and inherited access grants.

SELECT Id, Name, DeveloperName, Type, OwnerId FROM Group
Share This:    Facebook Twitter

Monday, December 7, 2020

Secure Salesforce Apex Programming

How permissions and sharing work on Salesforce

The Salesforce platform has two main ways of controlling access to records—permissions and sharing. Permissions in Salesforce focus on what you can do with a particular object in general. Sharing focuses on what records you can see for that object based on their ownership.

With Salesforce's permissions and sharing tools, you can build up a very granular set of visibility permissions that control exactly who can access the different records within your org. When you attempt to retrieve a record in Salesforce, these permissions are checked before any further processing occurs. Following this, sharing calculations are then run to verify whether you have access to the record or records that you are retrieving.

Sharing and performance

As an application grows on the platform, the volume of data stored on it will also inevitably grow. The obvious side effect of this is that querying for records and loading lists of data can become much slower. To help keep your application performant, you should reduce the amount of data every user can see to that which is strictly necessary. This will ensure that queries, list views, reports, and all manner of functionalities continue to run in an optimal way and don't slow down the user experience.

Enforcing sharing

By default, all Apex operations (and Process Builder and certain Flows) run in System Mode; that is, they execute as a generic system user that has access to all metadata and data within the org. Within our Apex configuration, sharing is enforced through the use of the with sharing keywords in our class definition. Declaring either with sharing or without sharing explicitly is a deliberate action for us to verify that we either do or do not want the sharing rules for the current user to be enforced. If we do not define a class as with sharing or without sharing explicitly (ClassC), then the current sharing rules remain in force.

public with sharing class ClassA {
	public static List<Account> getAccounts() {
		return ClassC.getAccounts();
	}
}

public without sharing class ClassB {
	public static List<Account> getAccounts() {
		return ClassC.getAccounts();
	}
}

public class ClassC {
	public static List<Account> getAccounts() {
		return [SELECT Name from Account];
	}
}

If ClassC was the entry point to our transaction, it would operate in without sharing mode by default.

In situations where we want to default to a with sharing context, but enable the code to run in a without sharing context when called from a class defined as without sharing, we can utilize the inherited sharing option as our default. Apex without a sharing declaration is insecure by default. An explicit inherited sharing declaration makes the intent clear, avoiding ambiguity arising from an omitted declaration or false positives from security analysis tooling.

So whenever we are defining our Apex classes, we should apply the following rules to ensure our sharing is actually enforced as we anticipate it to be:

  • Use with sharing when we know we want the sharing model to be enforced.
  • Use without sharing when we know we want the sharing model to be ignored.
  • Otherwise, use inherited sharing as a default.

Sharing records using Apex

Salesforce has several ways of sharing records with users and groups of users such as managed sharing, user-managed (or manual) sharing, and Apex managed sharing:

  • Managed sharing is the point-and-click sharing that most Salesforce developers and administrators are familiar with, and relies upon record ownership, the role hierarchy in the org, and any sharing rules.
  • User-managed sharing or manual sharing is when a user chooses to share a record with a user or group of users using the Share button.
  • Apex managed sharing is the sharing of records with a user or group of users through the use of Apex code.

All three of the methods described store records in the share object associated with the record within the Salesforce database. For every object, there is a corresponding share object. For standard objects, it is the object API name plus share, so AccountShare, ContactShare, and so on. For custom objects, __c in the object API name is replaced by __Share. Sharing via org-wide defaults, the role hierarchy, and permissions such as View All are not stored in these objects.

So as an example, to create an AccountShare record, we require to set the following information:

  • The ID of the record to be shared with the ParentId field.
  • The user of group to be shared within the UserOrGroupId field.
  • An access level, either Edit or Read, in the AccessLevel field.
  • A reason for sharing in the RowCause field. The default value is Manual, as we have set here, however custom reasons can be set by adding them through the setup menu.
AccountShare newShare = new AccountShare();
newShare.ParentId = accId;
newShare.UserOrGroupId = userId;
newShare.AccessLevel = 'Read';
newShare.RowCause = Schema.AccountShare.RowCause.Manual;
accShares.add(newShare);

Enforcing object and field permissions

We have two ways of enforcing our object-level and field-level permissions in Apex code, the first of which is to utilize the describe methods within Apex to verify that the user had the correct permissions. The methods to verify the permissions for an sObject are as follows and are utilized on the Schema.DescribeSObjectResult instance for the given sObject:

  • isAccessible
  • isCreateable
  • isUpdateable
  • isDeletable

For example, we can verify permissions on a Contact object as follows:

if(Schema.sObjectType.Contact.isAccessible()) {
   // Read Contact records
}

if (Schema.sObjectType.Contact.isCreateable()) {
   // Create Contact records
}

if (Schema.sObjectType.Contact.isUpdateable()) {
   // Create Contact records
}

if (Schema.sObjectType.Contact.isDeletable()) {
   // Create Contact records
}

Similarly, at the field level, on the Schema.DescribeFieldResult instance for a field, we have the following methods:

  • isAccessible
  • isCreateable
  • isUpdateable

All of these are available to us to verify that we have the correct permissions to manipulate a field:

if(Schema.sObjectType.Contact.fields.Email.isAccessible()) {
   // Read Contact record Email
}

if (Schema.sObjectType.Contact.fields.Email.isCreateable()) {
   // Populate Contact record Email
}

if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) {
   // Edit Contact record Email
}

We can also enforce field and object permissions using the Security.stripInaccessible method, which takes two parameters. The first is an access level that we wish to verify against, and the second is a List<sObject>. The method then removes any fields that the user does not have the stated access level for. It is also particularly useful for sanitizing records as a whole, such as when we are providing an API and receiving sObject data from external users. Read more about the stripInaccessible method here.

In the following code, we are using the stripInaccessible method to remove any fields that the user does not have update permissions on:

String jsonBody = '[{"FirstName":"Alice", "LastName":"Jones", "Email": "ajones@test.com"}]';

List<Contact> contacts = (List<Contact>)JSON.deserializeStrict(jsonBody, List<Contact>.class);

SObjectAccessDecision accessDecision = Security.stripInaccessible(AccessType.UPDATABLE, contacts);
update accessDecision.getRecords();

If you still want to throw an exception if the user has no access to any one of the fields using <code>stripInaccessible</code> method, then you can use the below Utils method:

public static List<SObject> checkFieldLevelSecurity(List<SObject> sobjects, AccessType accessCheckType) {
    SObjectAccessDecision decision = Security.stripInaccessible(accessCheckType, sobjects);
    System.debug(LoggingLevel.INFO, decision);
    if (decision.getRemovedFields().size() > 0) {
        throw new QueryException('User cannot read these fields: ' + decision.getRemovedFields());
    }
    return decision.getRecords();
}

And to use checkFieldLevelSecurity method, pass the list of sobjects and the AccessType.

(List<Task>) Utils.checkFieldLevelSecurity(sobjects, AccessType.READABLE);

Enforcing permissions and security within SOQL

Salesforce added the WITH SECURITY_ENFORCED clause to the SOQL language. Unlike the stripInaccessible method, if the user is lacking permissions for a field, an exception is thrown rather than the field simply being removed.

To apply this clause, we simply include WITH SECURITY_ENFORCED after any WHERE clause and before any ORDER BY, LIMIT, OFFSET, or aggregate function clauses. For example, consider the following:

List<Contact> contacts = [SELECT FirstName, LastName, Secret_Field__c FROM Contact WITH SECURITY_ENFORCED];

In the preceding query, if the user has no access to Secret_Field__c, then an exception will be thrown, indicating insufficient permissions.

Avoiding SOQL injection vulnerabilities

The first and most simple is to ensure we are using Apex binding variables and static queries. By default, Apex binding variables are automatically escaped and so will ensure that the query would run as expected.

public String searchName {get; set;}

public PageReference search() {
   return [SELECT Id, LastName, Email FROM Contact WHERE LastName Like :searchName];
}

There are instances where we must use a dynamic query. In these instances, we should ensure that we escape any input from the end user using the escapeSingleQuotes method:

public String searchName {get; set;}

public PageReference search() {
   return Database.query('SELECT Id, LastName, Email FROM Contact WHERE LastName Like \'%' + String.escapeSingleQuotes(searchName) + '%\'');
}
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top