Debug “Validation Errors While Saving Record(s)” error message when calling Test.loadData()

Sometimes when you use Test.loadData() you might receive some confusing error message saying “Validation Errors While Saving Record(s)”, it is hard to understand what is wrong in data so it is possible to use the following code to debug the problem


StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'TestData' LIMIT 1];
String body = sr.Body.toString();
String[] fields = body.split('\r\n')[0].split(',');
SObject[] records = new List();
String[] lines = body.split('\r\n');
for ( Integer j = 1; j < lines.size(); j++ ) {
SObject r = new Custom_Object__c();
String[] data = lines[j].split(',');
for (Integer i = 0; i < fields.size(); i++ ) {
System.debug(LoggingLevel.ERROR, '@@@ fields[i]: ' + fields[i] + ' + data[i] ' + data[i] );
r.put( fields[i], data[i]);
}
records.add( r );
}
insert records;

So when you run a code like this you will find out the exact problem you face

Posted in salesforce | Leave a comment

How can we create custom objects in bulk?

There could be several ways to automate sobject creation, if we need to create multiple custom objects.

If you use SFDX, it is possible to use shane plugin to create custom object metadata file and then deploy those files or create a package from them and install the package.

upperlim=2000
for ((i=0; i<=upperlim; i++)); do
echo "$i"
sfdx shane:object:create -t custom -l "CustomObject$i" -p "CustomObjects$i" -a "CustomObject${i}__c"
done

Another option is to use Metadata API and create them in Apex

for (Integer i = 0; i < 100; i++) {
HttpResponse res = MetadataApiCustomObjectCreate.add('CustomObject' + i);
System.debug(res.getBody());
}
public without sharing class MetadataApiCustomObjectCreate {
private static String getSoapBodyXml(String name) {
return ''
+ '<?xml version="1.0" encoding="utf-8"?>'
+ '<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns:xsd="http://www.w3.org/2001/XMLSchema&quot; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">&#39;
+ '<env:Header>'
+ '<urn:SessionHeader xmlns:urn="http://soap.sforce.com/2006/04/metadata">&#39;
+ '<urn:sessionId>' + UserInfo.getSessionId() + '</urn:sessionId>'
+ '</urn:SessionHeader>'
+ '</env:Header>'
+ '<env:Body>'
+ '<createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">&#39;
+ '<metadata xsi:type="CustomObject">'
+ '<label>' + name + '</label>'
+ '<pluralLabel>' + name +'s' + '</pluralLabel>'
+ '<fullName>' + name + '__c' + '</fullName>'
+ '<nameField><label>Name</label><type>Text</type></nameField>'
+ '<deploymentStatus>Deployed</deploymentStatus>'
+ '<sharingModel>ReadWrite</sharingModel>'
+ '</metadata>'
+ '</createMetadata>'
+ '</env:Body>'
+ '</env:Envelope>'
;
}
public static HttpResponse add(String name) {
HttpRequest req = new HttpRequest();
req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + '/services/Soap/m/50.0');
req.setMethod('POST');
req.setHeader('Content-Type', 'text/xml');
req.setHeader('SOAPAction', '""');
req.setBody(getSoapBodyXml(name));
return new Http().send(req);
}
}
Posted in Uncategorized | Leave a comment

Salesforce: Use Apex to find out the current permissions of a user to an object

On enterprise projects Users tend to have a lot of Permission Set assigned.
So sometimes it is hard to determine what kind of access they have to a particular object, since verifying the profile settings and all the permission sets settings is a cumbersome task.
Instead, a simple apex script can do this job.
First, we need to find the DurableId of the object which access we need to check.
For this, we need a simple SOQL Query
SELECT DurableId FROM EntityDefinition where QualifiedApiName = ‘CustomObject__c’
Then we need to combine this with a user id and separate them by a dot and query the corresponding record from UserEntityAccess object.
SELECT Id, IsCreatable, IsReadable FROM UserEntityAccess where DurableId = ’01I0r0000005CqU.0051K000008xPfC’
And now we can see the actual permissions which User has to a particular field.

Posted in Uncategorized | Leave a comment

Find out which permission set provides read access to a field

To find which permission set provides read access to a field, use the following SOQL

SELECT ParentId FROM FieldPermissions WHERE
Field = 'CustomObject__c.CustomField__c'
AND SObjectType = 'CustomObject__c'
AND PermissionsRead = true
AND ParentId IN (SELECT PermissionSetId from PermissionSetAssignment WHERE AssigneeId = '005USerID0000AAA')

view raw
whichPS.soql
hosted with ❤ by GitHub

Posted in Uncategorized | Leave a comment

Salesforce: Use Apex to find out the current permissions of a user to a field

On enterprise projects Users tend to have a lot of Permission Set assigned.
So sometimes it is hard to determine what kind of access they have to a particular field, since verifying the profile settings and all the permission sets settings is a cumbersome task.
Instead, a simple apex script can do this job.
First, we need to find the DurableId of the field which access we need to check.
For this, we need a simple SOQL Query
SELECT DurableId FROM FieldDefinition where EntityDefinitionId = ‘CustomObject__c’ AND DeveloperName = ‘CustomField’
Then we need to combine this with a user id and separate them by a dot and query the corresponding record from UserFieldAccess object.
SELECT Id, IsAccessible, IsUpdatable FROM UserFieldAccess where DurableId = ’01I0r0000005CqU.00N0r000001AgFw.0051K000008xPfC’
And now we can see the actual permissions which User has to a particular field.

Posted in Uncategorized | Tagged , , , | Leave a comment

Hierarchy Custom Settings: the difference between getInstance and getValues methods

For deprecated list custom settings, both getInstance and getValues methods work in the same way.
While for Hierarchy Custom Settings, getInstance and getValues methods work in a slighty different way.
It is widely known that getInstance method would return a parent record if the record doesn’t exist.
However, it is also returning a value from a parent record if the value is not set for the current record.
It gets really tricky for checkbox field. When a custom setting record is queried by SOQL, the null value is returned as false. When a custom setting record is get by getValues method, the field and the value is not present in the record. When a custom setting record is get by getInstance method and the value for the parent record is true, getInstance method returns true.
When querying the custom setting by SOQL, there is no way to distinguish whether there is an actual value of “false” in the checkbox field or the value is not set on the record.

There is an interesting article about Boolean in Apex, which discusses the behaviour of Boolean in SOQL as well.
The Curious Nature of the Salesforce Boolean https://www.ktema.org/2018/05/28/curious-boolean-nature/
However, there is a statement in the article which suggests that a cascade never happens for a Checkbox field, which isn’t true.
For an existing custom setting records created before introducing a checkbox field, the corresponding checkbox value is null, and cascade happens here.

Posted in Uncategorized | Tagged , , , | Leave a comment

SOQL Query peculiarities in with sharing context

An interesting fact.
If there are objects A and B and object C has lookups to A and B, and user has access to records of C but doesn’t have access to records of B, user can receive B data by quering C, but not by querying directly B.
So, inside an apex class having with sharing context, the following queries

Select Id, ( SELECT Id, B__c, B__r.Name FROM C__r ) FROM A and

SELECT Id, Name FROM B__c WHERE ID IN ( SELECT B__c FROM C__C )
might return different results.
When user has access to 1 of 4 records of B, by the first query user receives data about all record of B, but in the second case about only one.

Posted in SOQL | Tagged , , | Leave a comment

BOF Per Man 1.0.3

Today I have released a new version 1.0.3 of Bof Per Man.
I will fix two internal errors preventing users from installing this package in some cases and organization settings.

#23 If Subscriber Admin has Email Administration set to “System Email”, install or upgrade fails Discovered in 1.0.2 Fixed in 1.0.3
#19 Push Upgrade Failure. Discovered in 1.0.2 Fixed in 1.0.3

The previous release notes:

 

Posted in bofperman | Leave a comment

Published a repo to get Trailhead Data

Earlier I have mentioned that I was using some trailhead api workaround to get Trailhead data and I was fascinated by the app created by others

Now I have decided to investigate more and publish some app to get trailhead data. It should be updated often but it works at March 2020.

I have also published to code https://github.com/Patlatus/Salesforce-Trailhead-Api-Hack

This is a hack implementation to get access to Trailhead API to get Trailhead user points and other attributes. Requests should be used in the form https://trailheadapi.herokuapp.com/?link=/id/userAlias

Posted in Git, salesforce, Uncategorized | Tagged , , , , , , | 3 Comments

Release notes for BofPerMan Version 1.0.2

The following items have been fixed in version 1.0.2

Install error in Group and Professional Edition.
Inability to select Authorization Form and Scorecards in object list in OLS.
Idea, Pricebook2, Product2 and PushTopic do not allow Modify All permission but this wasn’t reflected on OLS.
On search, previous selection is removed: objects, fields, profiles and permission sets.
No spinner on save in OLS and FLS shown
Fields Contract.EndDate and Individual.MasterRecord displayed as Writeable
CPU Time Error for 918 records update

For CPU Time Error, a quick fix was introduced.
The process takes too much CPU time on processing Upsert Save Results when there are more than 306 records to save. Proposed Quick Fix includes avoiding calculation of Upsert Save Results for more than 306 records saving and appropriate message is shown.

I could think of implementation of some generic Event Streaming API subscription as long term fix later.

Also I tried to implement some more features but wasn’t able because of platform limitations.
There is no way to set FLS for fields on ScorecardMetric in Apex, so I can’t expose this in my package.
I would like to add support of Custom Settings and Custom Metadata OLS to my package but this is not yet supported by Apex as well.

Posted in bofperman, Release Notes | 1 Comment

Thanks for the interest in Bof Per Man package

Thanks for submitting web to lead form.

I appreciate your interest in Bof Per Man package

Posted in bofperman | Leave a comment