Apex Questions
Apex Questions
Apex Questions
Salesforce offers Data manipulation language (DML) with built in exception handling.
Salesforce Object Query Language (SOQL) and Salesforce Object Search language (SOSL) are used to
query and retrieve data.
Apex in Salesforce has built-in record-locking mechanism. This prevents record update conflicts.
Salesforce Apex programming language runs on multi-tenant Environment.
Apex code is stored in Metadata format.
It has syntax and variables similar to Java.
It provides unit testing and test execution with code coverage.
When we want to add web and Email services to your Application.
It is used to perform complex business processes.
When can add complex validation rules to your application.
Salesforce Apex can be used to add a custom logic on operations like saving a record.
1) Standard Navigation.
2) Developer Console.
3) Execute Anonymous Window:
4) Eclipse IDE.
Datatypes
1. Primitive Datatypes:
Integer, Long, string, Decimal, Double, Boolean, Date, DateTime, ID, Blob.
2. SObject Datatypes:
6. What is Class?
A class is a Physical entity / Blue print, which contains a collection of variables, functions, procedures,
properties, Constructors, etc.
Classes are used to achieve the Encapsulation feature of OOP.
Note:
Develope
User r Fil Ne Apex
Menu Console e w Class
7. What is Object?
In-order to assign and access the class members, we need a reference called as an "Object".
Which is an instance of the class.
Note:
8. What is Encapsulation?
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
Its Provides Security. Ex: Class
9. What is Polymorphism?
When one task is performed by different ways simply it’s called as polymorphism.
we use method overloading and method overriding to achieve polymorphism.
When one object acquires all the properties and behaviors of parent object known as inheritance. It
provides code reusability.
It is used to achieve runtime polymorphism.
A class which is inherited is known as Parent class, Base class or Super class.
A class which extends base class is known as Derived class or child class.
Keywords:
private
protected
public
global
3
If you make any variable as final, you cannot change the value of final variable (It will be constant). if the
Class declared as final it can't be inherited.
Final variables can only be assigned a value once, either when we declare a variable or in initialization
code
If the implementation is perfect and does not requires any further modification then make that method is
final.
The super keyword can be used by classes that are extended from virtual or abstract classes.
By using super, we can override constructors and methods from the parent class.
Only classes that are extending from virtual or abstract classes can use super.
You can only use super in methods that are designated with the override keyword.
The class is declared with keyword abstract and known as abstract class.
If we don't know the implementation of method now and can implemented latter then make that method
as abstract.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that
only have their signature declared and no body defined.
If you declare a class as with sharing, sharing rules given to the current user will be taken in to the consideration
and user can access and perform the operations based on the permissions given to him on objects to fields.
If you declare a class as without sharing, then this apex class runs in system mode which means apex code has
access to all the objects and fields irrespective of current user sharing rules, field level security and Object
permissions.
An interface is like a class in which none of the methods have been implemented the method signatures
are there, but the body of each method is empty.
To use an interface, another class must implement it by providing a body for all of the methods contained
in the interface.
Exception occurs during the execution of a program. We have to handle the excretion in code.
try: This keyword is used to identifies a block of code in which an exception can occur.
catch: This keyword is used to identifies a block of code that can handle a particular type of exception.
finally: This keyword is used to identifies a block of code that is guaranteed to execute.
throw: This keyword is used to throws an exception, signaling that an error has occurred.
In simple terms you can assume Synchronous as Sequential. In Synchronous process the thread waits for
the task to be completed and then moves to the next task Sequentially. All the tasks are completed in a
single thread.
The common example of a Synchronous apex is Trigger.
In Asynchronous apex the thread does not waits for the task to be completed to move on to the next task.
The tasks are run in different threads all together. These threads run in independent silos whenever the
system is free.
Most common example is the Future annotation.
This will take the value from the visual force page and stores to the Apex variable name.
This method will return a value to a visual force page whenever a name variable is called.
Constructor in Apex Programming is a code and is a special method that is invoked when an object is created from
the class. Constructor has the following properties.
List is Ordered.
List allows duplicates.
We can access list elements with index.
We can sort list elements with sort method (default sorting order is ascending).
Contains method is not available in List.
We can process records which are stored in list using DML statements (insert, update, delete and
undelete).
List Methods:
1) Add (<Element Name>): This method is used to add an element to the collection.
2) AddAll (<From List>): This method will add all the element from the specified collection.
3) Add (Integer IndexPositin, <elementName> ): This method will insert the element at the
specified index position in the collection.
4) Integer Size(): It returns an integer, which indicates the Number of elements exist in the collection.
5) Boolean isEmpty(): This method is used to verify the collection is empty or not.It returns TRUE,
when the collection is empty. Else it returns FALSE.
6) Get(<IndexPosition>): This method is used to get the elements from the collection, based on the
index position.
7) Equals(<ListCollection>): This method is used to compare the two collections. And it returns TRUE,
when both the collections are Same.Else it returns FALSE.
8) Remove (IndexNumber): By using this method, we can remove the element from the collection
exist at the specified index position.
9) Clear (): This method will remove all the elements from the collection.
10) Set (indexposition, <NewValue>): By using this method, we can update the element name with a
new value, which is exist in the specified position.
11) SObjectType(): It returns the Datatype of the collection.
Set is unordered.
Set doesn't allow duplicates
Set elements cannot be accessed with index.
sort method is not available for Set.
Contains method is available for Set to search for a particular element in the set.
We cannot process records which are stored in set using DML statements.
List Methods:
Map Methods:
By using DML statements, we can perform the operations on the salesforce object records.
DML operations can be used for both Standard and custom objects.
By using DML statements, we can perform the operation on either one or more records.
1) Insert
2) Update
3) Delete
4) Undelete
5) Upsert (Combination of insert and update)
6) Merge (Combination of update and delete)
By using this statement, we can insert one or more records into the object.
This statement is used to modify the data that is already commited in the database.
To update we need 'ID' of the record
By using this statement, we can remove either one or more records from the object.
Note: To remove the record, record Id is enough.
Deleted records will be stored in recyclebin till 15 days.
This statement is used to get the deleted records(from Recyclebin) back to the actual object.
Note:
1. The records, which are having the Id's will be updated into the Database.
2. The records, which are not having the Id's will be inserted into the object.
7
Salesforce Object Query Language is used to query that records from the database.com based on the requirement.
1. Static SOQL
2. Dynamic SOQL
Static SOQL:
Dynamic SOQL:
It is used to refer to the creation of a SOQL string at run time with Apex code.
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT
OFFSET
ALL ROWS
FOR UPDATE.
8
Best Practice’s
1. We can call the SOSL Queries from all the apex classes.
2. It is recommended, to avoid the usage the SOSL queries inside the "Triggers".
3. SOSL Query will search the content in All Text fields, Email Fields and Phone Fields.
Large amount of data divided in to no of batches. every batch processed separately is called batch apex
By using Batch apex, we can perform the DML operations on the bulk records at a time.
Batch Apex allows us to process max. of 50 million records.
Batch apex jobs will executed out side of the Salesforce organization by using the Salesforce resources.
Note: All Batch Apex classes should be defined with the Access specifier "Global".
To implement the batch process, we need to use an interface called as Database.Batchable<SObject>".
start method and finish method executes only one time. but execute method executes multiple times.
per every execute method have fresh governor limits
1) start method
2) execute method
3) finish method
Start method
It will prepare the records to process and execute only one time.
Execute method
It will take the records prepared in start method and split those records into batches and it will execute
multiple times.
For example if the start method is returning 1000 records then execute method executes 5 times if you
don't mention the batch size (Default Batch Size is: 200).
Maximum batch size is: 2000.
Finish method
We can perform post commit logic like sending emails with the success or error information. It will execute only
one time.
database.allowcallouts=true
The class that implements this interface can be executed as a batch Apex job.
If we use a Database.QueryLocator, the governor limit for the total number of records retrieved by SOQL queries
is bypassed. (Default 50,000 It allow up to 50 million records).
If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries is still
enforced.
Yes you can call a batch apex from another batch apex .Either in start method or in finish method you can call
other batch
Asynchronous operations.
56. What is the maximum size of the batch and minimum size of the batch ?
BatchableContext Interface is Represents the parameter type of a batch job method and contains the
batch job ID.
This interface is implemented internally by Apex.
58. How to track the details of the current running Batch using BatchableContext?
You can check the AsyncApexJob.Status using the JobId from the Database.BatchableContext.
For each 10,000 AsyncApexJob records, Apex creates one additional AsyncApexJob record of type
BatchApexWorker for internal use.
63.What is Database.AllowCallouts?
To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition.
Email New
Setu Buil Develo Email
p d p Servic
es Services
65. what is email service in salesforce?
the email services are automated process that use apex classes to process the contents, headers and
attachments of inbound email
example: we can create an email services that automatically creates a contact records based on contact
information message
if we want to send an email from salesforce to external system using outbound message we can send.
if we received any email from external system to salesforce then we call it as inbound email.
11
two types
single email message we can send message related to only single record
the single email message contains the methods and classes that are required to send an email these are
defined messaging.singleemailmessage==name space
SetBccAddresses(bccAddresses)
This method will set Bcc Address to the whom the email should be sent. We can set up to 25 email
addresses.
setCcAddresses(ccAddresses)
This method will set CcAddress to whom the mail should be sent. We can set utp 25 email address.
setToaddress()
This method will set the address, we can set up to 100 addresses.
setSubject(string)
setPlainTextBody()
setHtmlBody(htmlBody)
2. MassEmailMessage :
Through MassEmailMessage we can send a mass email messages to a recipient list that consists of
contacts, Leads, Person accounts or users you can view in Salesforce.
when we want to send a different email template to different set of recipients we use mass email message
we can up to 250 emails
Messaging.MassEmailMessage
Messaging.MassEmailMessage class all the methods defined in the Email class and also Email base class methods.
if you want to receive a email from external system to salesforce we use inbound email message based on
the details or information available in the message we can create account, contact, case
if we want to acheive the concept of inbound email that class has implemented an interface called
messaging.inboundemailresult
messaging.inboundemailresult
this method contains the datamember called success information,whose value is set to true if the
email handled properly
messaging.inboundemail
this class contains the properties of the email which is received as in bound from name,from
adress,subject,plaintextbody etc
12
messaging.inboundenvelope
this class contains to and from address of the inbound email which is received
messaging.inboundemailhandler
Messaging.InboundEmailResult :
Messaging.InboundEmail:
This is a predefined Apex class which contains the values of email what we recevied as inbound
1. fromAddress
2. fromName
3. toAddress
4. subject
5. plainTextBody
Messaging.InboundEnvelope
This is a predefine Apex class which contains to and from address of the inbound email.
13
Develope
r File Ne Apex Write
menu w classes code
Console
3. By using "Eclipse IDE
o go to "File" menu.
o Click on "New" menu item.
o Click on "Apex Classes" from "Submenu".
o Enter the "Apex Test Class Name" in the Text box, provided by the Dialog box.
o Write the "Test Class Code" and Save the code by using "CTRL + S".
o Click on Run Test Button.
Before Knowing how to write Test Classes in Apex Salesforce we should know why we write Test Classes.
We write Test Classes In Apex Salesforce for Unit Testing.
We get to find the bugs in our code and fix it to give better output. Testing gives the Code Coverage.
After developing an apex class or apex trigger we should write the unit tests(Test Class) and ensure that
we are able to execute at least 75% of the lines of code.
If you are moving the code from sandbox to sandbox then code coverage is not required.
If you are moving the code from sandbox to production at-least 75% code coverage is required.
IF the code coverage is less than 75% deployment will fail.
You have to start your class with @isTest annotation, then only Salesforce will consider this class as test
class.
Keep your class as Private, and the best practice is to name your test class as your original Class or trigger
Name + ‘Test’.
Syntax:
1. @isTest
2. private class MyTestClass {
3. @isTest
4. static void myTest1() {
5. }
6. static testMethod void myTest2() {
7. }
8. }
14
1. 75% of Apex statements must be executed (strive for 100% code coverage)
2. All Apex triggers must be called.
3. All Apex tests must execute without throwing any uncaught exceptions or exceeding governors
Verify that when passed valid inputs, called code completes without throwing an exception.
System.assert()
System.assertEquals()
System.assertNotEquals()
Verify that when passed invalid inputs, exceptions are properly handled
Step 4: Governors
By default test class cannot recognize the existing data in the database.
if you mention @isTest(seeAllData = true) then test class can recognize the existing data in the database.
If possible Don’t use seeAllData=true, Create your Own Test Data.
StartTest and StopTest are standard test methods which are available for test classes
Test.startTest() and Test.stopTest() maintains fresh set of governor limits. [ These methods help you to
reset your governor limits ]
Per testMethod we can use Test.startTest() and Test.stopTest() only for one time.
To execute asynchronous methods synchronously we can call those methods from inside of
Test.startTest() and Test.stopTest().
Once your test code runs between Test.startTest() and Test.stopTest(), you must use assert statements to
test whether your actual code is executing correctly and giving the results as expected.
15
System.assertEquals(val1,val2)
If both val1 and val2 are same then test class run successfully otherwise test class will fail.
System.assertNotEquals(val1,val2)
If both val1 and val2 are not same then test class run successfully otherwise test class will fail.
System.assertEquals(val1> val2)
If the condition satisfied then test class run successfully otherwise test class will fail.
private variables and methods in apex class we can include @TestVisible so that even though variable is private
we can access from the test class.
16
Trigger is piece of code that is executes before and after a record is Inserted/Updated/Deleted from the force.com
database.
Trigger is a Custom Business logic to perform the operations on one or more records upon DML Events.
Triggers will get fired automatically based on the DML operations performed on the object.
Trigger can be fired "Before" or "After" performing the operation.
By using Triggers, we can perform complex validation rules and Transactional flows.
Triggers are "Asynchronous" operations.
By using Triggers, we can perform all DML manipulations on either one or more object records.
Triggers will get fired based on the Events [ before insert, after insert, before update, after update, before
delete, after delete, after undelete]
1) Before Triggers.
2) After Triggers.
1 . Before Triggers?
These triggers are fired before the data is saved into the database.
2 . After Triggers?
These triggers are fired after the data is saved into the database.
We can execute the complex business logics and Complex validation rules before inserrting the record into
the object, which can be fired based on "Before Insert" event.
By using this event, we can fire the actions which contains the business logic to be performed after
inserting a new record.
By using this event, we can invoke the actions which performs certain operations before updating the
record.
By using this event, we can invoke the actions which performs the operations after updating the records.
By using this event, we can fire the actions which perform the operations before removing the records
from the object.
By using this event, we can fire the actions which perform the operations after deleting the records from
the object.
By using this event, we can fire the actions to be performed after re-storing the records back to the
object.
Syntax:
Note:
By using Trigger Context variables, we can get the current state of the triggers. (To capture the runtime
information, we use trigger context variables)
Trigger.isInsert: Returns true if the trigger was fired due to insert operation.
Trigger.isUpdate: Returns true if the trigger was fired due to update operation.
Trigger.isDelete: Returns true if the trigger was fired due to delete operation.
Trigger.isBefore: Returns true if the trigger was fired before record is saved.
Trigger.isAfter: Returns true if the trigger was fired after record is saved.
Trigger.New: Returns a list of new version of sObject records.
Trigger.Old: Returns a list of old version of sObject records.
Trigger.NewMap: Returns a map of new version of sObject records. (map is stored in the form of map)
Trigger.OldMap: Returns a map of old version of sObject records. (map is stored in the form of map)
Trigger.Size: Returns a integer (total number of records invoked due to trigger invocation for the both old
and new)
Trigger.isExecuting: Returns true if the current apex code is a trigger.
19
yes we can. It is same as usual class method calling from trigger. The only difference being the method
should always be asynchronous with @future
Recursion occurs in trigger if your trigger has a same DML statement and the same dml condition is used
in trigger firing condition on the same object(on which trigger has been written)
By default every trigger is a bulk trigger which is used to process the multiple records at a time as a batch.
For each batch of 200 records.
Using @Future annotation we can convert the Trigger into a Asynchrinous Class and we can use a Callout
method.
Use a static variable in an Apex class to avoid an infinite loop. Static variables are local to the context of a
Web request.
We can write more than one trigger But it is not recommended .Best practice is One trigger On One object.
A batch apex can be called from a class as well as from trigger code.
Database.executeBacth(bh);
There are many things which can contribute to the data loss in Salesforce. Which includes
Migrating to number, per cent, and money, from other data types.
When you change the date and time
Migrating to multi-select picklist from any other type but except picklist.
Moving from Checkbox, auto number, multi-select picklist to any other types.
Changing text area to phone, URL, email, or text.