Monday 22 May 2017

Salesforce Interview Questions-Validation Rules




1. What are validation rules?
Validation rule contains an error condition and error message. If evaluation of error condition results in true value, record is not saved, and the error message is generated. Validation rules can be attached to fields. They are executed when a record is created or updated.

2. Can we avoid deletion of records through validation rules?
No. Validation rules fire in insert and update operation.

3. Can we bypass validation Rules?
Validation rules can never be bypassed. If we have upload records and need to bypass validation, then deactivate validation rule and upload records. After upload, again activate validation rule.

4. Is it possible to fire validation only for records which is being getting updated not to newly inserted records?
Yes, We can use ISNEW() function which will return true whenever new record is getting created in validation rule. We can use this function and check our criteria only if ISNEW() function is returning false(means record is being updated).

5. Is there is any way through which validation rule is bypassed while doing upload through data loader but not when user is creating record from user interface?
Yes. Create a checkbox field as API upload and make this field hidden in page layout. Create a validation rule and in evaluation criteria first check if checkbox is false and then check other validation criteria.
Whenever user upload record through data loader, specify value for this checkbox as true in .csv file and then upload it to salesforce. While upload, validation rule will fire and will find checkbox value as true so it will not check other criteria and system will allow to upload records.

6. What is the difference between ISBLANK() AND ISNULL()?
ISNULL() works only for number data type fieds, if we don't populate with value for number fields it will return true.
ISNULL() won't support TEXT data type fields because text fields never become null.
ISBLANK() supports both number as well as text data types.

7. What are cross object formula fields?
Cross-object formulae span two or more objects by referencing merge fields. By using this you can refer parent fields from child record.

8. What are different ways to make field required in salesforce?

While field creation, specify required field as true.
Through page layouts
Validation rule
Apex trigger9. Admin wants to avoid the deletion of child records in master detail relationship. Is it possible to achieve this using point and click functionality?
Yes. First create a roll up summary field on parent which calculates the total count of child records. Now write a validation rule on parent object which checks if previous value of total count is less than new value. If yes, then display error message.
Suppose field name is total_count__c in parent object then validation rule criteria will be:
Priorvalue(total_count__c) <total_count__c
When we delete the child record then roll up summary field value will get reduced by 1. System will update the parent record roll up summary field which will fire the validation rule and avoid user from deleting child record.

Sunday 21 May 2017

Using Database.upsert with external ID field


Using Database.upsert with external ID field
External Id plays very important role if you want to update records without knowing the record Ids or want to relate the child record with parent record without knowing the parent record Id.

As a best practice, you should always make External Id unique. If you are performing upsert with External Id, then following situations will occur:


If no record is found in table with provided External Id, then it will create record in table.
If 1 record is found in table with provided External Id, then it will update record in table.
If more than 1 records is found in table with provided External Id, then system will throw an error.
I am going to cover 2 different aspect of using external Id in apex.


Updating a record with External Id


Create a External Id field on Account as Account_Unique_Number__c and mark it as External Id and unique while creating it.Now we will create a new record using upsert.


Execute below command in developer console


List<Account> acclist=new list<Account>();
acc.name='Demo test1';
acc.Account_Unique_Number__c='00001';
acclist.add(acc);
Schema.SObjectField ftoken = Account.Fields.Account_Unique_Number__c;
Database.UpsertResult[] srList = Database.upsert(acclist,ftoken,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());

}
}
}


As there is no record in Account with Account_Unique_Number__c as 00001, system will create a new record.


Now again we will run same script in developer console and will specify some more field values:


List<Account> acclist=new list<Account>();
Account acc=new Account();
acc.name='Demo test1';
acc.Account_Unique_Number__c='00001';
acc.type='Other';
acc.Industry='Banking';
acclist.add(acc);
Schema.SObjectField ftoken = Account.Fields.Account_Unique_Number__c;
Database.UpsertResult[] srList = Database.upsert(acclist,ftoken,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());

}
}
}


Now you will see that system will update the record as it was able to find a Account record with Account_Unique_Number__c as 00001

Relating a child record with parent record by using parent record Id


In order to understand this, we will create contact record and will relate to account using Account_Unique_Number__c. Execute below code in developer console:

List<Contact> conlist=new list<Contact>();
Contact con=new Contact();
con.lastname='Kumar';
con.Firstname='Kumar';
con.email='sunil02kumar@gmail.com';
Account acc=new Account(Account_Unique_Number__c='00001');
con.Account=acc;
conlist.add(con);
Database.UpsertResult[] srList = Database.upsert(conlist,false);
for (Database.UpsertResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('error has occurred.' + err.getStatusCode() + ': ' + err.getMessage());
System.debug('fields that affected this error: ' + err.getFields());
}
}
}


This will create a new contact for Account which have Account_Unique_Number__c as 00001.


In above code snippet, you can see that in order to relate contact with account, we are not specifying the account 15 or 18 digit record id. We are just specifying the external Id of account and system will maintain the relationship.


Why it is recommended to mark External Id as unique?


Imagine you are creating a contact and specified External Id of parent. Suppose there are 2 records in account table with same value, then system will not able to identify with whom it needs to relate the contact and will throw error saying more than 1 match found.

Same is applicable when you update the record with External Id.

Salesforce Interview Questions-Sharing & Security Part-1




  • 1. What are different levels of security in salesforce?


  • Object level security
The bluntest way that we can control data is by preventing a user from seeing, creating, editing, and/or deleting any instance of a particular type of object, like a Position or Review. Object-level access allows us to hide whole tabs and objects from particular users, so that they don't even know that type of data exists.
On the platform, we set object-level access rules with object permissions on user profiles.
  • Field level security
A variation on object-level access is field-level access, in which a user can be prevented from seeing, editing, and/or deleting the value for a particular field on an object. Field-level access allows us to hide sensitive information like the maximum salary for a position or a candidate's social security number without having to hide the whole object.
On the platform, we set field-level access rules with the field-level security.
  • Record level security
To control data with a little more finesse, we can allow particular users to view an object, but then restrict the individual object records that they're allowed to see. For example, record-level access allows an interviewer like Melissa Lee to see and edit her own reviews, without exposing the reviews of everyone else on her team.
On the platform, we actually have four ways of setting record-level access rules:
Organization-wide defaults
Role hierarchies
Sharing rules
Manual sharing
2. What is Organization wide default?

OWD stands for Organization wide defaults. This setting is defined at object level. OWD defined the default record level sharing for objects. All profiles get at least the privileges defined in OWD. OWD takes three different values -

A. Private
B. Public Read only
C. Public Read-WriteTo find out what should be set as OWD for an object, first find out which user requires least access to an object. OWD is set based upon this users access requirements.
Most restrictive record access is defined using OWD. Access to additional records is made available through Role hierarchy, Sharing rules, Manual sharing.

3. What is role hierarchy?

Role Hierarchy allows additional users access to records. A hierarchy of roles is defined based upon access requirements at record level. Each user belongs to a unique role. If a role has access to some record, than its parent and ancestors will also have access to this record. Roles can be created using the Manager Users menu. Roles are used to control record access, where as profiles are used to specify access at object and field level.

4. What is public group?

Public group consists of users, roles or "roles and subordinates". Sharing rule is defined using public groups. Record that match certain condition can be assigned to users in public groups using Sharing Rules. Sharing rules functionality is available via the menu Sharing Settings.

5. What is manual sharing (User Managed Sharing)?

Manual Sharing is used to grant one-off access. Manual sharing can be granted by record owner, any one above the owner in role hierarchy and System Administrator. Manual sharing is used to handle exception cases where access to a particular record needs to be given to a specific user. There is a Sharing button on the records page. This is used to provide manual sharing.

Finding RecordType access to different profiles by using Metadata API




Consider a scenario in which you have an object which is having more than 10 recordtypes. Now you need to find out which all profiles have access to which recordtype. In order to achieve this, admin has to go to each profile and check the recordtype access. Imagine if you have more than 10 profiles which have access to different recordtype of this object.

In order to avoid this manual effort, I have created a VF page where user can select object and particular profile or all profiles and can see the result on a report. I am using metadata API to achieve this.

Please find below unmanaged pakage installation URL:

https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000NPA0

Or you can download the code from Git by using below URL:

After installation, open tab "RecordType Access Finder". You may get "Unauthorized endpoint URL".



Add endpoint URL to remote site setting.

After opening the tab, select the object and profile for which you want to get report for recordtype access to different profiles. You can also specify "All" for profiles.





If you are getting some error by selection all profiles and clicking on "Retrieve and generate report" button, then it means you profile metadata file size is more so in this case, select one profile at one time and click on "Retrieve and generate report" button.
After this operation is finished, then select another profile and again click on "Retrieve and generate report" button. Repeat same process for all profiles you want to check.

Now click on report link and you will be redirected to SFDC standard report where you can see different recordtypes assigned to different profiles.


Asynchronous Apex- Apex Scheduler, Batch Apex & Future Methods Implementation Tricks





Salesforce provide different options to run asynchronous jobs which can run in background whenever salesforce resources will be available.
  •  Apex Scheduler is one of the options through which you can schedule a job to run after certain interval of time or to run at particular time everyday, every week, every month etc.

  • Batch Apex allows you to process large volume of data. Normal apex class will hit governor limits if we process large volume of data. Batch Apex split the records in different batched and you will get new governor limits for each batch.

  • Future methods runs asynchronously which can be used to perform some operation in background. When you are executing particular code and you want to perform some other operation and don't want to wait for it to get completed, then you can use future method to perform that operation and you can continue executing your code. You can consider that future methods starts new thread or execution.




  1. Now we are going to cover different scenarios related to future methods and apex schedulers and batch apex.

  • Is it possible to call future method from apex scheduler or not?
  • Yes
  1. Below is sample code which I tested for this scenario. After scheduling the scheduler, I checked the debug logs and it was displaying logs for future handler and debug statement present in future method was present in logs.
//Scheduled Apex
public class DemoScheduler1 implements Schedulable{
public void execute(SchedulableContext sc){
system.debug('*******Going to call future method ');
DemoAsynchronousTest.futureMethodCallFromScheduler();
}
}


//apex class containing future method
public class DemoAsynchronousTest{


@future
public static void futureMethodCallFromScheduler(){
system.debug('******futureMethodCallFromScheduler get called');
}

}


  • Is it possible to do Synchronous Web service callouts from scheduled apex? 
  • No.
Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class.

  • Can we call scheduler from future method?
  • Yes
  • Can we call future method from batch apex (from execute method)?
  • No
Is there is any way through which we can call future method from batch apex?
As we know that a webservice can be called from batch class and webservice can call @future method. So in your batch class call webservice and which can call your @future method.


Also you can call future method from finish method in batch class.
What all different things which we need to consider while using future methods?
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
Future methods cannot be called from batch class.

  • Can we modify the scheduler class or classes referenced by this scheduler class if any scheduled job is pending?
  • No

If there are one or more active scheduled jobs for an Apex class, you cannot update the class or any classes referenced by this class through the Salesforce user interface. However, you can enable deployments to update the class with active scheduled jobs by using the Metadata API.

What we can do if we have to deploy the scheduler class or classes referenced by this scheduler class if any scheduled job is pending for that scheduler class in target org?

By default, changes to Apex code that have Apex jobs pending or in progress can’t be deployed. To deploy these changes, do one of the following.
Cancel Apex jobs before deploying changes to Apex code. Reschedule the jobs after the deployment.
Enable deployments with Apex jobs in the Salesforce user interface in the Deployment Settings page.