Apex (1-18)
Apex (1-18)
Introduction to
Apex
kshitijdhoble
Overview of Apex
● Apex is a strongly typed, object-oriented programming
language, similar to Java and runs on Force.com Platform.
● It is used by developers to execute flow and transaction
control statements on the Salesforce platform.
● It allows developers to add business logic to most system
events, including button clicks, related record updates, and
Visualforce pages.
● Apex offers more advanced automation capabilities and
enables extensive customization like creation of triggers,
data manipulation, and integration with other systems.
kshitijdhoble
Use Cases
● Custom Business Logic: Automate complex business
processes.
● Data Manipulation: Perform operations on Salesforce data
(insert, update, delete).
● Integration: Connect Salesforce with external systems.
● Custom Web Services: Create custom SOAP and REST
web services.
kshitijdhoble
Benefits
● Seamless Integration: Built natively on the Salesforce
platform, ensuring smooth integration with Salesforce
data and features.
● Scalability: Designed to handle large volumes of data and
complex processes.
● Security: Enforces Salesforce's robust security model.
● Efficiency: Reduces the need for point-and-click
automation by allowing advanced customizations.
kshitijdhoble
Basic Syntax & Structure
Apex Class Structure: An Apex Class is the blueprint for
creating Objects. It contains Properties, Methods, &
Constructors. Here’s a basic example:
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 02
Data Types & Variables
in
Apex
kshitijdhoble
Variables in Apex
● A Variable is name of memory location used to store data
kshitijdhoble
Rules to Declare Variables
● A Variable Name must begin with an Alphabet not with
number and special characters.
● Special characters and spaces are not allowed while
declaring variables, excluding Underscore (_).
● We can’t use Reserved Apex Keywords to declare variables.
Valid ✅ Invalid ❌
Integer i3; String _ia; String str_;
String i_5; String i 2; String i$5;
String $a2; String $_s_4;
kshitijdhoble
Constants in Apex
● In Apex, a Constant is a variable whose value is fixed and
cannot be changed once it is assigned.
● Constants are declared using the keyword “final”.
● Often used to define values that should remain consistent
and immutable, such as configuration settings, fixed values
for calculations, or any value that should not change
during runtime.
● Constants are often declared as “static” because they are
shared across all instances of the class.
kshitijdhoble
Constants in Apex
● In the MathConstants example:
○ static: The constants belong to the class, not instances.
○ final: The values are immutable and cannot be changed.
○ So, PI and MAX_STUDENTS are fixed values that can be
accessed via the class name and cannot be altered
kshitijdhoble
Data Types in Apex
● In Apex, data types define the kind of data a variable can
hold.
● Apex is a strongly typed language, meaning you must
declare the type of data a variable will store.
● There are some major data types in Apex:
○ Primitive Types
○ Collections Types
○ Salesforce Specific Types
○ Special Types
○ Custom Types
kshitijdhoble
Primitive Data Types
● Integer
○ Represents 32-bit whole numbers (both positive and
negative) without decimal places (…-3, -2, -1, 0, 1, 2, 3…).
○ Size: 4 bytes. Range: -2147483647 to 2147483647
○ Example: Integer num = 100; Integer x = -25;
● Long
○ Represents a 64-bit integer, useful for handling large
range of numbers .
○ Size: 8 bytes. Range: −263 to 263-1
○ Example: Long largeNum = 1234567890123L;
kshitijdhoble
Primitive Data Types
● Double
○ Represents 64-bit floating-point numbers, which can
contain decimal points.
○ Size: 8 bytes. Range: Approx. ±1.7E-308 to ±1.7E+308.
○ Example: Double price = 99.99;
● Decimal
○ Represents a 64-bit integer, useful for handling large
range of numbers .
○ Size: Variable, with fix precision. Range: Can handle
large & small numbers but with fixed precision.
○ Example: Decimal salary = 12345678.90;
kshitijdhoble
Primitive Data Types
● String
○ Represents a sequence of characters enclosed with
single quotes ( ‘ ‘ ).
○ Size: Variable, depends on the length of the string
○ Example: String name = ‘Kshitij Dhoble’;
● Boolean
○ Represents a true or false value .
○ Size: 1 byte.
○ Example: Boolean isActive = true;
Boolean isCompleted = false;
kshitijdhoble
Primitive Data Types
● Date
○ Represents a calendar date without time.
○ Size: 8 bytes.
○ Example: Date today = Date.today();
● Time
○ Represents a specific time of the day without a date.
○ Size: 8 bytes.
○ Example: Time currentTime = Time.now();
● DateTime
○ Represents a specific date and time.
○ Size: 8 bytes.
○ Example: DateTime now = DateTime.now();
kshitijdhoble
Collection Data Type
● List
○ Represents an ordered collection of elements, which
can be of any data type like primitive, user-defined
objects, sObjects, or other collections.
○ Data is stored in sequence and are case-insensitive.
○ We can store duplicate data in a list.
○ Example:
kshitijdhoble
Collection Data Type
● Set
○ Represents a collection of unique elements, useful for
eliminating duplicates. It can store primitive data
types, sObjects, or user-defined objects.
○ Sequence of data is not followed and are
case-sensitive.
○ We cannot store duplicate data in a set.
○ Example:
kshitijdhoble
Collection Data Type
● Map
○ Represents a collection of key-value pairs, where each
key is unique.
○ Data is stored in key-value pair and are case-sensitive.
○ In Map, Value can be duplicate but Key should be
unique.
○ Example:
kshitijdhoble
Salesforce Specific Types
● ID
○ Represents Salesforce record IDs, which are 15-character
or 18-character unique identifiers.
○ This is system generated and can’t be edited/deleted.
○ 15 Digit IDs (0066A000004rMoL) are case-sensitive.
Salesforce uses it internally to maintain database, also
visible in the UI.
○ 18 Digit IDs (0066A000004rMoLIA0) are case-insensitive.
The last 3 characters are the checksum of the
capitalization of 1st 15 characters. It is returned by API
Calls. Meanwhile, the API will accept 15 digit ID but
always returns 18 digit ID.
kshitijdhoble
Salesforce Specific Types
● First 3 characters of an ID denotes the object type. These
prefixes never change for objects. And we can’t predict the
prefix of custom object, it’s based on internal SFDC rules.
● These are some prefixes of standard objects:
Objects Prefixes
Account 001
Contact 003
Leads 00Q
kshitijdhoble
Salesforce Specific Types
● sObject
○ A special data type used to work with Salesforce
records. It represents a generic Salesforce object.
○ Fields can be accessed dynamically using get and put
methods. Here’s an example:
kshitijdhoble
Special Types
● Null
○ Represents a state where a variable has no value
assigned to it.
○ We can assign null to any variable (primitive or
non-primitive) to indicate that it has no value
○ Example:
Integer number = null;
kshitijdhoble
Special Types
● Blob
○ Represents raw binary data, allowing you to work with data
that is not text-based.
○ Typically used for file handling, such as storing
attachments, images, or any binary files.
○ The maximum size of a Blob can be up to 6 MB per
operation in Salesforce.
○ Example:
kshitijdhoble
Special Types
● Object
○ It’s a base class for all data types, which means it can
hold any type of value, including primitive data types,
collections, sObjects, and custom objects, but while
retrieving, we need to cast it back to original type.
○ Example:
kshitijdhoble
Custom Types
● Enum
○ Defines a set of named constants. Useful for representing a
collection of related constants.
○ Used to represent fixed state of status, values, categories,
and types.
○ It provide type safety restricts the value that variable can
take, reducing the risk of invalid values.
○ Example:
‘COMPLETED’ };
kshitijdhoble
Custom Types
● User-defined Classes
○ Classes that we define to create custom data types
with specific attributes and methods.
○ Example: defining and using the class below.
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 03
Type Conversion, Operators &
Logic Control Statements in
Apex
kshitijdhoble
Type Conversion
● Type conversion is the process of converting a value from
type to another.
kshitijdhoble
Implicit Type Conversion
● Implicit conversion occurs automatically when you assign
kshitijdhoble
Explicit Type Conversion
● Explicit conversion, or casting, requires a developer to
● Example:
Double d = 20;
Integer num = (Integer)d;
// Explicit Conversion Double to Integer
System.debug(num); // Output: 10
kshitijdhoble
Explicit Conversions (Casting)
● The .valueOf() is an explicit conversion method in
kshitijdhoble
Integer Type Conversions
● Integer Conversions
kshitijdhoble
Long Type Conversions
● Long Conversions
kshitijdhoble
Double Type Conversions
● Double Conversions
kshitijdhoble
Decimal Type Conversions
● Decimal Conversions
kshitijdhoble
String Type Conversions
● String Conversions
kshitijdhoble
String Type Conversions
● String Conversions
kshitijdhoble
Boolean Type Conversions
● Boolean Conversions
kshitijdhoble
Date Type Conversions
● Date Conversions
kshitijdhoble
DateTime Type Conversions
● DateTime Conversions
DateTime dt = DateTime.now();
String str = String.valueOf(dt);
// "2023-01-01 12:00:00"
Date date = dt.date(); // August 3, 2024
kshitijdhoble
Handling Null Values
● When converting types, always handle null values to
kshitijdhoble
Note
● IDs can always be assigned to Strings.
exception thrown.
ID or not.
kshitijdhoble
Operators in Apex
● These operators provide a wide range of functionalities in
○ Arithmetic Operators
○ Comparison Operators
○ Logical Operators
○ Bitwise Operators
○ Assignment Operators
kshitijdhoble
Arithmetic Operators
Operator Details Example
Addition ( + ): Adds two operands. Integer sum = 5 + 3; // 8
kshitijdhoble
Comparison Operators
Operator Details Example
kshitijdhoble
Comparison Operators
Operator Details Example
kshitijdhoble
Logical Operators
Operator Details Example
Logical OR ( || ): Returns
true if at least one of the Boolean result = (5 > 3) || (5 < 2); // true
operands is true.
kshitijdhoble
Bitwise Operators
Operator Details Example
Bitwise AND ( & ): Performs a bitwise
Integer result = 5 & 3; // 1
AND operation.
kshitijdhoble
Assignment Operators
Operator Details Example
Assignment ( = ): Assigns the right-hand
Integer a = 5; // a = 5
operand to the left-hand operand.
kshitijdhoble
Assignment Operators
Operator Details Example
Multiplication assignment ( *= ): Multiplies
the left-hand operand by the right-hand
Integer a = 5; a *= 3; // 15
operand and assigns the result to the
left-hand operand.
kshitijdhoble
Miscellaneous Operators
Operator Details Example
kshitijdhoble
Logic Control Statements
● Control Flow & Loop Statements determine the flow of
execution in your code based on conditions or repeated
execution.
● Common Control Flow Statements in Apex include:
○ If - else
○ switch
● And various types of Loops include:
○ while
○ do - while
○ for
○ for - each
kshitijdhoble
if Statements
● The if-else statement executes a block of code based on
whether a condition is true or false.
● Basic if Statement example:
kshitijdhoble
if - else Statements
● if - else Statement example:
Integer num = 3;
if (num > 5) {
System.debug('Number is greater than 5');
} else {
System.debug('Number is 5 or less');
} // Output: Number is 5 or less
kshitijdhoble
If - else if - else Statements
● if - else if - else Statement example:
Integer num = 5;
if (num > 5) {
System.debug('Number is greater than 5');
} else if (num == 5) {
System.debug('Number is 5');
} else {
System.debug('Number is less than 5');
} // Output: Number is 5
kshitijdhoble
Shorthand if Statements
● The ternary operator is a concise way to perform an if-else
check in a single line.
Integer num = 4;
String result =
(num > 5) ? 'Greater than 5' : '5 or less';
System.debug(result);
// Output: 5 or less
kshitijdhoble
Switch Statements
● It tests a variable against a list of values, each with its own
block of code. Here’s an example:
kshitijdhoble
While Loop
● The while loop continues to execute a block of code as
long as a specified condition is true. Here’s an example:
kshitijdhoble
Do - While Loop
● The do-while loop is similar to the while loop but ensures
the block of code executes at least once before checking
the condition.
Integer i = 0;
do {
System.debug('i: ' + i);
i++;
} while (i < 5);
// Output: i: 0, i: 1, i: 2, i: 3, i: 4
kshitijdhoble
For Loop
● for loop allows you to execute a block of code repeatedly
based on a given condition. It consists of three parts:
○ Initialization: This is where you initialize a counter
variable, usually a number. This part is executed once
at the beginning of the loop.
○ Condition: The loop continues to execute as long as
this condition is true. It is checked before each
iteration.
○ Increment/Decrement: This part updates the counter
variable after each iteration. It usually increments or
decrements the counter.
kshitijdhoble
For Loop
● Example:
kshitijdhoble
For Loop
● You can also use a for loop to iterate over collections like
lists or sets in Apex. Here’s an example:
List<String> fruits = new List<String>{'Apple',
'Banana', 'Cherry'};
for (Integer i = 0; i < fruits.size(); i++) {
System.debug(fruits[i]);
} // Apple Banana Cherry
● Explanation:
○ Initialization: Integer i = 0 sets the starting index to 0.
○ Condition: i < fruits.size() ensures the loop runs until i is less
than the size of the list.
○ Increment: i++ increases the index by 1 after each iteration.
kshitijdhoble
For each Loop
● The for each loop in Apex is used to iterate over collections
such as lists, sets, or maps. It provides a clean and concise
way to iterate through elements without needing to
manage index variables manually.
● Basic Syntax:
kshitijdhoble
For each Loop
● Example with collection:
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 04
Keywords, Classes/Objects
& Constructors in
Apex
kshitijdhoble
Reserved Keywords in Apex
● Reserved keywords are special words predefined by the
syntax.
kshitijdhoble
Reserved Keywords
Usage Keywords
Control Flow if, else, switch, case, default, break, continue, do, while, for
kshitijdhoble
Reserved Keywords
Usage Keywords
SOQL Queries select, from, where, order by, group by, having, limit, offset
System Methods system, type, void, super, this, return, trigger, testmethod
kshitijdhoble
Note
● Remember that some keywords, like after, before, count,
identifiers.
kshitijdhoble
Access Modifiers
● An Access Modifiers are keywords used to define the
kshitijdhoble
Access Modifiers
● private: Accessible only within the class it is defined.
organization.
organization.
kshitijdhoble
Access Modifiers
● global: Accessible by any class in any Salesforce
kshitijdhoble
Access Modifiers
● transient: Prevents variables from being saved during
remains unchanged.
kshitijdhoble
Access Modifiers
● abstract: Declares a class that cannot be instantiated on
implemented by subclasses.
kshitijdhoble
Defining Classes
● A Class is a blueprint for creating objects. It defines
and inner classes that the objects created from the class
will have and can also used to define custom data types.
kshitijdhoble
Defining Classes
● Here’s a quick example:
kshitijdhoble
Defining Objects
● Here’s a quick example:
kshitijdhoble
Constructors
● Constructor in Apex are special methods that are called
○ Default Constructors
○ Parameterized Constructors
kshitijdhoble
Default Constructors
● A default constructor is a constructor that takes no
arguments.
constructors
kshitijdhoble
Default Constructors
● Default Constructor Example:
kshitijdhoble
Parameterized Constructors
● it’s a constructor that accepts arguments to initialize the
to their requirements.
kshitijdhoble
Constructor Overloading
● A class can have multiple constructors, each with a
overloading.
the requirements.
the requirements.
kshitijdhoble
Constructor Overloading
● Constructor Overloading example:
public class MyClass{
public String name;
public Integer age;
public MyClass(){ // default constructor
this.name = “Default”;
this.age = 0;
} // parameterized constructor
public MyClass(String name, Integer age){
this.name = name;
this.age = age;
}displayInfo() {
System.debug(“Name: “ + name “, Age: “ + age);
}
}
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 05
Methods: Parameters &
Return Types in
Apex
kshitijdhoble
Defining Methods
● A Method is a block of code designed to perform a
particular task.
within a class.
result.
kshitijdhoble
Defining Methods
● Here’s the basic syntax:
public [static] returnType methodName(parameterList){
// method body
// code to be executed/business logic
}
● Access Modifiers: public, private, protected, global
○ public methods are accessible by any Apex code.
○ private methods are accessible within the class.
○ protected methods are accessible within the class and
by the classes that extends the class.
○ global methods are accessible by any Apex code
anywhere.
kshitijdhoble
Defining Methods
● static methods belongs to the class itself, can be called
static method.
camelCase convention.
parameters.
kshitijdhoble
Defining Methods
● Here’s an example how methods defined:
public class MyClass{
// Method with no return value and no parameters
public void sayHello() {
System.debug('Hello, Apex!');
}
kshitijdhoble
Invoking Methods
● To call a method, we use the method name followed by
parentheses.
directly.
kshitijdhoble
Invoking Methods
● Here’s an example (invoking methods of previous example):
public class TestMethods {
public static void test() {
// Creating an instance of the class
MyClass example = new MyClass();
● Parameter Types:
return.
processData.
kshitijdhoble
Best Practices
● Overloading Methods: Use method overloading to provide
parameter lists.
● Here’s an example:
kshitijdhoble
Best Practices
● Avoid Hardcoding: Use constants or configuration objects
Double discountedPrice =
originalPrice * (1 - DISCOUNT_RATE);
kshitijdhoble
Best Practices
● Parameter Validation: Validate method parameters to
● Here’s an example:
public void setAge(Integer age) {
kshitijdhoble
Day 06
Deep Dive into Collections,
Exception Handling in
Apex
kshitijdhoble
Deep Dive into Collections
● On 2nd Day of learning Apex Programming, we have gone
○ List
○ Set
○ Map
collections.
kshitijdhoble
How to Initialize List
● Basic syntax:
kshitijdhoble
List Methods
Methods Purpose
kshitijdhoble
List Methods
Methods Purpose
contains( element ) Returns true if the list contains the specified element.
kshitijdhoble
List Method Example
// declaring List
List<String> names = new List<String>();
// adding elements
names.add(“Kshitij”); names.add(“Rudra”);
names.add(“Shrawni”); names.add(“Parth”);
System.debug(names);
// output: Kshitij, Rudra, Shrawni, Parth
kshitijdhoble
List Method Example
// adding another list at specified index
List<String> emp =
new List<String>{“Kamlesh”, “Hemant”};
names.addAll(1, emp);
// output: Kshitij, Kamlesh, Hemant, Rudra,
Mandar, Shrawni, Parth
kshitijdhoble
List Method Example
// removing element of specified index
names.remove(5);
// output: Hemant, Kamlesh, Kshitij, Mandar,
Parth, Shrawni
kshitijdhoble
List Method Example
// cloning list
List<String> candidates = names.clone();
// clearing list
names.clear();
kshitijdhoble
Set
● Set is the collection of unique elements which is
unordered.
● Can store primitive data types, sObjects or user-defined
objects.
● Main properties of Set:
○ Only stores unique elements and not duplicate.
○ Sequence of element is not followed.
○ Elements in Set are case-sensitive.
● Therefore, we should use Set when uniqueness of data is
important and sequence is not important.
kshitijdhoble
How to Initialize Set
● Basic syntax:
kshitijdhoble
Set Methods
Methods Purpose
kshitijdhoble
Set Methods
Methods Purpose
kshitijdhoble
Set Methods
Methods Purpose
kshitijdhoble
Set Method Example
// methods like add() addAll() clear() clone()
contains() equals() isEmpty() remove() size()
toString() has same implementation as of list.
// declaring set
Set<String> names = new Set<String>{'Kshitij',
'Shrawni', 'Mandar'};
kshitijdhoble
Set Method Example
// removeAll (list of elements)
removeAll(list1);
System.debug(names); // Output: Set{'Shrawni'}
// same goes with set
kshitijdhoble
Map
● Map is a collection of key-value pair. Key can be any
primitive type and value can be primitive, sObjects, and
other collections.
● Data stored in Map is not in sequence.
● Main properties of Map:
○ Data stored in key-value pair.
○ Data stored is not in sequence.
○ Key must be unique and value can be duplicate.
● Therefore, we should use Map when we want to quickly
kshitijdhoble
How to Initialize Map
● Basic syntax:
kshitijdhoble
Map Methods
Methods Purpose
kshitijdhoble
Map Methods
Methods Purpose
kshitijdhoble
Map Methods
Methods Purpose
kshitijdhoble
Map Method Example
// methods like clear() clone() equals() isEmpty()
size() toString() has the same implementation as of
list and set.
// declaring map
Map<String, Integer> emp = new Map<String, Integer>
{'Kshitij'=>24, 'Shrawni'=>21,
'Mandar'=>10};
// containsKey
System.debug(emp.containsKey(“Kshitij”));
// true
System.debug(emp.containsKey(“John”));
// false
kshitijdhoble
Map Method Example
// size of map
emp.size(); // output: 3
// clone map
Map<String, Integer> empClone = emp.clone();
kshitijdhoble
Map Method Example
// adding all the mappings to a specified map
Map<String, Integer> emp1 = new Map<String, Integer>
{'Kamlesh'=>30, 'Parth'=>34,};
emp1.putAll(emp);
kshitijdhoble
Exception Handling
● Exception Handling is crucial in programming to manage
system.
handle exceptions.
kshitijdhoble
Exception Handling
● What exactly happens when exception occurs?
it isn’t catched.
kshitijdhoble
Exception Statements
● The throw statement is used to explicitly throw an
exception.
exception.
kshitijdhoble
Exception Statements
● We can handle exceptions using try-catch, finally blocks.
types of exceptions.
● These exceptions are built into the Apex language and are
runtime.
kshitijdhoble
System-defined Exceptions
● There are various system-defined exceptions in Apex.
kshitijdhoble
System-defined Exceptions
● Example:
try {
// Attempt to call a method on a null object
Account acc = null;
String accName = acc.Name; // This will throw
NullPointerException
} catch (NullPointerException e) {
// Handle null pointer exceptions
System.debug('Null Pointer Exception: ' +
e.getMessage());
} finally { // Code that will always execute
System.debug('This block is always executed.');
}
kshitijdhoble
Custom Exceptions
● Custom exceptions are user-defined and extend the
Exception class.
manner.
kshitijdhoble
Custom Exceptions
● Example:
public class TestCustomException {
public void checkNumber(Integer num) {
if (num < 0) {
throw new MyCustomException('Number must
be non-negative.');
}
}
}
kshitijdhoble
Exception Methods
Methods Purpose
kshitijdhoble
Best Practices
● Catch specific exceptions rather than generic ones. This
allows for more precise error handling and debugging.
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 07
Salesforce Object Search
Language (SOQL) in
Apex
kshitijdhoble
SOQL
● Salesforce Object Query Language, is similar to SQL
(Structured Query Language).
kshitijdhoble
When to use SOQL
● Retrieve Data: Fetch records from one or more Salesforce
objects (like Account, Contact, Custom objects, etc.).
● Filter Results: Get specific records by using conditions
(like WHERE clauses) to filter the data.
● Join Objects: Query related objects using relationships
(like parent-child relationships).
● Sort Data: Order the retrieved records using ORDER BY
clauses.
● Aggregate Data: Use functions like COUNT, SUM, AVG to
perform calculations on the data.
● In short, use SOQL to query and manipulate Salesforce
data effectively and efficiently.
kshitijdhoble
SOQL Syntax
● Here’s the basic syntax of SOQL:
● Example 01:
● Example 02:
SELECT FIELDS(ALL)
FROM Account
WHERE Name != null kshitijdhoble
SOQL Syntax in Apex
● In Salesforce, writing SOQL queries within square brackets
[ ] is a specific syntax used in Apex code.
● Here’s an example:
kshitijdhoble
SOQL Syntax in Apex
● Why do we need to write queries in [square brackets]?
kshitijdhoble
SOQL Syntax in Apex
● Example with output:
kshitijdhoble
Iteration of Query
● In Apex, we can iterate over the results of a SOQL query
using for or for-each loops, however, for-each loop is more
concise and recommended for iterating through
collections.
// using for loop
List<Account> accounts = [SELECT Name FROM Account];
for (Integer i = 0; i < accounts.size(); i++) {
System.debug(accounts[i].Name);
}
// using for-each loop
for (Account acc : [SELECT Name FROM Account]) {
System.debug(acc.Name);
}
kshitijdhoble
Variable Binding
● Variable binding allows us to use Apex variables in your
SOQL queries, enhancing flexibility and security.
● Here’s an example:
public Id accId = '0015g00000P5W8kAAF';
Account acc = [SELECT Id, Name
FROM Account
WHERE Id = :accId];
kshitijdhoble
Keywords
Category Keywords
kshitijdhoble
Keywords
● GROUP BY: Aggregates records by specified fields.
● HAVING: Filters aggregated records based on conditions.
● ORDER BY: Sorts the query results by specified fields.
● LIMIT: Restricts the number of records returned.
● OFFSET: Skips a specified number of records in query results.
● TYPEOF: Handles polymorphic relationships in queries.
● WHEN: Specifies conditions within a TYPEOF expression.
● THEN: Defines the result for a WHEN condition.
● ELSE: Provides an alternative result if no WHEN conditions
met.
kshitijdhoble
Keywords
● END: Concludes a TYPEOF expression.
● USING SCOPE: Limits query results based on a specified
scope.
● FOR VIEW: Retrieves records for viewing purposes.
● FOR REFERENCE: Retrieves records for reference purposes.
● UPDATE TRACKING: Tracks changes to records.
● UPDATE VIEWSTAT: Updates view statistics for records.
● FOR UPDATE: Locks records for update.
kshitijdhoble
Operators
Category Operators
kshitijdhoble
Operators
● ( = ) Checks if a value is equal to a specified value.
● ( != ) Checks if a value is not equal to a specified value.
● ( < ) Checks if a value is less than a specified value.
● ( > ) Checks if a value is greater than a specified value.
● ( <= ) Checks if a value is less than or equal to a specified
value.
● ( >= ) Checks if a value is greater than or equal to a specified
value.
kshitijdhoble
Operators
● LIKE: Checks if a value matches a specified pattern.
● IN: Checks if a value matches any value in a specified list.
● NOT IN: Checks if a value does not match any value in a
specified list.
● INCLUDES: Checks if a multi-select picklist field includes a
specified value.
● EXCLUDES: Checks if a multi-select picklist field excludes a
specified value.
● BETWEEN: Checks if a field value falls within a specified
range.
kshitijdhoble
Aggregate Functions
● Aggregate Functions are used to perform calculations on a
set of records and return a single value.
● useful for summarizing or grouping data to get meaningful
insights. Here are the main aggregate functions in SOQL:
Function Purpose
kshitijdhoble
Wild Cards
● In SOQL, the % and _ wildcards are used with LIKE operator:
kshitijdhoble
Relationship Queries
● Relationship queries traverse parent-to-child and
return results.
parent of Contact.
kshitijdhoble
Relationship Queries
● Parent-to-Child Relationship Queries (Subqueries):
○ Parent-to-Child relationship queries involve querying
related child records from a parent record.
○ This is done using subqueries.
○ Here’s an example: Query list of Accounts along with
their related Contacts.
SELECT Name,(SELECT FirstName, LastName
FROM Contacts)FROM Account
kshitijdhoble
Relationship Queries
● Child-to-Parent Relationship Queries (dot notation)
○ Child-to-Parent relationship queries involve querying
fields from a parent record when you are querying
from the child record.
○ This is done using dot notation.
○ Here’s an example: list of Contacts along with the
name of the Account they belong to.
SELECT FirstName, LastName, Account.Name
FROM Contact
kshitijdhoble
Multi-level Relationship Queries
● SOQL supports up to five levels of parent-to-child
relationships.
● We can traverse up to a maximum of five levels when
querying data from child-to-parent relationships.
● Here’s an example:
SELECT Name,
(SELECT LastName,
(SELECT AssetLevel,
(SELECT Description,
(SELECT LineItemNumber
FROM WorkOrderLineItems)
FROM WorkOrders)
FROM Assets)
FROM Contacts)
FROM Account kshitijdhoble
Dynamic SOQL
● Dynamic SOQL refers to the creation of a SOQL string at
runtime using Apex code.
● This allows for more flexible and customizable queries
based on user input or other variables.
● Here are some key points:
○ Creation: Dynamic SOQL queries are constructed as
strings at runtime.
○ Execution: Use Database.query or
Database.queryWithBinds methods to execute the
dynamic query.
○ Flexibility: Allows for dynamic filtering and querying
based on varying criteria.
kshitijdhoble
Dynamic SOQL
● Dynamic SOQL refers to the ability to create SOQL
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 08
Salesforce Object Search
Language (SOSL) in
Apex
kshitijdhoble
SOSL
● SOSL (Salesforce Object Search Language) is a language
used to perform text searches in Salesforce records.
kshitijdhoble
SOSL
● Why we need SOSL?
kshitijdhoble
SOSL Syntax
● We can write SOSL in 2 formats:
// example
FIND 'Acme'
IN ALL FIELDS
RETURNING Account(Name),
Contact(FirstName, LastName)
kshitijdhoble
SOSL Syntax
○ Apex Query Format: In Apex, SOSL queries are written
within square brackets [ ] and the result is a list of lists
of sObjects.
List<List<sObject>> results =
FIND 'searchQuery'
IN searchGroup
RETURNING objectType1(fields),
objectType2(fields)];
// example
List<List<sObject>> searchResults =
[FIND 'Acme' IN ALL FIELDS
RETURNING Account(Id, Name),
Contact(Id, Name)];
kshitijdhoble
Keywords in SOSL
Keywords Purpose
kshitijdhoble
Scope in SOSL
● In SOSL, the scope determines which fields are searched.
Here are the different scopes we can use:
Scope Purpose
SIDEBAR FIELDS Searches within fields indexed for the Salesforce sidebar
kshitijdhoble
Filters in SOSL
● In SOSL, we can use various filters to refine your search
results. Here are the main filters available:
Filters Purpose
kshitijdhoble
Wildcards in SOSL
● Wildcards in SOSL (Salesforce Object Search Language)
are special characters used to broaden the scope of a
search query by allowing partial matches. They are useful
when you don’t know the exact term you’re searching for
or want to capture variations of a word or phrase.
○ Asterisk ( * )
○ Question Mark ( ? )
kshitijdhoble
Wildcards in SOSL
● Asterisk ( * )
○ The asterisk wildcard matches zero or more characters
in a search term. It’s used to search for any sequence of
characters before or after a specified string. It is
typically placed at the beginning or end of a search
term to find words that start with or contain a specific
string.
○ Here’s an example:
FIND 'Acme*' IN ALL FIELDS RETURNING Account(Id, Name)
// This will find any record where a field starts with
"Acme" (e.g., "Acme Corp", "Acme Inc.").
kshitijdhoble
Wildcards in SOSL
● Question Mark ( ? )
○ The question mark wildcard matches exactly one
character. It’s used when you want to search for a
string with one variable character.
○ Example:
FIND 'Sm?th' IN NAME FIELDS RETURNING Contact(Id, Name)
// This will find contacts with names like "Smith" or
"Smyth" but not "Smithe" or "Smoth".
kshitijdhoble
SOSL Result Structure
● Why SOSL returns List of List of sObjects?
kshitijdhoble
SOSL Result Structure
● SOSL searches can retrieve data from several different
objects in a single query. For each object type specified in
the RETURNING clause, SOSL generates a separate list of
results.
● The outer List<List<sObject>> structure allows SOSL to
group the search results by object type. Each inner
List<sObject> corresponds to the search results for one
object type. This means that if we search across three
objects (Account, Contact, Opportunity), the result will be a
list containing three lists - one for each object type.
● This structure makes it easier to handle and process results
by object type. We can individually access the results for
each object type by referencing the appropriate index in
the outer list.
kshitijdhoble
SOSL Result Structure
// Consider the following SOSL query:
List<List<sObject>> searchResults = [FIND 'Acme' IN ALL
FIELDS RETURNING Account(Id, Name), Contact(Id, Name)];
kshitijdhoble
Dynamic SOSL
● Dynamic SOSL allows you to construct and execute SOSL
queries at runtime, giving you flexibility in building search
queries based on user input or other dynamic conditions.
kshitijdhoble
Key Concepts
● String-based query construction:
○ Unlike static SOSL, where the query is hard-coded,
dynamic SOSL involves constructs query as a string.
○ The query string is built using Apex string
manipulation techniques, such as concatenation or
string variables.
● Execution using Search.query( ):
○ The dynamically constructed query string is passed to
the Database.query() method, which executes the
SOSL query.
○ This method returns the results in the same format as
a static SOSL query: a List<List<sObject>>.
kshitijdhoble
Detailed Structure
● Defining search term in String variable:
String searchTerm = ‘Acme’’;
● Constructing SOSL query by concenating search term:
String soslQuery = 'FIND \'' + searchTerm + '\'
IN ALL FIELDS
RETURNING Account(Id, Name),
Contact(Id, Name)';
● Executing the query using Search.query( ):
List<List<sObject>> searchResults =
Search.query(soslQuery);
kshitijdhoble
Advantages
● Advantages of Dynamic SOSL
kshitijdhoble
Use Cases
● User-Driven Searches: Create searches based on what
users are looking for.
kshitijdhoble
SOQL / SOSL Difference
Feature SOQL SOSL
kshitijdhoble
Best Practices
● Input Sanitization: Be cautious of SOSL injection, a
security risk where malicious input could alter your query.
Always validate or escape user inputs.
kshitijdhoble
Day 09
DML Statements &
Database Class Methods in
Apex
kshitijdhoble
What is DML?
● Data Manipulation Language (DML) refers to the set of
retrieve records.
tasks.
kshitijdhoble
DML Uses
● DML used in Salesforce when you need to manage and
manipulate records in the database.
kshitijdhoble
Syntax & Structure
● Direct DML Statements:
○ These are straightforward commands like insert,
update, delete, etc. Example:
Account acc = new Account(Name='Acme Corporation');
insert acc;
● Database Class Methods: (We will cover this further)
○ This provides more control over DML operations,
allowing for fine-grained exception handling and the
ability to execute partial operations. Example:
Account acc = new Account(Name='Acme Corporation');
Database.SaveResult sr = Database.insert(acc, false);
kshitijdhoble
Various DML Statements
● Insert: To add new records in Salesforce.
kshitijdhoble
Various DML Statements
● Update: To modify existing records in Salesforce.
kshitijdhoble
Various DML Statements
● Delete: To remove records from Salesforce.
kshitijdhoble
Various DML Statements
● Undelete: To restore records that have been deleted and
are still in the Recycle Bin.
kshitijdhoble
Various DML Statements
● Upsert: To insert a record if it doesn't exist or update it if it
does.
// Create new Account record with external Id field
Account acc = new Account();
acc.Name = 'New Account';
acc.Industry = 'Finance';
acc.ExternalId__c = '12345'; // Assume externalId__c
is a unique field
kshitijdhoble
Various DML Statements
● Merge: Combines up to 3 records of same object type into
one, keeping the master record and merging others. Use
merge to clean up duplicate records in Salesforce org.
Account master = [SELECT Id FROM Account
WHERE Name='Acme Corp'
LIMIT 1];
Account duplicate1 = [SELECT Id FROM Account
WHERE Name='Acme Corp'
AND Id != :master.Id LIMIT 1];
Account duplicate2 = [SELECT Id FROM Account
WHERE Name='Acme Corp'
AND Id != :master.Id
AND Id != :duplicate1.Id
LIMIT 1];
merge master duplicate1 duplicate2;
kshitijdhoble
Bulk DML Operations
● Bulk DML operations are used when you need to perform
DML on multiple records at once.
● Apex automatically optimizes bulk DML operations to
ensure efficiency and to avoid hitting governor limits.
● Here’s a simple example in which we are trying to insert
100 contacts at once using DML statement.
// inserting 100 contacts at once
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 100; i++) {
contacts.add(new Contact(FirstName='John',
LastName='Doe' + i));
}
insert contacts;
kshitijdhoble
Database Class Methods
● The Database class in Apex provides specialized methods
for executing DML (Data Manipulation Language)
operations.
kshitijdhoble
Use Cases
We use Database class methods for several reasons:
● Partial Success Handling: Unlike standard DML
operations that fail entirely if one record causes an error,
Database class methods allow partial success. This means
some records can be successfully processed even if others
fail.
● Exception Handling: Database methods provide a way to
capture detailed error information, enabling developers to
handle exceptions more effectively.
● Bulk DML Operations: These methods are designed to
work efficiently with large datasets, respecting Salesforce's
governor limits and allowing bulk processing.
● Transaction Control: They allow more refined control over
transactions, such as rolling back operations if certain
conditions aren't met.
kshitijdhoble
Methods in Database Class
Methods Purpose
Database.merge(masterRecord,
Merges records with a master record.
recordsToMerge)
kshitijdhoble
Exception Handling in DML
Database Class Methods Result Object:
kshitijdhoble
Partial Execution
● Partial Exception occurs when a DML operation succeeds
for some records and fails for others.
Database.SaveResult[] results =
Database.insert(cc, true);
kshitijdhoble
Scenario - Partial Execution
● Hence we need to pass false to perform partial execution.
// handling exceptions with partial execution.
try{ Database.saveResult[] results =
Database.insert(cc, false);
for(Database.saveResult rr : results){
if (rr.isSuccess()){
System.debug(“Contact Inserted” + rr.getId());
}else{ for(Database.error er : rr.getErrors()){
System.debug(“Error” + er.getMessage());}}
}catch(DmlException e){
System.debug(“Exception during record insertion”
+ e.getLineNumber());
}
kshitijdhoble
Scenario - Partial Execution
● In the previous Apex code, we passed the parameter as
false. Also we iterated over results to get ID of records
which are saved successfully and error message for records
which are failed
kshitijdhoble
Transaction Control / Roll Back
● Salesforce treats DML operations within a single execution
context as a transaction.
kshitijdhoble
Best Practices
● Bulkifying Code: Always handle multiple records at once
to avoid hitting governor limits.
kshitijdhoble
Note
● Never exceed allowed number of DML Statements as per
governor limits.
the loop.
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 10
Synchronous Apex - Triggers
in
Apex
kshitijdhoble
Synchronous Apex
● Synchronous Apex refers to processes that execute
● This means the user interface (UI) will block and wait for
kshitijdhoble
Why Synchronous Apex?
● Why Do We Use Synchronous Apex?
kshitijdhoble
Types of Synchronous Apex
● Types of Synchronous Apex:
kshitijdhoble
What is Trigger?
● A Trigger in Salesforce Apex is a piece of code that
automatically executes before or after certain events occur
on a Salesforce object.
performance issues.
kshitijdhoble
Types of Triggers
● Before Triggers:
kshitijdhoble
Types of Triggers
● After Triggers:
kshitijdhoble
Use Cases - After Triggers
● Accessing System Fields: Use after triggers to access
fields like Id or CreatedDate that are available only after the
record is saved.
● Related Records: Create, update, or delete related records.
For instance, create a contact when an account is inserted.
● Callouts: Make callouts to external systems after a record is
saved, but do this cautiously to avoid performance issues.
● Complex Business Logic: Perform complex logic that
requires the record to be committed, such as aggregating
data based on new or updated records.
kshitijdhoble
Trigger Events
● Trigger events are specific database operations that cause
a trigger to fire in Salesforce.
kshitijdhoble
Trigger Events
● Before Insert executes before a new record is inserted.
Ideal for validating or modifying record values before they
are committed.
● Before Update executes before an existing record is
updated. Useful for checking and updating record values
before they are saved.
● Before Delete executes before an existing record is
deleted. Allows you to perform cleanup or validation tasks
before the record is removed.
● Before Merge executes after records have been merged
into a single record. Allows you to perform actions or
validations before the merge operation is finalized. This
event is used to handle scenarios where you need to
validate or adjust the records that will be merged.
kshitijdhoble
Trigger Events
● After Insert Executes after a new record is inserted.
Suitable for actions that require the record to be saved,
such as creating related records or making external system
callouts.
kshitijdhoble
Trigger Events
● After Undelete executes after a record is recovered from
the Recycle Bin. Allows you to perform actions based on
records that have been restored, such as re-establishing
relationships or updating related records.
kshitijdhoble
Before undelete
● The event before undelete is not available because:
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 11
Apex Triggers (Part 2)
in
Apex
kshitijdhoble
Flow of Triggers
Initiate
Database Before Trigger
Operation
Database
After Trigger
Operation
kshitijdhoble
Flow of Triggers
● Initiate Database Operation: This is where the action
begins, typically from a user’s action in the Salesforce UI, a
code execution, or an external system.
● Before Trigger: Before the actual database operation is
committed, the before trigger executes. This is where you
can perform validation or set values before they are
committed to the database.
● Database Operation: After the before trigger completes
successfully, the database operation (like INSERT, UPDATE,
DELETE, UNDELETE) is executed.
● After Trigger: Once the database operation is completed,
the after trigger runs. This is typically used when you need
to make changes that rely on the database operation
having been completed
kshitijdhoble
Syntax
● A trigger in Salesforce has a specific structure. Here’s
the syntax breakdown:
trigger TriggerName on ObjectName(trigger_events)
{
// validations
// custom logic
// code to be executed
}
● trigger is the keyword used to declare a trigger.
● TriggerName could be any name for trigger.
● ‘on’ keyword binds the trigger to a specific Salesforce object.
● trigger_events are the specific DML events that will cause
the trigger to fire.
kshitijdhoble
Example
● Scenario: Write a trigger on the Account object that
automatically sets the Description field to "New Account"
whenever a new account record is inserted.
kshitijdhoble
Facts
● A single Apex trigger can handle multiple events, including
before and after events for insert, update, delete, merge,
upsert, and undelete. To specify multiple events, use a
comma-separated list in the trigger syntax.
kshitijdhoble
Order of Execution of Triggers
● The order of execution in Apex triggers is a defined
sequence that Salesforce follows when processing a record
in the database.
● Understanding this order is crucial for ensuring that your
code behaves as expected, especially when multiple
triggers, workflows, and validations are involved.
● Here’s the order of execution when a record is created,
updated, or deleted:
1. System Validation Rules: Basic checks like required fields
and data types are performed.
2. Before Triggers: Executes before saving the record, used
to validate or modify values.
kshitijdhoble
Order of Execution of Triggers
3. System Validation Rules (Again): Re-validates the record,
including custom rules.
4. Duplicate Rules: Checks for duplicates, potentially halting
the process.
5. Record Saved (Not Committed): The record is saved but
not yet committed.
6. After Triggers: Executes after saving the record, often used
for related operations.
7. Assignment Rules: Processes lead or case assignment
rules.
8. Auto-Response Rules: Processes auto-response rules for
leads and cases.
kshitijdhoble
Order of Execution of Triggers
9. System Validation Rules (Again): Re-validates the record,
including custom rules.
10. Workflow Rules: Evaluates and processes any triggered
workflow rules.
11. Escalation Rules: Processes escalation rules for cases.
12. Processes and Flows: Processes any triggered processes
or flows.
13. Entitlement Rules: Processes entitlement rules if
applicable.
14. Roll-Up Summary Fields: Recalculates parent roll-up
summary fields.
kshitijdhoble
Order of Execution of Triggers
15. Commit Transaction: Attempts to commit the transaction;
if errors occur, it rolls back.
16. Post-Commit Logic: Executes post-commit actions like
sending emails.
17. DML on Related Records: Repeats the process for any
related records affected.
18. Email Notifications: Sends out any triggered email
notifications.
kshitijdhoble
Trigger Context Variables
● Trigger context variables in Apex are special variables that
Salesforce automatically provides within a trigger.
kshitijdhoble
Trigger Context Variables
● Trigger.new
○ It returns list of new version of sObject records that are
being inserted or updated.
○ Trigger.new is only available for insert, update, and
undelete operations, it’s not available in delete because
there’s no new version of records when they are
deleted.
● Trigger.old
○ It returns list of old version of sObject records that are
being updated or deleted.
○ Trigger.old is only available for update and delete
operations, it’s not available in insert triggers because
there are no old versions of the records.
kshitijdhoble
Trigger Context Variables
● Trigger.newMap
○ It returns a map of record IDs to the new versions of
the records. This is useful when you need to quickly
access a record by its ID.
○ Trigger.new is available for insert and update
operations and not available for delete operations.
● Trigger.oldMap
○ it returns a map of record IDs to the old versions of the
records. This is useful when you need to quickly access
a record by its ID.
○ Trigger.old is available for update and delete
operations and not available for insert operations.
kshitijdhoble
Trigger Context Variables
● Trigger.isInsert
○ Returns true if the trigger was fired due to an INSERT
operation. This is useful for performing actions only
when records are being inserted.
● Trigger.isUpdate
○ Returns true if the trigger was fired due to an UPDATE
operation. You can use this to handle logic specific to
record updates.
● Trigger.isDelete
○ Returns true if the trigger was fired due to a DELETE
operation. This is useful for actions that should occur
when records are deleted.
kshitijdhoble
Trigger Context Variables
● Trigger.isUndelete
○ Returns true if the trigger was fired due to an
UNDELETE operation. This is specifically used for
actions that should occur when records are restored
from the Recycle Bin.
● Trigger.isBefore
○ Returns true if the trigger was fired before any records
were saved to the database (i.e., BEFORE triggers). Use
this for validations or modifications to the records
before they are committed to the database.
● Trigger.isAfter
○ Returns true if the trigger was fired after the records
were saved to the database (i.e., AFTER triggers).
Typically used for actions that require the record to be
already committed.
kshitijdhoble
Trigger Context Variables
● Trigger.operationType
○ Returns the specific type of DML operation that caused
the trigger to fire. It can return values like insert,
update, delete, undelete.
● Trigger.size
○ Trigger.size returns the total number of records that
are part of the trigger invocation.
○ It is particularly useful when you want to check how
many records are being processed within a single
trigger context.
kshitijdhoble
Bulkifying Triggers
● A bulkified trigger is written to handle a large number of
records efficiently, rather than processing one record at a
time.
kshitijdhoble
Why Bulkify Triggers?
● Avoid Hitting Governor Limits: Salesforce imposes limits
on the number of records processed and the number of
SOQL queries, DML operations, etc., per transaction.
Bulkified triggers help ensure that your code does not
exceed these limits.
kshitijdhoble
Why Bulkify Triggers?
● Non-bulkified triggers may work for small volume of data,
but it has some drawbacks.
kshitijdhoble
Trigger Helper Class
● Trigger Helper Class Design Pattern is the best practice
used when writing triggers. Using this pattern helps in
keeping trigger logic modular, reusable and maintainable.
kshitijdhoble
Recursion in Triggers
● A trigger directly invokes itself. For example, if a trigger
performs a DML operation that causes the same trigger to
fire again, it results in direct recursion.
kshitijdhoble
Day 12
Governor Limits
in
Apex
kshitijdhoble
Governor Limits
● Governor limits are runtime limits enforced by Salesforce
to regulate the consumption of resources.
● These limits apply to Apex code execution, making sure
that a single transaction does not consume excessive
resources, which could impact the performance of the
entire Salesforce instance.
● These are some set of rules that restrict the use of cloud
resources by organizations that use Salesforce servers.
● These limits are enforced by the Apex runtime engine to
ensure that one client or process does not monopolize
shared resources on the Salesforce platform.
kshitijdhoble
Why Governor Limits Exists?
● Salesforce is a multi-tenant environment, meaning
multiple customers share the same underlying
infrastructure.
● To ensure fair usage and to prevent any single customer
from consuming too many resources (which could
degrade the performance for others), Salesforce enforces
governor limits. These limits help in:
○ Ensuring the stability and performance of the
Salesforce environment.
○ Preventing infinite loops or resource-heavy operations
from crashing the system.
○ Encouraging developers to write efficient, scalable
code.
kshitijdhoble
Types of Governor Limits
● Major Governor Limits:
○ Total number of SOSL queries issued in Salesforce: 20
○ DML Governor Limits in Salesforce (Total number of
statements issued per transaction): 150
○ Total number of records retrieved by a single SOSL
query: 2000
○ Total number of records retrieved by SOQL queries:
50000
○ Total number of records retrieved by
Database.getQueryLocator: 10000
○ Salesforce Governor Limits for heap size total: 6 MB
Synchronous, 12 MB Asynchronous
kshitijdhoble
Types of Governor Limits
● Per-transaction Certified Managed Package Limits:
○ The total number of SOQL queries issued: 1100
○ The total number of records retrieved by
Database.getQueryLocator: 110000
○ The total number of SOSL queries issued: 220
○ The total number of DML statements issued: 1650
○ The total number of callouts (either HTTP requests or
Web services calls) in a transaction: 1100
○ The total number of sendEmail methods allowed: 110
kshitijdhoble
Types of Governor Limits
● Static Apex Limits:
○ Default timeout of callouts (HTTP requests/Web
services calls) in a transaction: 10 seconds
○ Maximum size of the callout request or response : 6 MB
for synchronous,12 MB for asynchronous.
○ Maximum SOQL query runtime before Salesforce
cancels the transaction: 120 seconds
○ Maximum number of class and trigger code units in
the deployment of Apex: 5,000
○ Apex trigger batch size: 200
○ For loop list batch size: 200
○ Maximum number of records that are returned for a
Batch Apex query in Database.QueryLocator: 50 million
kshitijdhoble
Types of Governor Limits
● Per-transaction Apex Limits:
○ The total number of SOQL queries issued: 100
synchronous, 200 asynchronous
○ Number of records retrieved by SOQL queries: 50,000
○ Number of records retrieved by
Database.getQueryLocator: 10000
○ The total number of SOSL queries issued: 20
○ The total number of records retrieved by a single SOSL
query: 20000
○ The total number of DML statements issued: 150
○ Number of records processed as a result of DML
statements, Approval.process, or
database.emptyRecycleBin: 10000
kshitijdhoble
Types of Governor Limits
○ The total stack depth for any Apex invocation that
recursively fires triggers with insert, update, or delete
statements:16
○ The total number of callouts (either HTTP requests or
Web services calls) in a transaction: 100
○ The maximum cumulative timeout for all callouts
(either HTTP requests or Web services calls) in a
transaction: 120 seconds
○ The maximum number of methods with the future
annotation allowed per Apex invocation : 50 in
synchronous, 0 in batch and future contexts and 1 in
the queueable context
kshitijdhoble
Types of Governor Limits
○ The total number of sendEmail methods allowed: 10
○ The total heap size: 6 MB synchronous, 12 MB
asynchronous
○ The maximum CPU time on Salesforce servers: 10,000
milliseconds in synchronous, 60,000 milliseconds in
asynchronous
○ The maximum execution time for each Apex
transaction: 10 minutes
○ The maximum number of push notification method
calls allowed per Apex transaction: 10
○ The maximum number of push notifications that can
be sent through each push notification method call:
2000
kshitijdhoble
Types of Governor Limits
● Lightning Platform Apex Limits:
○ The maximum number of asynchronous Apex method
executions (Batch Apex, future methods, Queueable
Apex, and Scheduled Apex) per 24-hour period: Either
250,000 or the number of user licenses in the org
multiplied by 200, whichever is greater
○ The number of synchronous concurrent transactions
for long-running transactions, which last longer than 5
seconds for each org.: 10
○ The maximum number of Apex classes scheduled
concurrently: 100 In Developer Edition org, the limit is 5
○ The maximum number of Batch Apex jobs in the Apex
flex queue that is in the Holding status: 100
kshitijdhoble
Types of Governor Limits
○ The maximum number of Batch Apex jobs queued or
active concurrently: 5
○ The maximum number of Batch Apex job start
method concurrent executions: 1
○ The maximum number of batch jobs that can be
submitted in a running test:5
○ The maximum number of test classes that can be
queued in a 24-hour period (in Production org other
than Developer Edition): Either 500 or 10 multiplied
by the number of test classes in the org, whichever is
greater
kshitijdhoble
Types of Governor Limits
○ Maximum number of query cursors open concurrently
per user: 50
○ Maximum number of query cursors open concurrently
per user for the Batch Apex start method: 15
○ Maximum number of query cursors open concurrently
per user for Batch Apex execute and finish methods: 5
kshitijdhoble
Types of Governor Limits
● Specific Apex Limits:
○ Maximum number of characters in a class: 1 million
○ Maximum number of characters in a trigger: 1 million
○ Maximum amount of code used by all Apex codes in
org: 6 MB
○ The method size limit: 65,535 bytecode instructions in a
compiled form
kshitijdhoble
Monitoring Governor Limits
● Monitoring governor limits in Apex is crucial for ensuring
that our code adheres to Salesforce's execution constraints,
preventing runtime exceptions and improving
performance.
kshitijdhoble
Monitoring Governor Limits
● Common methods of Limits Class:
○ SOQL Queries:
■ Limits.getQueries(): Returns the number of SOQL
queries executed.
■ Limits.getLimitQueries(): Returns the maximum
number of SOQL queries allowed (100 in a
synchronous, 200 in an asynchronous).
○ DML Statements:
■ Limits.getDMLStatements(): Returns the number
of DML statements executed.
■ Limits.getLimitDMLStatements(): Returns the
maximum number of DML statements allowed
(150 in a synchronous context, 150 in an
asynchronous context).
kshitijdhoble
Monitoring Governor Limits
○ CPU Time:
■ Limits.getCpuTime(): Returns the CPU time (in
milliseconds) consumed.
■ Limits.getLimitCpuTime(): Returns the maximum
CPU time allowed (10,000 ms).
○ Heap Size:
■ Limits.getHeapSize(): Returns the amount of heap
memory used.
■ Limits.getLimitHeapSize(): Returns the maximum
heap size allowed (6 MB for synchronous
transactions, 12 MB for asynchronous transactions).
kshitijdhoble
Monitoring Governor Limits
2. Using Apex Debug Logs:
kshitijdhoble
Day 13
Asynchronous Apex -
Batchable Interface in
Apex
kshitijdhoble
Asynchronous Apex
● Asynchronous Apex refers to processes that run in the
background, separate from the main thread, allowing
operations to continue without waiting for the process to
complete.
kshitijdhoble
Why Asynchronous Apex?
4. Improving User Experience:
kshitijdhoble
Why Asynchronous Apex?
5. Scalable Processing:
kshitijdhoble
Why Asynchronous Apex?
6. Handling External Integrations:
kshitijdhoble
Types of Asynchronous Apex
● Batch Apex: Use for processing large volumes of records,
such as updating all contacts in an organization or
recalculating all opportunities.
kshitijdhoble
What is Batch Apex?
● Batch Apex is a powerful feature in Salesforce that allows
you to process large volumes of data in smaller,
manageable chunks.
kshitijdhoble
Origin of Batch Apex
● Batch Apex was introduced by Salesforce as part of its
asynchronous processing capabilities to handle scenarios
where operations on large datasets are required.
kshitijdhoble
How Batch Apex Works?
● Batch Apex is implemented by writing a class that
implements the Database.Batchable interface. This
interface requires the implementation of 3 methods:
○ Start( ): The start method is used to collect the records
or data you want to process. It returns an Iterable or
Database.QueryLocator that Batch Apex will use to
retrieve the records in chunks.
○ Execute( ): The execute method is where the actual
processing of data happens. It takes in a context and a
list of records (or a scope) to process in each batch.
○ Finish( ): The finish method is executed after all
batches have been processed. It can be used for any
post-processing logic, such as sending a notification or
triggering another batch process.
kshitijdhoble
How Batch Apex Works?
● Why Batch Class is Global?
● What is Database.Batchable<SObject>
kshitijdhoble
How Batch Apex Works?
● What is Database.QueryLocator
● What is Database.BatchableContext
kshitijdhoble
How Batch Apex Works?
● What is Database.getQueryLocator
kshitijdhoble
How Batch Apex Works?
● Example: Updating the status of all active accounts.
global class UpdateStatusBatch implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext BC){
String query = ‘SELECT Id, Name
FROM Account WHERE Status__c = \’Active\’’;
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> sc){
for(Account acc : sc){
acc.Status__c = ‘Inactive’;
} update scope;
}
global void finish((Database.BatchableContext BC){
// finishing tasks like sending success mails
}
} kshitijdhoble
Key Features of Batch Apex
● Batch Size: The default batch size is 200 records, but you
can specify a different batch size (between 1 and 2,000)
when invoking the batch.
● Monitor and Log: Use the finish method to log the results
of the batch job or send notifications to monitor the
success or failure of the job.
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 14
Schedulable Interface
in
Apex
kshitijdhoble
What is Scheduled Apex?
● Scheduled Apex is a feature in Salesforce that allows you
to execute Apex classes at specified times.
kshitijdhoble
Origin of Scheduled Apex
● Scheduled Apex is another feature provided by Salesforce
as part of its asynchronous processing capabilities,
allowing developers to automate the execution of Apex
code at specific times or intervals.
● This is particularly useful for tasks that need to be run
regularly, such as nightly data processing, sending periodic
emails, or performing maintenance activities.
● In Scheduled Apex, developers implement the
Schedulable interface, which provides a method called
execute that contains the logic to be run.
● Once the Apex class is written, it can be scheduled to run
at a specified time using the System.schedule( ) method
or through the Salesforce user interface.
kshitijdhoble
Origin of Scheduled Apex
● The Schedulable interface makes it possible to trigger
Apex code according to a defined schedule, allowing for
greater automation and better resource management.
kshitijdhoble
How Scheduled Apex Works?
● Here's a step-by-step breakdown of how it works:
1. Implementing the Schedulable Interface:
○ To create a class that can be scheduled, the class must
implement the Schedulable interface.
○ This interface requires you to define an execute
method that contains the code you want to run when
the job is triggered.
2. Scheduling a Job:
○ There are several ways to schedule an Apex job,
depending on the requirements and complexity.
Contd…
kshitijdhoble
How Scheduled Apex Works?
A. Using the Salesforce UI (Setup Menu): Steps to follow
○ Setup > Apex Classes > Schedule Apex > Select Class
○ Specify the frequency (daily, weekly, etc.), start date,
and preferred time. Then Save.
kshitijdhoble
How Scheduled Apex Works?
B. Using Corn Expressions (Programmatic Approach):
kshitijdhoble
How Scheduled Apex Works?
C. Using System.schedule( ) method:
○ The System.schedule() method is used to schedule a
class that implements the Schedulable interface.
○ This method allows us to specify a cron expression to
determine when the job should run.
○ We can schedule an Apex job directly from the
Developer Console by executing anonymous Apex
code.
D. Using scheduleJob( ) method:
○ When we want to schedule a job programmatically
from another class, we can use the ScheduleJob()
method, which internally uses the System.schedule
method.
kshitijdhoble
How Scheduled Apex Works?
3. Executing the Scheduled Job:
○ When the scheduled time arrives, Salesforce
automatically invokes the execute method of the
scheduled class. The code within this method runs
with the privileges of the user who scheduled the job.
○ If the scheduled class includes batch processing or
another scheduled job, those processes will be kicked
off as well.
4. Monitoring and Managing Scheduled Jobs:
○ We can monitor and manage your scheduled jobs in
Salesforce.
○ This includes checking the status, aborting jobs, and
even rescheduling them if necessary.
kshitijdhoble
How Scheduled Apex Works?
● What is SchedulableContext?
○ The SchedulableContext interface provides methods to
interact with the scheduled job when the execute
method of a Schedulable class runs. It allows you to
track information about the job execution and its
context.
○ SchedulableContext.getJobId( ) method Returns the
ID of the scheduled job, which can be used to track or
abort the job if needed.
● What is scheduleJob( ) method?
○ The scheduleJob method in the context provided is a
custom method that encapsulates the logic for
scheduling an Apex class to run at a specific time using
System.schedule( ) method.
kshitijdhoble
How Scheduled Apex Works?
● What is System.schedule( )?
○ The System.schedule method is used to schedule an
Apex class that implements the Schedulable interface
to run at a specific time in the future or on a recurring
basis.
○ Parameters:
■ jobName: A string that names the scheduled job
(e.g., "Daily Update Status Job").
■ cronExpression: A string that defines the schedule
using a cron expression.
■ schedulableClass: An instance of the class
implementing the Schedulable interface that you
want to run.
kshitijdhoble
How Scheduled Apex Works?
● What is a Corn Expression?
kshitijdhoble
How Scheduled Apex Works?
● Structure of Corn Expression?
Field Breakdown:
<sec>: Seconds (0-59), <mins>: Minutes (0-59)
<hrs>: Hours (0-23), <day-of-month>: Day of the month (1-31)
<month>: Month (1-12 or JAN-DEC)
<day-of-week>: Day of the week (1-7 or SUN-SAT).
<year>: Optional Year (e.g., 2024)
kshitijdhoble
How Scheduled Apex Works?
● Example: Scheduling the batch for 2 AM everyday.
// implementing Scheculabe interface
global class ScheduleUpdateStatus implements Schedulable {
global void execute(SchedulableContext SC) {
// calling batch class (previous example in batch class)
UpdateStatusBatch batchJob = new UpdateStatusBatch();
Database.executeBatch(batchJob);
}
public static void scheduleJob() { // using scheduleJob() method
// Define the cron expression (every day at 2 AM)
String cronExp = '0 0 2 * * ?';
// scheduling job using System.schedule() method
System.schedule('Daily Update Status Job', cronExp,
new ScheduleUpdateStatus());
}
} kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 15
Future Method
in
Apex
kshitijdhoble
What is a Future Method ?
● A Future Method is an asynchronous process in Apex that
transaction.
kshitijdhoble
Why We Use Future Method ?
Future methods are used in scenarios where we need to:
kshitijdhoble
Key Features
● Asynchronous Execution: Future methods run in the
background, allowing the main thread to continue
processing without waiting for the future method to
complete.
kshitijdhoble
Syntax & Structure
● public: The method must be public so that it can be
accessed from other classes or triggers.
● static: The method must be static because it does not
depend on an instance of the class.
● void: Future methods cannot return a value, hence the
return type is void.
● Type1 param1, Type2 param2, ...: The method parameters.
These must be primitive data types, collections of
primitives, or sObject IDs. Future methods don’t accept
sObjects or complex data types as parameters.
● The body of the method contains the code that will be
executed asynchronously.
kshitijdhoble
Example
● Scenario: To send a welcome email asynchronously
when a new customer record is created
// Step 1: Creating the Future Method
public class CustomerService {
@future
public static void sendWelcomeEmail(Id customerId) {
// Fetch the customer record
Customer__c customer = [SELECT Name, Email__c
FROM Customer__c
WHERE Id = :customerId];
kshitijdhoble
Use Cases
● Making Callouts: Future methods are often used when
making callouts to external web services, especially when
the callout needs to happen after some database
operations have completed.
kshitijdhoble
Key Points to Remember
● Future methods must be static. This is because they are
executed in a separate thread from the initiating code, so
they must not depend on instance-specific data.
● Future methods do not return any value. This is because
they are executed asynchronously and the result is not
available to the calling method.
● Future methods have higher limits than synchronous
methods. For example, we can perform up to 200 SOQL
queries or DML statements in a future method, compared
to 100 in synchronous.
● We cannot call a future method from another future
method. However, we can use Queueable Apex if you need
to chain asynchronous operations.
kshitijdhoble
Limitations
● Limited to One: You can only have one future method in a
single transaction.
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 16
Queueable Interface
in
Apex
kshitijdhoble
What is Queueable Apex?
● Queueable Apex is another powerful feature in Salesforce
designed to handle asynchronous processing, similar to
Batch Apex but with some differences in functionality and
use cases.
kshitijdhoble
Origin of Queueable Apex
● Queueable Apex was introduced by Salesforce to offer a
flexible and easier alternative to traditional asynchronous
processing methods like future methods.
● execute(QueueableContext context):
kshitijdhoble
How Queueable Apex Works?
● Example: Updating the contact records with a specific
value for a custom field
// implementing queueable interface
public class UpdateContactsQueueable implements Queueable {
public void execute(QueueableContext context) {
// Query contacts to be updated
List<Contact> contactsToUpdate = [SELECT Id, Custom_Field__c
FROM Contact WHERE Custom_Field__c = NULL LIMIT 100];
for(Contact con : contactsToUpdate) { // updating custom field
con.Custom_Field__c = 'Updated Value';
}
// Perform the DML operation to update the records
if(!contactsToUpdate.isEmpty()) {
update contactsToUpdate;
}
} kshitijdhoble
}
How Queueable Apex Works?
● Enqueuing the job:
kshitijdhoble
Key Features
● Asynchronous Execution: Queueable Apex allows us to
execute code asynchronously, meaning it runs in the
background without blocking the main transaction.
kshitijdhoble
Key Features
● Job Monitoring: Queueable jobs can be monitored
through the Salesforce UI, where us can track the status
and progress of the queued jobs.
● Finer Control Over Execution: The QueueableContext
object provides methods to retrieve the job ID and
manage the job, offering finer control over the job's
execution compared to @future methods.
● Limits: Queueable Apex has higher governor limits
compared to synchronous code, similar to Batch Apex,
making it suitable for handling large data volumes.
However, it still has some limitations, such as a limit of 50
jobs that can be added to the queue per transaction.
kshitijdhoble
Use Cases
● Complex Calculations: When you need to perform long or
complex calculations without blocking other operations.
● Data Transformation: Converting or updating large
amounts of data in the background.
● External API Calls: Calling external web services or APIs
that may take time.
● Chaining Jobs: Running multiple jobs in sequence where
each job depends on the previous one.
● Handling Large Data Volumes: Processing large data sets
efficiently by breaking them into manageable pieces.
● Delayed Processing: Performing tasks that don’t need to
happen immediately but should be done asynchronously.
● Background Processing: Running tasks that don’t need to
be completed within same transaction as the user request.
Best Practices
● Use for Asynchronous Processing: Queueable Apex is
ideal for long-running or resource-intensive operations
that need to be processed in the background.
● Chain Jobs Carefully: You can chain Queueable jobs, but
avoid creating too many chained jobs to prevent hitting
governor limits.
● Limit Chaining Depth: Salesforce limits the depth of job
chaining. Keep it shallow to avoid hitting limits.
● Handle Exceptions: Implement proper exception handling
within the execute method to ensure that errors are
managed gracefully.
kshitijdhoble
Best Practices
● Optimize Resources: Avoid complex queries and
operations within execute to keep resource usage efficient.
● Test Thoroughly: Write test classes to cover your
Queueable Apex. Ensure that tests cover job execution and
handle possible exceptions.
● Consider Limits: Be mindful of Salesforce governor limits,
such as the maximum number of jobs in the queue and
the maximum execution time.
● Use Synchronous Jobs Sparingly: For short tasks or jobs
that must run immediately, consider using synchronous
methods like future methods or Batch Apex.
kshitijdhoble
Thank-You!
Stay Tuned & Follow
kshitijdhoble
Day 17
Apex Testing
in
Apex
kshitijdhoble
Apex Testing
● Apex testing involves writing and running unit tests to
ensure that the code behaves as expected.
● These tests are crucial for maintaining code quality and for
preventing future changes from breaking existing
functionality.
kshitijdhoble
Apex Testing
● The primary goal of writing Apex test code is to validate
that the production Apex classes and triggers behave as
expected under various conditions.
kshitijdhoble
Purpose of Apex Testing
● Apex tests are written in special test classes, which contain
methods that validate the logic in our Apex classes and
triggers.
● These tests simulate the execution of code in a controlled
environment, allowing us to check the expected outcomes
against actual results.
● The primary purpose of testing in Apex is to:
○ Ensures Code Quality: Testing helps in identifying
bugs or issues before they reach production.
○ Regression Testing: Automated tests ensure that new
changes don’t break existing functionality.
kshitijdhoble
Purpose of Apex Testing
○ Required by Salesforce: Salesforce mandates a
minimum of 75% code coverage for deployment to
production. This means that our test cases must cover
at least 75% of our Apex code.
○ Continuous Integration (CI): Tests are crucial for CI
pipelines, ensuring that code integrates smoothly.
kshitijdhoble
Key Concepts in Apex Testing
● Test Coverage:
○ Refers to the percentage of our code that is executed
during testing.
○ Higher coverage usually indicates more thorough
testing, but 100% coverage doesn't always mean that
all potential issues are addressed.
● Isolation:
○ Each test should be independent and should not affect
the results of other tests.
○ Salesforce provides a clean environment for each test
method, ensuring data created or modified during one
test doesn’t affect others.
kshitijdhoble
Key Concepts in Apex Testing
● Best Practices:
kshitijdhoble
Code Coverage Considerations
● Positive Testing:
● Negative Testing:
○ These tests are crucial for ensuring that our code fails
gracefully and does not break under unexpected
conditions.
kshitijdhoble
Code Coverage Considerations
● Edge Case Testing:
● Bulk Testing:
kshitijdhoble
Code Coverage Considerations
● Testing All Possible Branches:
kshitijdhoble
Apex Testing Framework
● The Apex testing framework is an integral part of the
Salesforce platform, allowing developers to write and
execute unit tests to ensure the reliability and performance
of their Apex code.
kshitijdhoble
Key Components
a. Test Classes and Methods:
○ Test Class: A class in which us write test methods. It is
annotated with @isTest.
○ Test Method: A method inside a test class that is
responsible for testing a specific piece of functionality.
It is annotated with @isTest or the testMethod
keyword.
// Example
@isTest
public class MyApexTestClass {
@isTest
static void myTestMethod() {
// Test logic here
}
}
kshitijdhoble
Key Components
b. Test Data:
○ Test Data Creation: Salesforce recommends creating
test data within our test methods rather than relying
on existing data in the organization.
○ Test.loadData: Allows loading static test data from a
CSV file.
○ TestSetup Method: A method annotated with
@TestSetup is used to create common test data that
can be shared across multiple test methods in a class.
// Example
@TestSetup
static void setup() {
// Create common test data
}
kshitijdhoble
Key Components
c. Isolation of Test Context:
○ Governor Limits: Test methods have their own set of
governor limits, ensuring that tests do not interfere
with each other.
○ Test.startTest & Test.stopTest: These methods are
used to test asynchronous methods by resetting the
governor limits within a test.
// Example
Test.startTest();
// Execute code to test
Test.stopTest();
kshitijdhoble
Various Annotations & Methods
● In Apex, testing involves writing test classes and methods,
using specific annotations and methods to simulate
different scenarios.
Annotations
kshitijdhoble
Various Annotations & Methods
Methods
○ Test.startTest() & Test.stopTest(): These methods
delineate the start and end of a test block. Any
asynchronous code called between them is executed
synchronously within the test context.
○ System.assert(): To verify conditions in test methods.
○ Test.setMock(): Sets a mock implementation for a
callout. Useful for testing HTTP callouts.
○ Test.isRunningTest(): Checks if the code is running in
a test context.
○ Test.loadData(): Loads data from CSV files into
SObjects for testing.
○ Test.getStandardPricebookId(): Retrieves standard
price book ID for testing.
kshitijdhoble
Running & Monitoring Tests
● Debugging: Use System.debug() statements within test
methods to trace execution and diagnose issues.
kshitijdhoble
Example
● Here's a simple scenario for testing an Apex class related to
the Account object.
● Objective: Verify that an Account record is created with
the correct name, and ensure that the record count in the
system is as expected.
// let's assume an Apex class that creates an Account record.
kshitijdhoble
Example
// Now, we'll write a test class to ensure the createAccount
method in the AccountHandler class works as expected.
@isTest
private class AccountHandlerTest {
@isTest
static void testCreateAccount() {
// Starting a new test context
Test.startTest();
kshitijdhoble
Example
Test.stopTest(); // Ending the test context
kshitijdhoble
Explanation
○ Assertions:
■ System.assertNotEquals(null, acc.Id): Ensures the
account was successfully inserted by checking that
the Id is not null.
■ System.assertEquals('Test Account', acc.Name):
Validates that the account name is as expected.
■ System.assertEquals(1, accountCount): Checks
that only one account exists in the database,
ensuring no other records were created.
kshitijdhoble
Explanation
● We can run this test class in our Salesforce org through the
Developer Console, Setup, or using a Continuous
Integration (CI) tool. The test should pass if the
createAccount method is working correctly.
● If the createAccount method behaves as intended, the test
will pass, confirming that the account creation logic is
functioning correctly. If any assertion fails, it indicates a
potential issue with the method implementation, which
will need to be addressed.
kshitijdhoble
Thank-us!
Stay Tuned & Follow
kshitijdhoble
Day 18
Apex
Security
kshitijdhoble
Apex Security
● Apex security is a critical aspect of developing secure and
robust applications on the Salesforce platform.
kshitijdhoble
Why do we need it?
● Apex security is essential for several reasons:
kshitijdhoble
Why do we need it?
● Compliance With Regulations
kshitijdhoble
Why do we need it?
● Prevention of Security Vulnerabilities
kshitijdhoble
Why do we need it?
● Respecting User Permissions
kshitijdhoble
Why do we need it?
● Preventing Data Breaches:
kshitijdhoble
Why do we need it?
● Ensuring Application Stability:
kshitijdhoble
Why do we need it?
● Maintaining Trust with Users & Customers:
kshitijdhoble
Why do we need it?
● Enabling Secure AppExchange Deployment:
kshitijdhoble
Enforcing CRUD & FLS
● CRUD (Create, Read, Update, Delete):
kshitijdhoble
Sharing Rules & Apex
● Two major types of Sharing rules:
○ Criteria-based Sharing Rules: Grant access to records
based on the values of specific fields.
○ Owner-based Sharing Rules: Grant access to records
based on who owns the record.
● How Sharing Rules works:
○ Default Behavior: OWD settings determine the
baseline level of access to records Sharing rules are
then applied to extend access beyond these defaults.
○ Hierarchy: Sharing rules do not decrease access levels;
they only grant additional access.
kshitijdhoble
Sharing Rules & Apex
● With Sharing and Without Sharing: When writing Apex
classes, the keywords with sharing and without sharing
determine whether the Apex code respects the sharing
rules defined in Salesforce.
● With Sharing: The Apex code respects the sharing rules
and OWD settings of the current user. It ensures that the
code does not access records the user should not see.
● Without Sharing: The Apex code ignores sharing rules and
can access records regardless of the current user’s
permissions. This is typically used when we need to
perform operations that require full access to records, like
administrative tasks.
kshitijdhoble
Sharing Rules & Apex
● Example:
kshitijdhoble
SOQL Injection Prevention
● SOQL Injection is a security vulnerability that occurs when
an attacker manipulates the input to a SOQL query in such
a way that it alters the intended query logic.
● This can lead to unauthorized data access or even data
modification.
● SOQL injection occurs when untrusted user input is
directly used in a SOQL query without proper validation or
sanitization.
● This can allow an attacker to alter the query's structure and
execute unintended commands.
● To prevent SOQL injection, always use bind variables in
your SOQL queries, which safely incorporate user input.
kshitijdhoble
SOQL Injection Prevention
● In this example, the input provided by the user could
manipulate the query to return all Account records instead
of just the intended one.
// Vulnerable code
String userInput = 'test\' OR Name != null OR Name = \'';
kshitijdhoble
SOQL Injection Prevention
● Risks Associated with SOQL Injection:
kshitijdhoble
SOQL Injection Prevention
● Preventing SOQL Injections:
● Use Bind Variables: The most effective way to prevent
SOQL injection is by using bind variables. Bind variables
automatically handle user input safely by escaping any
special characters that could alter the query structure.
● In this example, :userInput is a bind variable, and Salesforce
ensures that the input is treated as a string literal in the
query.
// Secure code using bind variables
String userInput = 'test';
List<Account> accounts = [SELECT Id, Name
FROM Account
WHERE Name = :userInput];
kshitijdhoble
SOQL Injection Prevention
● Strict Input Validation: Ensure that user input is validated
before it is used in a SOQL query. This includes checking
that the input conforms to expected formats and lengths.
// Input validation
String userInput = 'test';
if (userInput.matches('[a-zA-Z0-9]+')) {
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Name = :userInput];
} else {// Handle invalid input}
kshitijdhoble
SOQL Injection Prevention
● Static Queries: Use static SOQL queries wherever possible,
as they are automatically protected against injection
attacks. Example:
// Secure static query
List<Account> accounts = [SELECT Id, Name
FROM Account WHERE Name = 'test'];
kshitijdhoble
SOQL Injection Prevention
● Use Escaping Functions: If dynamic queries are
unavoidable and bind variables cannot be used, use
escaping functions such as String.escapeSingleQuotes() to
sanitize the input. Example:
// Secure dynamic query with escaping
String userInput = 'test';
String safeInput =
String.escapeSingleQuotes(userInput);
String query = 'SELECT Id, Name
FROM Account
WHERE Name = \'' + safeInput + '\'';
List<Account> accounts = Database.query(query);
kshitijdhoble
Data Sanitization
● User Input:
● Sanitization Techniques:
kshitijdhoble
Encryption
● Platform Encryption: Salesforce provides Shield Platform
Encryption for encrypting data at rest. Apex can interact
with encrypted fields, but it's essential to understand the
limitations, such as indexing and searching on encrypted
fields.
kshitijdhoble
Apex Class Security
● Public Access: Ensure that only authorized users or
processes can invoke the Apex classes. Avoid making
classes global unless necessary, as it opens the code to a
wider audience.
kshitijdhoble
Security Review for AppExchange
● If we are developing an app for the Salesforce
AppExchange, it must pass a security review. The review
checks for common vulnerabilities and adherence to
Salesforce's security best practices.
kshitijdhoble
Logging & Monitoring
● Security Monitoring:
● Audit Trail:
kshitijdhoble
Third Party Integrations
● Secure Integrations:
● OAuth:
kshitijdhoble
Best Practices
● Enforce CRUD/FLS: Always check if the user has permission
to access or modify data before doing so in Apex.
kshitijdhoble
Best Practices
● Use Encryption: Protect sensitive data using Platform
Encryption or the Crypto class.
kshitijdhoble
Best Practices
● Handle Errors Safely: Avoid exposing detailed error
messages; handle exceptions gracefully.
kshitijdhoble
Thank-us!
Stay Tuned & Follow
kshitijdhoble