Concepts or coding lessons of Salesforce that you can implement easily

Salesforce Interview Questions - Part 5

101. What is the difference between public cloud & private cloud in salesforce? Is a public cloud or private cloud?
Answer :
Public Cloud: Could services are provided "as a service" over the Internet with little or no control over the underlying technology infrastructure. More than one tenant can use the same resources.
Private Cloud: This also offers activities and functions "as a service" but is deployed over a company intranet or hosted data center. This is private product for a company or organization offering advance security. Is a public cloud as it is hosted on data centers and data of more than one tenant resides on same servers.

102. What is the difference between apex:pageMessages, apex:pageMessage, apex:Message and apex:Messages?
Answer :

This component displays all messages that were generated for all components on the current page, presented using the salesforce styling. This will display both salesforce generated messages as well as custom messages added to the ApexPages class 


Apex:PageMessage is a component that adds single message on the page. This is used to display custom message using the salesforce formatting


apex:Message is used to display an error on only a specific field. It is used to allow developers to place field specific errors in specific location.


apex:Messages is similar to apex:Message but it displays all errors

103. What are the aggregate functions supported by salesforce SOQL?
Answer :
Following aggregate functions are supported by salesforce SOQL
1. SUM()
2. MIN()
3. MAX()
4. COUNT()
5. AVG()

104. Write a sample aggregate query or explain how to write a aggregate queries?
Answer :
The return types of Aggregate functions are always an array of AggregateResult.

Sample Code

AggregateResult[] ar = [select AVG(Amount) aver from Opportunity];
Object avgAmt = ar[0].get('aver’);

105. Write a code to find the average Amount for all your opportunities by campaign?
Answer :
AggregateResult[] arList = [select CampaignId, AVG(amount) from Opportunity group by CampaignId];
for(AggregateResult ar : arList){
    System.debug('CampaignId ' + ar.get('CampaignId'));
    System.debug('Average Amount' + ar.get('expr0'));

106. What are groups in SFDC and what is their use in salesforce?
Answer :
Groups are set of users. They can contain individual users, other groups, the users in a particular role or territory, or the users in a particular role or territory plus all of the users below that role or territory in the hierarchy.
There are two types of groups:
•  Public groups: Only administrators can create public groups. They can be used by everyone in the organization.
•  Personal groups: Each user can create groups for their personal use.
You can use groups in the following ways:
•  To set up default sharing access via a sharing rule
•  To share your records with other users
•  To specify that you want to synchronize contacts owned by others users
•  To add multiple users to a Salesforce CRM Content library
•  To assign users to specific actions in Salesforce Knowledge

107. Write a syntax and structure of scheduler class?
Answer :
Sample class

global class ScheduleDemo implements Schedulable{
    global void execute(SchedulableContext sc){
        BatchClass b = new BatchClass();

108 .How to schedule export or take the backup of salesforce?
Answer :
Step by Step Instruction:

  • Click Setup >Data Management > Data Export > Schedule Export.
  • Select the desired encoding for your export file. Leaving the default is fine.
  • Check the Include in export checkbox if you want to include attachments in the export (optional)
  • Leave the default Replace carriage returns with spaces if you want your export files to have spaces instead of carriage returns.
  • Select Weekly as the frequency for the exports.
  • Choose start and end dates. Set the end date to sometime in the distant future such as 20 years from the begin date.
  • Set the time of day for your scheduled export. The export is put in a job queue and the exact time of the export will depend on the amount of activity in the queue.
  • You can select the types of data to include in your export. It is best to include all data in your export file. This will make sure all your organizations data is exported.
  • Click Save.

Points to Remember:

  • Formula and roll-up summary fields are never included in exports.
  • Articles are not included from exports.
  • The export notification email is sent to the email address on file for the user who created the scheduled export. There is no way to indicate another email address. If as an Administrator you want the email to go to another person, have them grant you login access, login as them and schedule the data export.
  • Important:
  • Scheduled backup exports of your data are limited to weekly exports.
  • You have 48 hours from the time you are notified the backup is available to download the backup file.
  • The email notification for backups goes to the email address in Salesforce of the person logged in who schedules the backup.

109. How to import attachments using Data Loader in salesforce?
Answer :
Please follow the instructions below.

1. Create an AttachmentList.csv file with the following column headers:
• ParentId - ID of the record to which the attachment should be associated 
• Name - Name of the attachment 
• ContentType - Format of the extension (e.g. .xls, .pdf, etc) 
• OwnerID - ID for the owner of the attachment
• Body - File path to the Attachment on your local machine (C:\Attachments\YourAttachmentFileName.pdf)
2. Log in to the Data Loader. 
3. Select the "Insert" command. 
4. In the 'Select Sforce Object' step, select the 'Attachments’ object. This object is not displayed by default hence check the 'Show all Sforce Objects' checkbox. 
5. Choose the AttachmentList.csv file. 
6. In the mapping step, map the following fields:
• Parent ID 
• Name 
• Owner ID 
• Body - Make sure to map the Body column which you created previously with the file extension. This is how you designate the file and location of the attachments to be inserted. 
7. Click "OK" to start the upload.

110. What is the difference between custom controller and extension in salesforce?
Answer :
Custom Controller: A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.
Controller extension: A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:
• You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
• You want to add new actions.
• You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply.
A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, whereCustomControllerName is the name of a custom controller you want to extend.
Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

111. Difference between with sharing and without sharing in salesforce ?
Answer :
By default, all Apex executes under the System user, ignoring all CRUD, field-level, and row-level security (that is always executes using the full permissions of the current user).
without sharing:
Enforcing the User’s Permissions, Sharing rules and field-level security should apply to the current user.
For example:
public with sharing class sharingClass {
// your Code here
without sharing:
Not enforced the User’s Permissions, Sharing rules and field-level security.
For example:
public without sharing class noSharing {
// your Code here
Enforcing the current user’s sharing rules can impact: (with sharing)
SOQL and SOSL queries – A query may return fewer rows than it would operating in system context.
DML operations – An operation may fail because the current user doesn’t have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.

112. What are email services in salesforce and explain how we can use them in code?
Answer :
Email services are automated processes that use apex class to process the contents, headers and attachment of an inbound email.

Sample code

Use Case: create a contact record if the inbound email subject is Create Contact and body contains contact name

global CreateContactFromEmail implements Messaging.InboundEmailHandler{
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelop envelop){
    Messaging.InboundEmailResult res = new Messaging.InboundEmailResult();
    String strToCompare = 'Create Contact’;
        Contact c = new Contact();
        c.LastName = email.plainTextBody();
        insert c;
        //save text attachments

for(Messaging.InboundEmail.TextAttachment att : email.textAttachments){
    Attachment a = new Attachment();
    a.Name = att.fileName;
    a.Body = att.Blob.valueOf(att.Body);
    a.ParentId = c.Id;
    insert attachment;
//save binary attachments

for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
            Attachment attachment = new Attachment();
            attachment.Name = bAttachment.fileName;
            attachment.Body = bAttachment.body;
            attachment.ParentId = c.Id;
            insert attachment;
res.Success = true;
return res;

113. What is Wrapper Class in Apex Salesforce ?
Answer :
Wrapper class is collections of different data type, subject etc.

In following example  we are  bind Account ,Opportunity standard object. We query and perform

business logic on the Collection of elements across unrelated objects with the custom data type.

Visual Force Page:

<apex:page controller="wrapperDemoCtrl">

<apex:pageBlock title="Account From wrapper  Class">

   <apex:pageBlockTable value="{!wraccount}" var="wra">

   <apex:column value="{!wra.acc.Name}"/>



<apex:pageBlock title="Opportunity From wrapper  Class">

   <apex:pageBlockTable value="{!wraoppn}" var="wropp">

   <apex:column value="{!wropp.op.Name}"/>




Apex Controller :

public class wrapperDemoCtrl {

    public list<wrapperClass> wraplist{get;set;}
    public list<wrapperClass> getwraccount()
            list<Account>acclist=[select Id,Name from Account limit 3];
            wraplist= new list<wrapperClass>();
            for(Account acn: acclist)
            wraplist.add(new wrapperClass(acn));
           return wraplist;
    public list<wrapperClass> getwraoppn()
         list<Opportunity>opplist=[select Id,Name from Opportunity limit 3];
         wraplist= new list<wrapperClass>();
         for(Opportunity opn:opplist )
         wraplist.add(new wrapperClass(opn));
         return wraplist;
    public class wrapperClass{
        public Account acc {get;set;}
        public Opportunity op {get;set;}
        public wrapperClass(Account accn){
                 acc= accn;         
       public wrapperClass(Opportunity opn)

114. How can we hard delete a record using a Apex class/by code?
Answer :
ALL ROWS key word can be used to get all the records including records in the recycle bin.
Below is the sample code to delete contact records from recycle bin
List<Contact> dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS];
Database.emptyRecycleBin( dContactList );

How do you do File Upload using visualforce?
Answer :
Below is the code sample of file upload in visualforce
<!-- Upload a file and put it in your personal documents folder-->
<!-- Page: -->
<apex:page standardController="Document" extensions="documentExt">
<apex:messages />
<apex:form id="theForm">
<apex:inputFile value="{!document.body}" filename="{!}"/>
<apex:commandButton value="Save" action="{!save}"/>
/*** Controller ***/
public class documentExt {
public documentExt(ApexPages.StandardController controller) {
        Document d = (Document) controller.getRecord();
        d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents

115. Explain Class Constructors with example?
Answer :
• A constructor is a special method used to create (or instantiate) an object out of a class definition.
• Constructors never have explicit return types.
• Constructors have the same name as the class.
• Classes have default, no-argument, public constructor if no explicit constructors is defined.
• If you create a constructor that takes arguments and still want a no-argument constructor, you must explicitly define one.
• Constructors can be overloaded, meaning you can have multiple constructors with different parameters, unique argument lists, or signatures.
• Constructors are called before all other methods in the class.
For Example:
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(…) calls the one argument constructor
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(20);
TestObject2 myObject2 = new TestObject2();

116. What are the available Trigger Events?
Answer :
There are 6 trigger events available.
1. Insert
2. Update
3. Delete
4. Merge
5. Upsert
6. Undelete

117. What are the available Trigger contest variables?
Answer :
Below are the list of Trigger context variables
1. isBefore
2. IsAfter
3. isInsert
4. IsUpdate
5. isDelete
6. isUndelete
7. isExecuting
8. new
9. old
10. newMap
11. oldMap
12. size

118. Let’s say we have to update the same record in After Trigger context. Is there any way or workaround?
Answer :
If we create a new instance of a sObject in the Apex Trigger in memory using the Id of the newly created record as provided in the After Trigger context, we can perform an Update DML statement and not get a read only error. This is because in Apex, the SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations. The below snippet of code illustrated this working and not working.
List<Contact> originals = new List<Contact>();
if(mirrorResultMap.values().size() > 0)
    for(Contact origContact : contactRecs.values())
        Contact mirrorContact = mirrorResultMap.get(origContact.Id);
        //origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original Record i.e. Mirror Record WILL FAIL
        Contact origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c = mirrorContact.Id); //This will WORK
    //update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL RECORDS IN MEMORY
    update originals;

119. How to get the picklist value in Apex class?
Answer :
Using Dynamic apex, we can achieve this. On object of type pickilist, call getDescribe(). Then call the getPicklistValues() method. Iterate over result and create a list. Bind it to <apex:selectOptions>.
Code Example:
Let’s say we have a custom object called OfficeLocation__c. This object contains a picklist field Country__c.
The first thing we need to do, within our controller is use the getDescribe() method to obtain information on
the Country__c field:
Schema.DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.getDEscribe();
We know that Country__c is a picklist, so we want to retrieve the picklist values:
List<Schema.PicklistEntry> ple = fieldResult.gerPicklistValues();
The only thing left for us to do is map the picklist values into an <apex:selectOptions> tag can use for display. Here is the entire method from our controller to do this:
public List<SelectOption> getCountries()
  List<SelectOption> options = new List<SelectOption>();
   Schema.DescribeFieldResult fieldResult =
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
   for( Schema.PicklistEntry f : ple)
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   return options;
With our controller logic all complete, we can call the getCountries() method from our Visualforce page,  and populate the <apex:selectList> tag:
<apex:selectList id="countries" value="{!Office_Location__c.Country__c}"
         size="1" required="true">
  <apex:selectOptions value="{!countries}"/>

120. What are the Salesforce annotations ?
Answer :
Apex annotations modify the way a method or class is used.
Below is the list of annotations supported by salesforce :
            Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. This is useful when you are re-factoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.
            Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources.
            To test methods defined with the future annotation, call the class containing the method in a startTest, stopTest code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
            Use the isTest annotation to define classes or individual methods that only contain code used for testing your application. The isTest annotation is similar to creating methods declared as testMethod.
            The @ReadOnly annotation allows you to perform unrestricted queries against the database. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations within the request: DML operations, calls to System.schedule, calls to methods annotated with @future, and sending emails.

            The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript remoting.

            Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.

Apex REST annotations:

            The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
            The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent, and deletes the specified resource.
            The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource.
            The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource.
            The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent, and creates a new resource.
            The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent, and creates or updates the specified resource.

More Salesforce Interview Questions and Answers:


No comments:

Post a Comment