80 Tricky Salesforce Interview Questions 



1.Whenever case is created send email to case owner. How to do that?

We can do it using workflow.

2.How to call Future methods from Process Builder?
To call Future methods from Process Builder, call the future method from the invocable method. 

3.What is System.RunAs?

Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account. The system method runAs enables us to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. 

The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing.We can use runAs only in test methods


4.What are Mixed DML Exception?

This error means that two Sobjects(setup & non-setup) that we are using in our code can not mix during the same transactions.This restriction exists because some sObjects affect the user’s access to records in the org. 


For example, We cannot insert an account and then insert a user or a group member in a single transaction.


To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.


5.What are the solutions for Mixed DML Operartion?


Solution For Mixed DML Operartion.


1. Separate the Setup object and Non-Setup object dml operation using Future Method.     

2. System.RunAs : Enclose mixed DML operations within System.runAs blocks to avoid the mixed DML error in test class.

6.Difference between before and after trigger?

Before triggers can be used to update or validate record values before they are saved to the database.
Use Before Trigger:In the case of validation check in the same object.
Insert or update the same object.

After triggers
 can be used to access field values that are set by the database (such as a record's Id or lastUpdated field) and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.

Use After Trigger:Insert/Update related object, not the same object.
Notification email.
NoteWe cannot use After trigger if we want to update a record because it causes read only error. This is because, after inserting or updating, we cannot update a record.

7.What are the best practice in avoiding Trigger Recursion?

1. One Trigger Per Object


2. Logic-less Triggers - use Helper classes to handle logic.


3. Code coverage 100%


4. Handle recursion - To avoid the recursion on trigger,we should make sure our trigger is getting executed only one time.


8.What are scenarios where we can use without sharing?


Without Sharing


1.If we have VF page in which we are showing "Sales Rep Performance" which displays a flag in red, green and yellow. Now ideally this field should not be visible whenever a Sales Rep accesses this page. But it is always visible if the class has no keyword specified or if a class has without sharing specified.


2.We want to use apex class globally for integration purspose,then we can use without sharing.


9.Is apex class always execute in system context?

Yes,apex class always execute in system context i.e. Apex code has access to all objects and fields irrespective of the logged in User. 


10.What are the considerations while using with sharing?
  • If the class is not declared as With Sharing or Without Sharing then the class is by default taken as Without Sharing.
  • Both inner classes and outer classes can be declared as With Sharing.
  • If inner class is declared as With Sharing and top level class is declared as Without Sharing, then by default entire context will run in With Sharing Context.
  • If a class is not declared as With/Without Sharing and if this class is called by another class in which sharing rules is enforced then both the classes run with With Sharing.
  • Outer class is declared as With Sharing and inner class is declared as Without Sharing, then inner class runs in Without Sharing Context only(Inner class don’t take the Sharing properties from outer class).
11.What is the difference between apex managed sharing and with sharing?

 Apex Managed Sharing is used to grant the access to the records.It is about pro grammatically configuring sharing rules. Keyword "With Sharing" is used to respect the current user sharing rule.


12.What are considerations while using apex managed sharing?

  • If record owner changes, then sharing created through apex managed sharing are maintained but if user share record manually, then record sharing will be lost if owner changes.
  • User with "modify All Data" can only add, edit or delete records in share table.
13.What are the limitations of manual sharing?
  • Manual Sharing cannot be stricter than Organization Wide Defaults.
  • Manual Sharing is only available on individual records, it is not available for all records of a certain object.
  • Only applicable on records that have Private or Public Read Only access in OWD.
  • When setting Automatic and Manual Sharing users and admins should define if the security should be extended to related records.
14.What is database.savepoint?

database.savepoint is a method which is used to define a point which can be roll back to. If any error occurs during a transaction, that contains many statements, the application will roll back to the most recent savepoint and the entire transaction will not be aborted.

15.What are the considerations while using save point?

  • If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid.
  • References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
  • Each savepoint you set counts against the governor limit for DML statements.
16.What is database.rollback?

Rollback is an operation which returns the database to some previous state. Rollbacks are important for database integrity, because they mean that the database can be restored to a clean copy even after erroneous operations are performed.


17.How to deactivate a validation for a particular user in production?

For deactivating for a particular user we will use hierarchy Custom Settings: A type of custom setting that uses a built-in hierarchical logic that lets us personalize settings for specific profiles or users.

18.What is external ID?


An external ID is a custom field that has the “External ID” attribute, meaning that it contains unique record identifiers from a system outside of Salesforce


19.What is the use of external Id?

1.It is mainly use for integration purpose. 

2.The field becomes searchable in the sidebar search.

3.We can use the upsert API call with the external ID to refer to records.

20.What is Unique ID?
Every Record, regardless of entity type, has a globally unique identification value in its ID field which is generated at the time of record creation. That Record ID value will never change, even if the record is deleted and then undeleted.

21.Why and How to Convert a 15-character Id to an 18-character Id?

We can convert 15 character IDs to 18 character IDs to update records, or to make it easier to work in systems that aren't case sensitive. Create a formula that will give you the 18-character Id of records.

22.What is custom login flows? 

Login flow is powerful solution for organization. Flow designer is a point-and-click tool that lets you automate business processes by building flows.   

Common uses cases includes
  • Collecting and updating user data at login
  • Configuring two-factor authentication
  • Integrating third-party strong authentication methods.
23.What is TOTP?

TOTP is time-based one-time password. We can use login flow that enhances TOTP authentication with a two-factor authentication method that Salesforce supports. The TOTP algorithm computes a one-time password from a shared secret key and the current time.

Users can use a time-based authentication application (such as Salesforce Authenticator or Google Authenticator) to scan the QR code and generate a TOTP token.

24.What is InvocableMethod Annotation?

This annotation lets us mark an Apex method as being something that can be called from somewhere other than Apex.

25.Can we call apex class from process builder?

Yes we can call an apex class from process builder. To call an Apex method, add the Call Apex action to your process and select an Apex class with a @invocable method Annotation. 

26.What are limitation of outbound messages?

We have outbound messages as one of the Actions for workflows.This works if other party implements the WSDL that is generated once Outbound messaging is defined with appropriate end point .

27.What is the best approach of making callout to external web services?

Future method invoked through triggers allowed to do apex callouts and invoke external web service provided the future method is annotated with @future(callout=true).This provides lot of flexibility and one of the best approaches .

28.Can we make callout directly from trigger?

No we cannot. Callout is a Asynchronous process where as Trigger is Dynamic / Synchronous. Callouts would hold up the database transaction until the callout completed, which can be up to 120 seconds from a limits perspective. This could cause significant contention with other transactions and impact performance. That means it is not directly possible to do a web service callout from a trigger. But using @Future annotation we can convert the Trigger into a Asynchronous Class and we can use a Callout method. 

29.What are setup objects?

Setup objects are those which interacts with metadata All other object (Standard and Custom) are non setup object.
30.What are use cases of future method?
  • Make a callout to external web services
  •  Avoid MIXED_DML_OPERATION exception 
31.What are the considerations while using future method?
  • Methods with the future annotation must be static 
  • It can only return void data type. 
  • The parameter must be primitive data types, arrays of primitive data types, or collections of primitive data types.
32.Difference between static and non static members of the class?

Static
Static means that it's a variable/method of a class which belongs to the whole class but not to one of its certain objects. This means that static keyword can be used only in a 'class scope'. We can access those members from outside the class also using the class name without instantiating a new instance of the class

Examples of static methods could be convert millimeters to centimeters, subtract two numbers, and convert String to uppercase

Non-static
Non-static method (and variables) must have a new instance of the class instantiated in order to be used.  Typically these rely on data inside the class that then is refered to inside the class.

Examples of non-static methods include 
lead convert, delete opportunity, and edit contact. 

33.What is the difference between keyword and literal?
Keyword- Reserved word having specific meaning. The words which have meaning already defined. We cannot use keyword to define variable. 

Literal - The name which we give. Like variable name.

34.Can we declare static variable inside method?

We can not declare variable as static inside a method. 

35.What are access modifiers in apex?

Apex allows you to use the privateprotectedpublic, and global access modifiers when defining methods and variables.
Private: The method or variable is accessible only within the Apex class in which it is defined. Note: By default all variables are private.
Protected: The method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class
Public: The method or variable can be used by any Apex in this application or namespace.
Global: The method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. 

36.What is Recursion ?

Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime.

37.How to avoid recursion?

To avoid the situation of recursive call, we have to write code in such a way that the trigger will execute one time. To do so, we can create a class with a static Boolean variable with default value true.

38.What is With sharing and without sharing?

With Sharing: It means "with Security Settings enforced".If you declare a class as a With Sharing, Sharing rules given to the current user will be taken into the consideration. This, pertains to only respecting OWDs and Sharing Rules.  We cannot "automatically" enforce field level security or profile permissions with "with sharing," 

Example
public with sharing class sharingClass

Without Sharing:If you declare a class as a Without Sharing, then this Apex class runs in system mode which means Apex code has access to all the objects and field irrespective of current users sharing rulesfield level security and Object permissions.

39.What will happen if SOQL query is written in for loop to access Custom Metadata Candidate Response?

 It will hit the governor limit.There is a governor limit that enforces a maximum number of SOQL queries.
When queries are placed inside a for loop, a query is executed on each iteration and governor limit is easily reached.
Wha
40.What is Order of execution?

When we save a record with an insertupdate, or upsert statement, Salesforce performs the following events in order.

1 – System Validation rule (SV) – Checks for the Required fields and field format like email should in the correct format.

2 – All Before Triggers are executed (BT) – Before trigger will execute and do the manipulation. 

3 – Custom Validation rules are checked (CV) – In this step, Custom validation run and check for the error

4 – Executes duplicate rules (DR) – All duplicate rule will execute for the Object if any

5 – After Triggers are executed (AT) 

6 – Assignment Rules are executed (AR)

7 – Auto-Response Rules are executed (ARR)

8 – Workflow Rules are executed (WR)

If workflow rule update any field then before and after triggers are executed one more time if the workflow rule updates a field (BT & AT)

9 – Process Builder (PB)

If process builder update any field then before and after triggers are executed one more time if the workflow rule updates a field (BT & AT)

10 – Escalation Rules are executed (ER)

11 – Parent Rollup Summary Formula or Cross Object Formula fields are updated in the respective objects. (RSF, COF and These parent records also goes through the entire execution order)

12 – Grand Parent Rollup Summary and Cross Object Formula Fields Calculation – ( GPRSF, GPCOF, and Grandparent also go through with the same process).

13 – Criteria Based Sharing rules are evaluated (CBS)

14 – Commits the data into Database!

15 – Any Post-Commit Logic is executed (PCL)  (like sending an email)

Note : The order of execution isn’t guaranteed when having multiple triggers for the same object due to the same event. For example, if you have two before insert triggers for Case, and a new Case record is inserted that fires the two triggers, the order in which these triggers fire isn’t guaranteed.

41.What is the difference between insert and database.insert?

Insert
  • Partial insert is not supported.
  • Roll back is not supported.
  • If we use the DML statement (Insert) in bulk operation, then if error occurs the execution will stop. In that case Apex code throws an error and none of the record will insert to the database.
Database.Insert
  • Database methods are static methods available in Database class.
  • Partial insert is supported.
  • Roll back is supported.
  • Includes the optional all or None parameters that defaults true.
  • If we use DML database methods (Database.Insert) in bulk operation, then if error occurs the remaining records will be inserted/updated means partial DML operation will be done. The only record throwing an error will not be inserted/updated.

Example: If we are inserting 10 records in an object, Where 5 records are correct and remaining 5 records are incorrect.

In DML statement (Insert) all the 10 records will be failed, because if one record is incorrect or error means all other remaining records will not be inserted. It will throw error.

In Database.insert 5 records will be inserted, remaining 5 records will be failed.(i.e. Partial DML Operation).
What is savepoint?

42.Can we use DML operation on before and trigger?

When we use before insert operation records are not committed to database.Here we dont need DML operations as whatever values we give in our code is automatically assigned to that record.
After Triggers, the record is already committed to the database hence we need an extra DML operation to reflect any changes. 
43.How can we monitor batch job?
We can monitor a Bulk API job in Salesforce. The monitoring page tracks jobs and batches created by any client application.

44.Examples of some Governer limits?

Total heap size6 MB/12 MB
Total number of DML statements issued150
Total number of records retrieved by a single SOSL query2000
Total number of SOSL queries issued20
Total number of records retrieved by Database.getQueryLocator10000
Total number of records retrieved by SOQL queries50000
45.Can we deactivate trigger in production?

We can do it using custom settings. We can create custom settings where we have checkbox field which will refer in the trigger and modify that record value to make it active or inactive.

46.When we can’t add Time-dependent action in Workflow rule in Salesforce?

You can’t add time-dependent actions to a rule if you choose Every time a record is created or edited.

47.What are the limitations of process builder?

  • It’s not possible to send outbound messages, as we do with Workflow Rules. This limitation can be overtaken by defining an apex class and recall it by setting Action Type “Apex”.
  • Each process can be associated with a single object only
  • We cannot Delete records
  • We cannot clone a record and it’s values
  • We cannot update unrelated records

48.What is difference between trigger and workflow?
Workflow
  • Workflow is automated process that fired an action based on Evaluation criteria and rule criteria.
  • We can access a workflow across the object.
  • We cannot perform DML operation on workflow
  • We cannot query from database
Trigger
  • Trigger is a piece of code that executes before or after a record is inserted or updated.
  • We can access the trigger across the object and related to that objects
  • We can use 20 DML operations in one trigger.
  • We can use 20 SOQL’s from data base in one trigger.
49.What is Difference between SOQL and SOSL?
SOQL(Salesforce Object Query Language)
  • Using SOQL we can Search only on one object at a time.
  • We can query on all fields of any datatype
  • We can use SOQL in Triggers and classes.
  • We can perform DML operation on query results.

SOSL(Salesforce object Search Language)
  • Using SOSL we can search on many objects at a time.
  • We can query only on fields whose data type is text,phone and Email.
  • We can use in classses but not in Triggers.
  • We cannot perform DML operation on search result
50.Explain what is Audit trail?
Audit trail function is helpful in knowing the information or track all the recent setup changes that the administration does to the organization.  It can store last 6 months data.

51.Difference between role and profile?

Profiles help to control object privileges such as CRED (Create, Read, Edit, Delete). They also contain system permissions that a user can carry out such as exporting data.


Roles help with sharing records across an organization. They work in a hierarchical fashion, giving users access to records that are owned by people lower down in the hierarchy. 

A user can only have a single Profile and Role assigned to them.
52. Difference between delete and hard delete?

Using Hard Delete your data will not be stored in the recycle bin. It will be permanently deleted.

Using Delete user can restore those datas lated within 15days from recycle bin

53. What are best practices of using trigger?


1) One Trigger Per Object
We should write single Apex Trigger per object. If we develop multiple Triggers for a single object, we have no way of controlling the order of execution if those Triggers can run in the same contexts.

2) Logic-less Triggers
If we write methods in our Triggers, those can’t be exposed for test purposes. We also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

54.What is apex design pattern?

Singleton:
Repeated execution of a class within a single transaction may lead to exceed the governor limit. This pattern is to reduce repeated instantiation of a class.
Strategy:
Strategy pattern is to provide different solutions for the same problem at runtime.
Decorator:
This pattern is used to provide the additional functionality to the sObject using Apex code.
Bulk State Transition:
 Implementing Bulk State transition ensure that the bulk action is performed based on the change of bulk record state.

55. How to use HTTP Callouts in batch class?

To use HTTP Callouts in batch class we need to use Database.allowcallouts in interface.



56. Difference between REST and SOAP API?
SOAP API:-
1)Supports data in the form of XML only 
2)Requires WSDL for the integration 
3)Use SOAP API in any language that supports Web services.
 
REST API :-
1)Supports both XML and JSON format
 2)Preferred for mobile and web apps since JSON being Lighter the app runs smoother and faster
You can also use Apex SOAP and REST Web services to expose data from platform or allow an external application to invoke Apex methods.


57. What is difference between 15 digit and 18 digit ID?

15 digit  is case sensitive. Example 100000000000ABC  is different from 100000000000abc. Internally, Salesforce uses a case-sensitive 15 digit ID for all records because everything is in control of salesforce  When using external productive tools like Microsoft Excel, MS Access and SQL Server external ID’s are not case sensitive and they don’t recognize the difference between 100000000000ABC  and 100000000000abc.

Salesforce.com has recognized this problem and Salesforce.com has established 18 digit character insensitive ID. This 18 Digit ID is case insensitive which is formed by adding a suffix to the 15 Character Id number. If user intend to use, load or manipulate records with an external program, for example, exporting data via reports or the API then use 18 digit ID

58.What is a platform event?

Platform events are part of Salesforce’s enterprise messaging platform. The platform provides an event-driven messaging architecture to enable apps to communicate inside and outside of Salesforce. Use platform events to deliver secure and scalable custom notifications within Salesforce or from external sources. 

Example: A user has salesforce and twitter account which are linked to each other. When a user change address in twitter, his address should also get changed in salesforce. For doing so we will use platform events to provide notification for changing the address. 

Publishing platform event: 
We can publish the platform events in 3 ways:
  1. Publish Events Messaging using APEX.
  2. Publish Events Messaging using Declarative tools (Process Builder or Cloud Flow Designer Tool / Visual Work flow).
  3. Publish Events Messaging using Salesforce API from external app.

59.What is difference between application and component event?
Component events are used to do communication between child and parent. They use bubbling and capture same as used in DOM events. A change in a child component can be communicated to the parent component via component event.
Application events are used to communicate any change in the component to a broader audience. Any component who has registered for this event will get a notified.
 The attribute type is the one that will differentiate Application event from Component event.
60.What are the best practices of using events?
Events Best Practices:
  1. Always try to use component events. Component event usage is more localized as these can be used by same component or component in containment hierarchy.
  2. If you use application events then it may fire system events.
  3. Use Application events only if components are present in 2 different app or are not in containment hierarchy.
61.What is the difference between visualforce and lightning?

Lightning
  • Lightning is single page application with multiple tabs inside it.
  • It is a Template based application. 
  • When component passes control to another component it is done using events or attributes
Visualforce
    • Visualforce is multiple page application
    • Visualforce page passes control to another page using page reference in apex controller

    62.Give a challenging scenario you faced and how you resolved it?

    Scenario
    When case is opened and it is not set to progress in two days then escalate to supervisor and if it is not closed in fivve days escalate to supervisor.Case is escalated based on closed date and cannot track progress.

    Solution
    Use time based workflow which will trigger email to the case owner

    63.What is list and hierarchical custom settings?

    List custom setting stores application data, visible to everybody. It can be reusable multiple times without using queries.

    Hierarchical custom settings are visible on the basis of role

    64.How to schedule a batch?

    Using schedule apex we can schedule a batch

    65.If batch is having 200 record and 1 record fails what will happen?

    If any record fails all 200 record will fail but next batch will get executed

    66.Difference between public group and queue?

    Queues are  used when you we  to assign a record to a bunch of users.With the help of queues we can assign a record to multiple users (using queues) so that any member of the queue can work on the record. It also allows the users to have there separate views. 
    It is used for load balancing
    It can be created for Custom objects and for Case, Lead and Knowledge Article Version

    Example:
    Real life Scenario

    There are many Customer Care Executive in a call centre and many customers call at a time and one executive can talk to one customer at one time,so other customer’s calls are kept in queues. Each user should assigned to at least one lead and same number of leads. 



    Same thing is there in salesforce :

    User need to handle assigned lead individually and all users in organization should assigned with same number of leads, in this case we can define users in organization as Queue and assign them one by one and in same number using round robin lead assignment.


    Public Group are team or group related user, used for a sharing data. They are not the owner of the records (like queue) but can share the records (in terms of access).

    Public group can be created across any object.

    67.A can see B data but B cannot see A data. Why?

    Check following conditions

    1 - Both users have same profile?
    2. Check Role Hierarchy of A and B.
    3. Check Sharing rule

    68.User A has the button CLONE visible on Accounts, User B can not see the button CLONE on Accounts. Why?

    Check following conditions
    1 - Both users have same profile?
    2 - There is no Custom Permission Set assigned to any user
    3 - Do you have record types for the Account Object and associated page layouts for those Record Types
    4 - You have checked the page layout and Clone button is added to the Page Layout.

    69.We have 2 users A and B under same profile and Role. How can we restrict records of A to B and Vise versa.?

    In profile set View all data and modify all date permission to 'false'. This will restric user to access data created by other users.

    70.How can we do field history tracking?

    WE can select certain fields to track and display the field history in the History related list of an object. Field history data is retained for up to 18 months through  the org.

    71.What is custom metadata?

    Custom metadata is customizable, deployable, packageable, and upgradeable application metadata. First, we create a custom metadata type, which defines the form of the application metadata. Then we build reusable functionality that determines the behavior based on metadata of that type. Similar to a custom object or custom setting, a custom metadata type has a list of custom fields that represent aspects of the metadata.

    72.What is relationship between account and contact?

    Lookup

    73. Relationship between account and opportunity?

    Master Detail

    74.There are 100 user. 90 user can read records, 10 users can update records?

    Create two profiles:
    First profile give read permission and add 90 users.
    Second profile give read and edit permission and add 10 users.

    75. What is the types of OWD?

    Private
    Public read only
    Public read and write
    Public read/write/transfer

    76. What is sharing rule?
    Sharing rule grants extra layer of access


    77. What are limitations of OWD model?
    OWD narrows down the access. Cannot open access

    78. There are five users  under one profile and only one user see all the data. Account is private.Why?

    Use sharing rule to grant extra level of permission to one user.

    79. What is difference between look up and master detail relationship?

    Master – Detail Relationship :
    1. If we delete master records then detail (Child) records are deleted.
    2. It creates the parent(master) child(Detail) relationship between objects.
    3. Child records do not have Owner fields it takes parents records owner as child records owner.
    4. We can have maximum 2 master details on an object
    Look up relationship :
    1. Look up relationship creates relations between two objects.
    2. If we delete any object then other object is not deleted.
    3. We can have maximum 25 lookup on an object


    80. How to convert lookup to master detail relationship?

    • We can convert a look up to master detail provided if our existing data look ups contain data for all records.
    • Also we should have "Allow reparenting' check box checked for that field otherwise we will find master detail disabled when we try to change the data type to master detail.
    81.What is standard controller, custom controller and extension?

    Standard controller:contain the same functionality and logic that are used for standard Salesforce pages.

    Custom controller:Custom controllers contain custom logic and data manipulation that can be used by a Visualforce page

    Custom extension: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.

    82. How to make HTTP request to external server?

    public class HttpCalloutSample {

      1. // Pass in the endpoint using the string url
      public String getCalloutResponseContents(String url) {

      2.  // Instantiate a new http object
        Http h = new Http();

       3.  // Instantiate a new HTTP request, specify the method and  endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');

       4. // Send the request, and return a response
        HttpResponse res = h.send(req);
        return res.getBody();
      }
    }


    83.How to test HTTP Callout ?


    Test HTTP Callouts by Implementing the HttpCalloutMock Interface


    @isTest global class MockHttpResponseGenerator implements HttpCalloutMock { 1. // Implement this interface method global HTTPResponse respond(HTTPRequest req) {
    2. // Optionally, only send a mock response for a specific endpoint // and method. System.assertEquals('http://example.com/', req.getEndpoint()); System.assertEquals('GET', req.getMethod()); 3. // Create a fake response HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"example":"test"}'); res.setStatusCode(200); return res; } }

    Test Class

    @isTest private class CalloutClassTest { @isTest static void testCallout() { 1. // Set mock callout class Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); 2. // Call method to test. // This causes a fake response to be sent 3. // from the class that implements HttpCalloutMock. HttpResponse res = CalloutClass.getInfoFromExternalService(); 4. // Verify response received contains fake values String contentType = res.getHeader('Content-Type'); System.assert(contentType == 'application/json'); String actualValue = res.getBody(); String expectedValue = '{"example":"test"}'; System.assertEquals(actualValue, expectedValue); System.assertEquals(200, res.getStatusCode()); } }

    84. How to Test HTTP Callouts Using Static Resources?

    Apex provides the built-in StaticResourceCalloutMock class that we can use to test callouts by specifying the response body in a static resource.

    @isTest
    private class CalloutStaticClassTest {
        @isTest static void testCalloutWithStaticResources() {
            // Use StaticResourceCalloutMock built-in class to
            // specify fake response and include response body 
            // in a static resource.
            StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
            mock.setStaticResource('mockResponse');
            mock.setStatusCode(200);
            mock.setHeader('Content-Type', 'application/json');
            
            // Set the mock callout mode
            Test.setMock(HttpCalloutMock.class, mock);
            
            // Call the method that performs the callout
            HTTPResponse res = CalloutStaticClass.getInfoFromExternalService(
                'http://example.com/example/test');
            
            // Verify response received contains values returned by
            // the mock response.
            // This is the content of the static resource.
            System.assertEquals('{"hah":"fooled you"}', res.getBody());
            System.assertEquals(200,res.getStatusCode());
            System.assertEquals('application/json', res.getHeader('Content-Type'));   
        }
    }

    85. How to perform DML Operations and Mock Callouts together?

    By default, we cannot use DML operation and callout in same transaction as DML operation prevents callouts from executing. However, we might want to insert test data in test method using DML before making a callout.

    To enable this, enclose the code that performs the callout within Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMockstatement. 

     Calls to DML operations must not be part of the Test.startTest/Test.stopTest block.


    @isTest
    private class CalloutClassTest {
         @isTest static void testCallout() {
            // Perform some DML to insert test data
            Account testAcct = new Account('Test Account');
            insert testAcct;

            // Call Test.startTest before performing callout but after setting test data.
            Test.startTest();

            // Set mock callout class 
            Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
            
            // Call method to test.
            // This causes a fake response to be sent
            // from the class that implements HttpCalloutMock. 
            HttpResponse res = CalloutClass.getInfoFromExternalService();
            
            // Verify response received contains fake values
            String contentType = res.getHeader('Content-Type');
            System.assert(contentType == 'application/json');
            String actualValue = res.getBody();
            String expectedValue = '{"example":"test"}';
            System.assertEquals(actualValue, expectedValue);
            System.assertEquals(200, res.getStatusCode());

            Test.stopTest();
        }
    }

    86. How to make Asynchronous Apex and Mock Callouts together?

    These asynchronous calls are enclosed within Test.startTest and Test.stopTest statements in test methodsBut if the asynchronous calls aren’t enclosed within Test.startTestand Test.stopTest statements, we will get an exception because of uncommitted work pending.

    Example
    Test.startTest();
    MyClass.asyncCall();
    Test.stopTest();
    Test.setMock(..); // Takes two arguments
    MyClass.mockCallout();

    87. What is the use of @RestResource?
    The @RestResource annotation is used at the class level and enables us to expose an Apex class as a REST resource.
    RestRequest and RestResponse objects are available by default in Apex methods through the static RestContext
    Methods annotated with @HttpGet or @HttpDelete should have no parameters. This is because GET and DELETE requests have no request body, so there's nothing to deserialize.
    Example
    @RestResource(urlMapping='/Account/*')
    global with sharing class MyRestResource {
        @HttpGet
        global static Account doGet() {
            RestRequest req = RestContext.request;
            RestResponse res = RestContext.response;
            String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
            Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
            return result;
        }
      @HttpPost
        global static String doPost(String name,
            String phone, String website) {
            Account account = new Account();
            account.Name = name;
            account.phone = phone;
            insert account;
            return account.Id;
        }
    }
    88.Does Apex Rest Web Services run in system mode?
    Invoking a custom Apex REST Web service method always uses system context. The current user's credentials are not used, and any user who has access to these methods can use their full power, regardless of permissions, field-level security, or sharing rules.

    89. What is apex transaction?
     All DML operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database.


    Example
     A custom Apex Web service method causes a trigger to fire, which calls a method in a class. In this case, all changes are committed to the database only after all operations in the transaction finish executing and don’t cause any errors.

    Use of Transaction
    Transferring funds from one bank account to another. It involves debiting the first account and crediting the second account with the amount to transfer. These two operations need to be committed together to the database. But if the debit operation succeeds and the credit operation fails, the account balances will be inconsistent.

    90. Provide some of the Governor Limit?

    Total number of SOQL queries issued- Synchronous Limit- 100 Asynchronous Limit -200
     
    Total number of records retrieved by SOQL queries 50,000
    Total number of records retrieved by Database.getQueryLocator 10,000
    Total number of SOSL queries issued 20
    Total number of records retrieved by a single SOSL query 2,000
    Total number of DML statements issued 150
    Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin 10,000
    Total number of callouts (HTTP requests or Web services calls) in a transaction 100
    Maximum number of methods with the future annotation allowed per Apex invocation 50
    Maximum number of Apex jobs added to the queue with System.enqueueJob 50
    Total number of sendEmail methods allowed 10
    Total heap size Synchronous Limit(6 MB)  Asynchronous Limit(12 MB)
    Maximum execution time for each Apex transaction 10 minutes

    91. What is dynamic SOQL?

    It is creating SOQL at run time. To create a dynamic SOQL query at run time, use the database query method
    Use Case
    Create a search based on input from an end user.

    Example
    String myTestString = 'TestName';
    List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString');

    92.What is Dynamic SOSL?

     Dynamic SOSL refers to the creation of a SOSL string at run time with Apex code. To create a dynamic SOSL query at run time, use the search query method


    Example
    List<List <sObject>> myQuery = search.query(SOSL_search_string);

    93. Is it possible to implement transactional DML for batches? 
    1. Create a savepoint
    2. do the whole batch (parent+child updates), and in the meanwhile maintain a Set of any parent record ids that either fail themselves or have failed children.
    3. Rollback that entire transaction to the savepoint

    94.How to handle error records in Batch apex?

    1. Make your batch class stateful using Database.Stateful so replace your first line with

    public class SimpleBatch implements Database.Batchable<sObject>,Database.Stateful{

    2.Create a global variable required which will maintain failed record.
    global List<String> exception_List;

    3.Use Database.update method instead of update with allOrNothing = false parameter which will return how many records has passed and failed in update call.
    Database.SaveResult[] SaveResultList = Database.update(objsToUpdate,false);   
    4.Iterate over saveResultList and add failed records in exception_list

     for(integer i =0; i<objsToUpdate.size();i++){
            String msg='';
            If(!SaveResultList[i].isSuccess()){
                    msg += userList.get(i).id + '\n'+'Error: "';        
                    for(Database.Error err: SaveResultList[i].getErrors()){  
                         msg += err.getmessage()+'"\n\n';
                    } 
            }
            if(msg!='')
                exception_List.add(msg);
         } 
    5. You can use this exception_list in execute method to send in your final email.

    95. What is SOQL injection?

    96. How to run batch apex in parallel mode?

    97. What is data migration?

    98. What is Enqueue action?
    Enqueue action is used in lightning javascript controllers to call server-side action.
    99. what is MVC and MVCC?
    Model :-  The Salesforce Data objects (Sobjects)
    View :-  Visual force markups and HTML tags
    Controller :- The apex code which driven the business logic's. 

    Lightning is a MVCC platform since it has two controllers which share the business logic.

    Model :-  The Salesforce Data objects (Sobjects) 
    View :-  Aura markups and HTML tags with SLDS
    Controller :- The JavaScript controller that communicate with View
    Controller :- The Apex controller that communicate with Model
    99. What is 101 SOQL error and how to resolve it?

    System.LimitException: Too many SOQL queries: 101 error

    Resolve the "Too many SOQL queries: 101" error

    To fix the issue, change your code so that the number of SOQL fired is less than 100.

    100. List exception in salesforce?
    ExceptionDescription
    AsyncExceptionAny problem with an asynchronous operation, such as failing to enqueue an asynchronous call.
    CalloutExceptionAny problem with a Web service operation, such as failing to make a callout to an external system.
    DmlExceptionAny problem with a DML statement, such as an insert statement missing a required field on a record.
    EmailExceptionAny problem with email, such as failure to deliver. For more information, see Outbound Email.
    ExternalObjectExceptionAny problem with external object records, such as connection timeouts during attempts to access the data that’s stored on external systems.
    InvalidParameterValueExceptionAn invalid parameter was supplied for a method or any problem with a URL used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer's Guide.
    LimitExceptionA governor limit has been exceeded. This exception can’t be caught.
    JSONExceptionAny problem with JSON serialization and deserialization operations. For more information, see the methods of System.JSONSystem.JSONParser, andSystem.JSONGenerator.
    ListExceptionAny problem with a list, such as attempting to access an index that is out of bounds.
    MathExceptionAny problem with a mathematical operation, such as dividing by zero.
    NoAccessExceptionAny problem with unauthorized access, such as trying to access an sObject that the current user does not have access to. This is generally used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer's Guide.
    NoDataFoundExceptionAny problem with data that does not exist, such as trying to access an sObject that has been deleted. This is generally used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer's Guide.
    NoSuchElementExceptionThis exception is thrown if you try to access items that are outside the bounds of a list. This exception is used by the Iterator next method. For example, ifiterator.hasNext() == false and you call iterator.next(), this exception is thrown. This exception is also used by the Apex Flex Queue methods and is thrown if you attempt to access a job at an invalid position in the flex queue.
    NullPointerExceptionAny problem with dereferencing null, such as in the following code:
    1String s;
    2s.toLowerCase(); // Since s is null, this call causes
    3                 // a NullPointerException
    QueryExceptionAny problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.
    RequiredFeatureMissingA Chatter feature is required for code that has been deployed to an organization that does not have Chatter enabled.
    SearchExceptionAny problem with SOSL queries executed with SOAP API search() call, for example, when the searchString parameter contains less than two characters. For more information, see the SOAP API Developer Guide.
    SecurityExceptionAny problem with static methods in the Crypto utility class. For more information, see Crypto Class.
    SerializationExceptionAny problem with the serialization of data. This is generally used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer's Guide.
    SObjectExceptionAny problem with sObject records, such as attempting to change a field in an update statement that can only be changed during insert.
    StringExceptionAny problem with Strings, such as a String that is exceeding your heap size.
    TypeExceptionAny problem with type conversions, such as attempting to convert the String 'a' to an Integer using the valueOf method.
    VisualforceExceptionAny problem with a Visualforce page. For more information on Visualforce, see the Visualforce Developer's Guide.
    XmlExceptionAny problem with the XmlStream classes, such as failing to read or write XML.
    Q,What is uncomitted work pending exception? 

    You have uncommitted work pending. Please commit or rollback before calling out' . It is System.CalloutException
    You need to perform Callout in the future method so your callout and DML will be in the different transaction
    This way you can resolve this issue
    create a list and serialize it to pass to the future method. Because we can't pas list of sobject as a parameter in the future method
    insert listofAccount;
    
    string jsonString = JSON.serializePretty(listofAccount );
    
    callout(jsonString);
    In future method make callout
    @future(callout = true)
    public static void callout(string jsonString){
        //do callout here rest or soap
    }


    References:
    https://blog.jeffdouglas.com/2010/05/07/using-exernal-id-fields-in-salesforce/

    http://www.salesforcefinessed.com/2017/10/why-should-you-care-about-external-ids.html

    https://www.biswajeetsamal.com/blog/salesforce-two-factor-authentication-using-login-flow/

    https://automationchampion.com/2015/07/09/getting-started-with-process-builder-part-33-call-an-apex-method-from-a-process/

    https://medium.com/devsys/apex-salesforce-how-to-make-a-callout-with-a-dml-operation-in-a-process-builder-34c168725dda

    https://salesforcelearningpoint.wordpress.com/2015/12/24/static-and-instance-in-apex-salesforce/

    Share this

    Related Posts

    Previous
    Next Post »