Salesforce Technology

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 72

Chapter - 1

INTRODUCTION

1.1 About the project

The new way of building and running applications are enabled by the world of cloud
computing, where we can access applications, over the Internet as utilities, rather than as
pieces of software running on your desktop or in the server room. This model is already quite
common for consumer apps like email and photo sharing, and for certain business
applications, like customer relationship management (CRM).

The Force.com platform is the world's first Platform as a Service (PaaS), enabling developers
to create and deliver any kind of business application in the cloud, entirely on-demand and
without software. It's a breakthrough new concept that is making companies radically more
successful by letting them translate their ideas into deployed applications in record time.
Building, sharing, and running business applications have never been so easy.
Building and running business applications with traditional software has always been too
complex, slow, and expensive. A new model, called cloud computing, has emerged over the
last decade to address this problem. Applications that run in the cloud are delivered as a
service so companies no longer have to buy and maintain hardware and software to run them.

Salesforce.com pioneered this model with applications business over the last decade. More
recently, Force.com have opened up the infrastructure and made it available for anyone
building any business application and running it on the servers using the Force Platform.

The Force Platform allows you to store structured data, implement business logic with
workflow rules, approval processes and custom code, support Web browsers, integrate with
other applications, do reporting and analytics and scale up or down—all with sub second
response time, high availability, and security you need to run your mission critical business
apps.

1.2 Company Profile

1
Bodacious IT Hub is a Jaipur based company founded by BijendraBhati (popularly known
as Bhati Sir). The company deals in software development and information technology
training both. It deliver products as well as services. It has been developing applications and
providing various services like Corporate Training, IT Consultancy, Software Development
Assistance and IT Outsourcing. Being a pioneer in IT education It always have best of the
brains with it and it is known for providing exceptionally well training to aspirants and using
all the latest technologies. Bodacious IT Hub is a team of talented professionals who
have been working on various types of projects (desktop applications, web applications
and mobile applications) since years using technologies like Java, iOS, Android,
Salesforce, .NET and C++. Bodacious is a renowned name as far as IT Training is
concerned and it also has a team of skilled and experienced professionals who have hands
on experience on different technologies so it always has people seeking its advice and
consultancy. It has been passionately providing consultancy to clients all over the world.

Their trainees have risen to such heights that they have made the name Bodacious IT Hub
synonyms with success in the IT world. Their trainees are working in the leading IT
companies all over the world (Amazon, Google, Facebook etc.) and some of them have got
certificate of excellence wherever they are working. The achievement of Bodacious IT Hub is
consolidated by the fact that they have trainees coming from various parts of world including
USA, CANADA etc. Bodacious IT Hub has produced hundreds of Sun Certified Java
Professionals so far. It is the leading organization that has been involved in preparing
students for online exams.

1.3 Salesforce at Bodacious

Bodacious provide training for Salesforce. It has been divided into two modules.

Their first module is totally intended towards Basics of Platform which helps you to
understand the declarative capabilities of Salesforce. Using which you can develop a fully
functional enterprise app in Salesforce.

2
Second module contains in-depth study of programming capabilities such as Apex,
Visualforce, and SOQL etc. in Salesforce. These capabilities are used to extend the
declarative features provided by Salesforce.

Their first Salesforce batch started on 3rd Jun 2015 that comprised of students of MBM
College of Engineering Jodhpur, JECRC Jaipur and Arya College of Engineering Jaipur. By
the combined efforts of students and faculty all students have become “Salesforce .com
certified Force.com Developers”. They expect more such achievements in the future batches

1.4 Objective

This is an application project for understanding and demonstrating cloud computing


capabilities using Force.com. I use Salesforce build in features to achieve the goal.

The application simulates the functionalities of a Bank

The objective of this application is to develop and deploy an application in the sales force
environment.

This application project must satisfy all type of users and should enable all cloud computing
capabilities.

It is assumed that this application will be developed in the force.com platform

3
Chapter - 2

Cloud Computing

2.1 What is Cloud?

Everyone is talking about “the cloud.” But what does it mean?

More and more, we are seeing technology moving to the cloud. It’s not just a fad — the shift
from traditional software models to the internet has steadily gained momentum over the last
10 years. Looking ahead, the next decade of cloud computing promises new ways to
collaborate everywhere, through mobile devices.

So, what is cloud computing? Essentially, cloud computing is a kind of outsourcing of


computer programs. Using cloud computing, users are able to access software and
applications from wherever they are; the computer programs are being hosted by an outside
party and reside in the cloud. This means that users do not have to worry about things such as
storage and power, they can simply enjoy the end result

Life before cloud computing

Traditional business applications have always been very complicated and expensive. The
amount and variety of hardware and software required to run them are daunting. You need a
whole team of experts to install, configure, test, run, secure, and update them.

When you multiply this effort across dozens or hundreds of apps, it’s easy to see why the
biggest companies with the best IT departments aren’t getting the apps they need. Small and
midsize businesses don’t stand a chance

Cloud computing: a better way

4
With cloud computing, you eliminate those headaches that come with storing your own data,
because you’re not managing hardware and software — that becomes the responsibility of an
experienced vendor like Salesforce. The shared infrastructure means it works like a utility:
You only pay for what you need, upgrades are automatic, and scaling up or down is easy.

Cloud-based apps can be up and running in days or weeks, and they cost less. With a cloud
app, you just open a browser, log in, customize the app, and start using it.

Businesses are running all kinds of apps in the cloud, like customer relationship management
(CRM), HR, accounting, and much more. Some of the world’s largest companies moved their
applications to the cloud with Salesforce after rigorously testing the security and reliability of
our infrastructure.

As cloud computing grows in popularity, thousands of companies are simply rebranding their
non-cloud products and services as “cloud computing.” Always dig deeper when evaluating
cloud offerings and keep in mind that if you have to buy and manage hardware and software,
what you’re looking at isn’t really cloud computing but a false cloud

2.2 Types of cloud computing

Infrastructure as a Service (IaaS)

A third-party hosts element of infrastructure, such as hardware, software, servers, and


storage, also providing backup, security, and maintenance.

Software as a Service (SaaS)

Using the cloud, software such as an internet browser or application is able to become a
usable tool.

5
Platform as a Service (PaaS)

The branch of cloud computing that allows users to develop, run, and manage applications
without having to get caught up in code, storage, infrastructure and so on.

2.3 Benefits of Cloud Computing

Less Costs

The services are free from capital expenditure. There are no huge costs of hardware in cloud
computing. You just have to pay as you operate it and enjoy the model based on your
subscription plan.

24 X 7 Availability

Most of the cloud providers are truly reliable in offering their services, with most of them
maintaining an uptime of 99.9%. The workers can get onto the applications needed basically
from anywhere. Some of the applications even function off-line.

Flexibility in Capacity

It offers flexible facility which could be turned off, up or down as per the circumstances of
the user. For instance, a promotion of sales is very popular, capacity can be immediately and
quickly added to it for the avoidance of losing sales and crashing servers. When those sales
are done, the capacity can also be shrunk for the reduction of costs.

All over Functioning

Cloud computing offers yet another advantage of working from anywhere across the globe, as
long as you have an internet connection. Even while using the critical cloud services that
offer mobile apps, there is no limitation of the device used.

6
Automated Updates on Software

In cloud computing, the server suppliers regularly update your software including the updates
on security, so that you do not need to agonize on wasting your crucial time on maintaining
the system. You find extra time to focus on the important things like ‘How to grow your
businesses.

Security

Cloud computing offers great security when any sensitive data has been lost. As the data is
stored in the system, it can be easily accessed even if something happens to your computer.
You can even remotely wipe out data from the lost machines for avoiding it getting in the
wrong hands.

Carbon Footprint

Cloud computing is helping out organizations to reduce their carbon footprint. Organizations
utilize only the amount of resources they need, which helps them to avoid any over-
provisioning. Hence, no waste of resources and thus energy.

Enhanced Collaboration

Cloud applications enhance collaboration by authorizing diverse groups of people virtually


meet and exchange information with the help of shared storage. Such capability helps in
improving the customer service and product development and also reducing the marketing
time.

Control on the Documents

7
Before cloud came into being, workers needed to send files in and out as the email
attachments for being worked on by a single user at one time ultimately ending up with a
mess of contrary titles, formats, and file content. Moving to cloud computing has facilitated
central file storage.

Easily Manageable

Cloud computing offers simplified and enhanced IT maintenance and management capacities
by agreements backed by SLA, central resource administration and managed infrastructure.
You get to enjoy a basic user interface without any requirement for installation. Plus you are
assured guaranteed and timely management, maintenance, and delivery of the IT services.

Even the few of these advantages of cloud computing might be enough to persuade
businesses to move onto the cloud computing services. But when summed up all of these 10,
it is accosting no-brainer domain.

8
Chapter - 3

APEX

Apex is an object oriented on-demand programming language

Object-Oriented

 Objects are discrete bundle of codes (data and related operations) modeled after things
in the real words

 Classes are the blueprint of an objects

 Objects are the instance of a class

On Demand

 On demand languages are entirely provided by a service provider, and so usually have
minimal requirements to get started

 For example, with client-side applications, you need a compiler or interpreter that has
to run on each client, and have to find a way to install/distribute these components to
other systems

 Most server-side languages are either compiled locally and uploaded, or are scripted,
meaning you have to debug them very manually

 In contrast, on demand languages compile and run "in the cloud," are easily
distributed, and usually requires no more software than what comes standard with
most operating systems (e.g. a web browser)

 'On Demand' means, you can use the tool at any places, irrespective of any machine.
Whenever you want, it will be available

 Functionality that you need available in the cloud, when you need it

 Automatically plugged into other force.com platform features

 It is Java like and build on the force.com platform

9
 It is multi-tenant, scalable, secure, proven, and trusted and running on
salesforce.com servers

 The code you write plugs write into other platform features

 It runs in the cloud so you don’t have to worry about software and hardware

 Your data structure already exists, so you can reference the same sObjects and fields
created through the declarative Setup menu

 Apex is a data focused and it is strongly integrated with data

 Apex is upgraded as a part of salesforce release

 Apex is backward compatible (We can save our apex code against different versions
of Force.com API)

 It has a build in framework for testing and deployment

Traditional Code Vs Apex Code

 Traditional code is fully flexible and tell the system to do anything

 Apex is governed and can only do what the system allows

3.1 Apex vs Java

Commonalities:

 Both have classes, inheritance, polymorphism and other common OOP features

 Both are compiled strongly typed (any invalid reference quickly fails)

 Both are transactional

Differences:

 Apex runs in its multitenant environment and is very controlled by its invocations and
governor limits

10
 Apex is case-insensitive

 Apex is not a general-purpose programming language but it’s the proprietary


language used for specific business logic functions

 Apex requires unit testing for deployment into the production environment

Features not supported by Apex

 No Graphic Library: It can’t show the elements in UI other than error message

 It can’t change the standard SFDC functionalities but can be used to stop its execution
and add new functionalities

 It can’t be used to create temporary files

 It can’t create multiple threads

3.2 How Apex code can be invoked

Fig.3.1.Ways of invoking Apex code

11
3.3 Declarative Tool (Clicks) vs Programmatic Tools (Code)

Before you commit to developing a new feature using programmatic tools such as
Visualforce, consider whether you can implement your feature with declarative tools instead:

Salesforce features built with declarative tools:

 Are usually faster and cheaper to build

 Generally, require less maintenance

 Receive automatic upgrades when the tools are improved

 Aren’t subject to governor limits

Programmatic tools are often required for features that:

 Support specialized or complex business processes

 Provide highly customized user interfaces or customized click-through paths

 Connect to or integrate with third-party systems

Fig.3.2.Force.com Platform

Developer action

When developer writes and save apex code to the platform, the platform app server first
compiles the code that can be understood by apex runtime interpreter and then saves those
instruction as compiled apex

12
End User Action

When the end user performs some actions, which involves the apex code (clicking a button,
accessing a VF Page) the platform app server retrieves the compiled instructions from meta-
data and send them through runtime interpreter before returning the result.

The end user observes no differences in the execution time as compare to the standard app’s
platform request

Declarative Programmatic

Page Layouts, VF Pages,


User Interface
Record Types Lightening Components

Formula Fields,
Apex Controllers,
Business Logic Validation Rules,
Apex Triggers
Workflows and Approvals

Objects, Metadata API, Rest API,


Data Model
Fields and Relationships SOAP API, Bulk API

TABLE 3.1
Declarative tools V/S Programmatic tools

13
Chapter - 4

VISUALFORCE

 Visualforce is a framework that allows developers to build sophisticated, custom user


interfaces

 Visualforce pages are webpages that belong to Salesforce

 These webpages are created using a unique tag-based Mark-up language

 It is similar to HTML

 The page is accessed by using a URL similar to that of a traditional webserver page

 Each tag in visual force language corresponds to some user interface component

 Like section of a page, a list view or a field of an object

 It can be easily mixed up with HTML markup, CSS style and Java libraries, etc.

 A page definition consists of two primary elements:

 Visualforce markup

 A Visualforce controller

VisualForceMarkup:

 Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other


Web-enabled code embedded within a single <apex:page> tag

 The markup defines the user interface components that should be included on the
page, and the way they should appear

VisualForceController:

14
 A Visualforce controller is a set of instructions that specify what happens when a user
interacts with the components specified in associated Visualforce markup

 E.g.: When a user clicks a button or link

 Controllers also provide access to the data that should be displayed in a page, and can
modify component behavior

 A developer can either use a standardcontroller provided by the Lightning platform,


or add customcontroller logic with a class written in Apex

StandardControllers:

 A standard controller consists of the same functionality and logic that is used for a
standard Salesforce page

 For example, if you use the standard Accounts controller, clicking a Save button in a
Visualforce page results in the same behavior as clicking Save on a standard Account
edit page

CustomControllers:

 A custom controller is a class written in Apex that implements all of a page's logic,
without leveraging a standard controller

 If you use a custom controller, you can define new navigation elements or behaviors,
but you must also reimplement any functionality that was already provided in a
standard controller

StandardListControllers:

 A standard list controller enables you to create Visualforce pages that can display or
act on a set of records

 E.g.: List pages, related lists, and mass action pages

15
Extensions:

 A controller extension is a class written in Apex that adds to or overrides behavior in


a standard or custom controller

 Extensions allow you to leverage the functionality of another controller while adding
your own custom logic

Use Of Visualforce Pages

 Override standard buttons, such as New button for accounts, or the Edit for contacts

 Override tab overview pages, such as the Accounts tab home page

 Customize, extend, or integrate the sidebars in the Salesforce console

 Add menu items, actions, and mobile cards in the Salesforce app

4.1 How is Visualforce Architected?

Fig.4.1.Architecture of Visualforce

16
 When a developer finishes writing a Visualforce page and saves it to the platform, the
platform application server attempts to compile the markup into an abstract set of
instructions that can be understood by the Visualforce renderer

 If compilation generates errors, the save is aborted and the errors are returned to the
developer

 Otherwise, the instructions are saved to the metadata repository and sent to the
Visualforce renderer

 The renderer turns the instructions into HTML and then refreshes the developer's view,
thereby providing instantaneous feedback to the developer for whatever changes were
made in the markup

4.2 Advantages:

 User-friendly development

 Integration with other Web-based user interface technologies

 Model-View-Controller (MVC) style development

 Concise syntax

 Data-driven defaults

 Hosted platform

 Automatically upgradeable

Displaying Field Values with Salesforce:

 To access fields from a record that is not globally available, like a specific account,
contact, or custom object record, you need to associate your page with a controller

 Controllers provide pages with the data and business logic that make your application
run, including the logic that specifies how to access a particular object's records

17
 While you can define a custom controller for any page with Apex, Salesforce includes
standard controllers for every standard and custom object

 For example, to use the standard controller for accounts, add the standardController
attribute to the <apex:page> tag, and assign it the name of the account object

<apex:page standardController="Account">

Hello {!$User.FirstName}!

</apex:page>

Overriding Detail View of all Account records with your VF Page

1. From the object management settings for accounts, go to Buttons, Links, and Actions

2. Click Edit next to View

3. In the Salesforce Classic section, select Visualforce page

4. From the Visualforce page drop-down list, select your VF Page

5. Click Save

18
Chapter - 5

SOQL

SOQL stands for Salesforce Object Query Language. It is Similar to SQL. SOQL is used to
fetch the data from the sObject (standard or custom object). Using SOQL, we can also fetch
data from related object child or parent object

Salesforce allows developers to:

 Retrieve rows of data (records), using user defined selection criteria, from objects that
resides in the salesforce database (standard and custom objects)
 Integrate data retrieval into Apex and API

E.g.:

 SELECT ID, Name, Active__c FROM Account


This query will fetch Id, Name Active Fields value for all Account records

 SELECT Name, First_Name__c, Last_Name__c FROM Student__c


This query will fetch Id, Student Id, First Name, Last Name value for all Student
records

5.1 SQL vs SOQL

SOQL queries are similar to SQL queries but they have the following differences:

SQL SOQL

19
Supports statements for DML transaction
Only support SELECT statements
control and embedded SQL

Support SELECT * Does not support SELECT *

Supports joins which are written using “left” Supports “relationship queries”, which are
and “right” table syntax written using parent-child syntax

Do not support dot notation syntax to Supports dot notation syntax to traverse table
traverse table relationship relationship

Are not governed limit Is multi-tenant aware

TABLE 5.1

SQL V/S SOQL

SOQL – Points to remember:

 SOQL queries are case insensitive


 Object Name, Field Name and Relationship name in SOQL queries should be spelled
correctly otherwise we’ll get an ERROR

SOQL Developer Tools:

Force.com
Workbench Setup Developer Console
IDE

Part of
Where A plug in Username>DC>Query
https://workbench.developerforce.com Salesforce
is it? for Eclipse Editor
org

20
View
API
YES YES YES YES
field
names
Point
and
Click YES Yes, but not relationship queries NO NO
Query
Builder

Write
and
Yes, but parent relationship queries
execute YES NO YES
are not enabled by default
ad-hoc
queries

TABLE 5.2
Developer Tools for Visualforce

SOQL Syntax:

SELECT <Field Names> FROM <Object Name>

[WHERE <Conditions>] // Optional

[GROUP BY <Column Names>] // Optional

[HAVING <Conditions>] // Optional

[ORDER BY <Column Names>] // Optional

[FOR UPDATE] // Optional

[LIMIT <No of Records to Return>] // Optional

[OFFSET <Number of records to skip>] // Optional

21
[ALL ROWS] // Optional

SOQL Clauses:

 WHERE
The WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a specified
condition
Ex:
Write a query to fetch all Account records whose industry is ‘Energy’
[SELECT Name, Industry, Phone FROM Account WHERE Industry='Energy']

Write a query to fetch all Case records whose origin is ‘Email’ or ‘Phone’
[SELECT Status, Priority FROM Case WHERE Origin='Email' OR Origin='Phone']

Write a query to fetch all Opportunity records whose stage is ‘closed won’ and
amount is greater than 50000
[SELECT Name, StageName, Amount FROM Opportunity WHERE
StageName='Closed Won' AND Amount>50000]

Note:
Using string comparision for Id field in WHERE (=) Clause is allowed, but at runtime
string is verified to be valid id
List<Account> acc1 = [SELECT Name, Industry FROM Account WHERE Id =
'0016F00002bFdKp'];
List<Account> acc2 = [SELECT Name, Industry FROM Account WHERE Id =
'Hello'];
The second query will give you an exception

22
 GROUP BY
The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns
Ex:
Write a query to fetch the Sum of Amount of Opportunity records stagewise
[SELECT SUM(Amount) FROM Opportunity GROUP BY StageName ORDER BY
StageName]

 HAVING
The HAVING clause was added to SOQL because the WHERE keyword could not be
used with aggregate functions
Write a query to fetch the Sum of Amount of Opportunity records whose sum of
amount > 5000 stagewise
[SELECT SUM(Amount) FROM Opportunity GROUP BY StageName HAVING
Sum(Amount)>5000]

Write a query to fetch the Sum of Amount of Opportunity records whose stage name
is ‘closed won’
[SELECT SUM(Amount) FROM Opportunity GROUP BY StageName HAVING
StageName='Closed Won']

 ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword
Ex:
Write a query to fetch all the accounts records where the latest created should be at
the top
[SELECT Name, Industry FROM Account ORDER BY CreatedDate DESC]

23
Write the query to fetch all opportunity, sort them by name in ascending order
[SELECT Name, StageName, Amount FROM Opportunity ORDER BY Name]

Write a query to fetch top 5 students of Harward college


[SELECT First_Name__c, Last_Name__c, Average_Percentage__c FROM
Student__c WHERE College__r.Name='Harvard' ORDER BY
Average_Percentage__c DESC LIMIT 5]

 FOR UPDATE
FOR UPDATE Clause will lock the record from getting updated for a transaction
Apex Trasaction:
 An Apex transaction represents a set of operations that are executed as a single
unit
 All DML operations in a transaction either complete successfully, or if an
error occurs in one operation, the entire transaction is rolled back and no data
is committed to the database
 The boundary of a transaction can be a trigger, a class method, an anonymous
block of code, a Visualforce page, or a custom Web service method
 In the below sample timeline, the lock won't be released until
METHOD_EXIT

METHOD_ENTRY Lock update triggers complete METHOD_EXIT


lock released

|-------------------|----------|-----------------|---------------------------|------------|

Child Transaction

Ex:
[SELECT Id FROM Account LIMIT 2 FOR UPDATE];

 LIMIT
The LIMIT clause is used to specify the number of records to return
The LIMIT clause is useful on large objects with thousands of records

24
Returning a large number of records can impact on performance
LIMIT clause is mostly placed last in the query (except if query contains OFFSET
clause or ALL ROWS clause)
Ex:
Write a query to fetch one account record from account object
[SELECT Name, Industry, Rating FROM Account LIMIT 1]

Write a query to fetch 5 Cases which are not closed


[SELECT CaseNumber, Status, Origin FROM Case WHERE isClosed=false LIMIT
5]

 OFFSET
OFFSET is used to specify how many records to skip before returning
Use OFFSET to specify the starting row offset into the result set returned by your
query. Because the offset calculation is done on the server and only the result subset is
returned, using OFFSET is more efficient than retrieving the full result set and then
filtering the results locally
The maximum offset is 2,000 rows. Requesting an offset greater than 2,000 results in
a NUMBER_OUTSIDE_VALID_RANGE error
Ex:
Write a query to fetch all Account records skipping 5 Account records
[SELECT Name FROM Account OFFSET 5]

Write a query to fetch the second last created Contact record


[SELECT FirstName, LastName FROM Contact ORDER BY CreatedDate DESC
LIMIT 1 OFFSET 1]

 ALL ROWS
ALL ROWS Clause is used to fetch all the records from the object including the
recycle bin
ALL ROWS Clause may not work in query editor

25
Ex:
Write a query to fetch all records of Case including those which were deleted under
15 days
[SELECT Status, Priority FROM Case ALL ROWS]

 LIKE
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards used in conjunction with the LIKE operator:
% - The percent sign represents zero, one, or multiple characters
_ - The underscore represents a single character
Ex:
Write a query to fetch all Contact records whose last name ends with s
[SELECT FirstName, LastName, Email FROM Contact WHERE LastName LIKE
‘%s’]

Write a query to fetch all Opportunity recoords whose name contains ‘salesforce’
[SELECT Name, StageName, Amount FROM Opportunity WHERE Name LIKE
‘%salesforce%’]

Write a query to fetch all contacts whose phone number is like 70X432X4x7 where X
is any single digit

[SELECT FirstName, LastName, Phone FROM Contact WHERE Phone LIKE


‘70_432_4_7’];

Note:

Using String with Id field in Like clause gives Compile time error

List<Account> acc3 = [SELECT Name, Industry FROM Account

WHERE Id LIKE '0016F00002bFdKp'];

26
List<Account> acc4 = [SELECT Name, Industry FROM Account WHERE Id LIKE
'Hello'];

The above two queries give CE:

5.2 Date Formats and Date Literals

 In a SOQL query you can specify either a particular date or a date literal

 A date literal is a fixed expression that represents a relative range of time, such as last
month, this week, or next year

 DateTime field values are stored as Coordinated Universal Time (UTC)

 When a dateTime value is returned in Salesforce, it’s adjusted for the time zone
specified in your org preferences

 SOQL queries, however, return DateTime field values as UTC values

 If you want to process these values in different time zones, your application might
need to handle the conversion

Date Formats

 A fieldExpression uses different date formats for date and dateTime fields

 If you specify a dateTime format in a query, you can filter only on dateTime fields

 Similarly, if you specify a date format value, you can filter only on date fields

Format Format Syntax Example

27
Date only YYYY-MM-DD 1999-01-01

 YYYY-MM-  1999-01-
DDThh:mm:ss+hh:mm 01T23:01:01+01:00
Date, time, and
 YYYY-MM-DDThh:mm:ss-  1999-01-01T23:01:01-
time zone offset
hh:mm 08:00

 YYYY-MM-DDThh:mm:ssZ  1999-01-01T23:01:01Z

TABLE 4.3

Date Formats

Note: For a fieldExpression that uses date formats, the date is not enclosed in single quotes.
Don’t use quotes around the date. For example

 List<Account> acc = [SELECT IdFROM AccountWHERE CreatedDate < 2018-11-


14T01:02:03Z];

 List<Account> acc = [SELECT IdFROM AccountWHERE CreatedDate <‘2018-11-


14T01:02:03Z’];

ERROR: value of filter criterion for field 'CreatedDate' must be of type dateTime and should
not be enclosed in quotes

1. //List<Account> l1 = [SELECT Id FROM Account WHERE CreatedDate < 2018-11-


14];
2. List<Account> l2 = [SELECT Id FROM Account WHERE CreatedDate < 2018-11-
14T01:02:03Z];
3. List<Opportunity> l3 = [SELECT Id FROM Opportunity WHERE CloseDate < 2018-
11-14];
4. //List<Opportunity> l4 = [SELECT Id FROM Opportunity WHERE CloseDate < 201
8-11-14T01:02:03Z];

Line 1 - value of filter criterion for field 'CreatedDate' must be of type dateTime and should
not be enclosed in quotes

Line 4 - value of filter criterion for field 'CloseDate' must be of type date and should not be
enclosed in quotes

28
Date Literals

 A fieldExpression can use a date literal to compare a range of values to the value in a
date or dateTime field

 Each literal is a range of time beginning with midnight (00:00:00)

 To find a value within the range, use =

 To find values on either side of the range, use > or <

Ex:

1. List<Account> a = [SELECT Name FROM Account WHERE CreatedDate = TODA


Y];
2. System.debug(a);

Output: (Account:{Name=TodayAccount, Id=0016F00002zLXdWQAW})

Minimum and Maximum Dates

 Only dates within a certain range are valid


 The earliest valid date is 1700-01-01T00:00:00Z GMT, or just after midnight on
January 1, 1700
 The latest valid date is 4000-12-31T00:00:00Z GMT, or just after midnight on
December 31, 4000
 These values are offset by your time zone
 For example, in the Pacific time zone, the earliest valid date is 1699-12-31T16:00:00,
or 4:00 PM on December 31, 1699

Aggregate Functions in SOQL

 An aggregate function allows you to perform a calculation on a set of values to return


a single scalar value

29
 We often use aggregate functions with the GROUP BY and HAVING clauses of the
SELECT statement
 Use aggregate functions in a GROUP BY clause in SOQL queries to generate reports
for analysis
 You can also use aggregate functions without using a GROUP BY clause. Fx:
SELECT AVG(Amount)FROM Opportunity
 However, these functions become a more powerful tool to generate reports when you
use them with a GROUP BY clause
 For example, you could find the average Amount for all your opportunities by
campaign
SELECT CampaignId, AVG(Amount) FROM OpportunityGROUP BY CampaignId

Syntax:

SELECT FROM <Object


Name>

AVG(FieldName) // List<AggregateResult> // OR

COUNT() // Integer // OR

COUNT(FieldName) // List<AggregateResult> // OR

COUNT_DISTINCT(FieldName) // List<AggregateResult> // OR

MIN(FieldName) // List<AggregateResult> // OR

MAX(FieldName) // List<AggregateResult> // OR

SUM(FieldName) // List<AggregateResult> // OR

AVG - Returns the average value of a numeric field

COUNT - Returns the number of rows matching the query criteria

30
COUNT_DISTINCT - Returns the number of distinct non-null field values matching the
query criteria

MIN - Returns the minimum value of a field

MAX - Returns the maximum value of a field

SUM - Returns the total sum of a numeric field

Note: If you are using a GROUP BY clause, use COUNT(fieldName) instead of COUNT()

COUNT(Id) in SOQL is equivalent to COUNT(*) in SQL

5.3 Relationship Queries


 Client applications need to be able to query for more than a single type of object at a
time

 SOQL provides syntax to support these types of queries, called relationship queries,
against standard objects and custom objects

 Relationship queries traverse parent-to-child and child-to-parent relationships


between objects to filter and return results

 Relationship queries are similar to SQL joins

 However, you cannot perform arbitrary SQL joins. The relationship queries in SOQL
must traverse a valid relationship path

 You can use relationship queries to return objects of one type based on criteria that
applies to objects of another type, For example:

“Return all accounts created by Bob Jones and the contacts associated with those
accounts”

 There must be a parent-to-child or child-to-parent relationship connecting the objects

 You can’t write arbitrary queries such as:

31
“Return all Opportunities and Tests created by Bob Jones”

“Return all Accounts and Users created by Bob Jones”

In order to write relationship queries, we need to understand three things:

 Types of join in SOQL

 Relationship Names – Parent-to-Child and Child-to-Parent

 Dot(.) Notation and Nested SOQL, when to use what

Types of Join in SOQL:

Fig.5.1 Types of Joins in SOQL

Relationship Names:

32
Fig.5.2 Relationship Names

Dot(.) Notation and Nested SOQL: When to use what:

Fig.5.3 Use Of Dot Notation

Right Outer Join (Child to Parent)

For Standard Object:

33
SELECT ID, Name, FirstName, LastName, Account.Name, Account.Industry

FROM Contact

For Custom Object:

SELECT ID, Name, Fees__c, Faculty__r.Name

FROM Course__c

Left Outer Join (Parent to Child)

For Standard Object:

SELECT ID, Name, Industry, (SELECT ID, Name, FirstName, LastName

FROM Contacts)

FROM Account

For Custom Object:

SELECT ID, Name, Experience__c, (SELECT ID, Name, Fees__c

FROM Courses__r)

FROM Faculty__c

34
Right Inner Join (Child to Parent)

For Standard Object:

SELECT ID, Name, FirstName, LastName, Account.Name, Account.Industry

FROM Contact WHERE AccountID != null

For Custom Object:

SELECT ID, Name, Fees__c, Faculty__r.Name

FROM Course__c WHERE Faculty__c != null

Left inner Join (Parent to Child)

For Standard Object:

SELECT ID, Name, Industry, (SELECT ID, Name, FirstName, LastName

FROM Contacts)

FROM Account

35
WHERE ID IN (SELECT AccountID

FROM Contact)

For Custom Object:

SELECT ID, Name, Experience__c, (SELECT ID, Name, Fees__c

FROM Courses__r)

FROM Faculty__c

WHERE ID IN (SELECT Faculty__c

FROM Course__c)

Right Anti Join (Child to Parent)

For Standard Object:

SELECT ID, Name, FirstName, LastName

FROM Contact WHERE AccountID = null

For Custom Object:

SELECT ID, Name, Fees__c

FROM Course__c WHERE Faculty__c = null

36
Left Anti Join (Parent to Child)

For Standard Object:

SELECT ID, Name, Industry

FROM Account

WHERE ID NOT IN (SELECT AccountID

FROM Contact)

For Custom Object:

SELECT ID, Name, Experience__c

FROM Faculty__c

WHERE ID NOT IN (SELECT Faculty__c

FROM Course__c)

37
Chapter - 6

DML

Salesforce Apex DML (Data Manipulation Language) statements are used to Insert, Update,
Merge, Delete and restore data in Salesforce. We can perform DML operations using the
Apex DML statements or the methods of the Database class.

We can perform 6 DML operations they are:

 insert  upsert

 update  merge

 delete  undelete

insert DML statements

The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to
your organization’s data

insert sObject

insert sObject[]

1. Account a = new Account(Name='Acme');


2. insert a;
3. List<Account> acc = [SELECT Name FROM Account WHERE Name='Acme'];
4. System.assertEquals(1, acc.size());

1. List<Account> acc = new List<Account>{new Account(Name='Honeywell')};


2. acc.add(new Account(Name='LivCorp'));
3. insert acc;

38
update DML statements

The update DML operation modifies one or more existing sObject records, such as individual
accounts or contacts, invoice statements, in your organization’s data

update sObject

update sObject[]

1. insert new Account(Name='Acme');


2. Account a = [SELECT Name FROM Account WHERE Name='Acme'];
3. a.Name = 'Acme Corporation';
4. update a;
5. List<Account> acc = [SELECT Name FROM Account WHERE Name = 'Acme Corporation'
];
6. System.assertEquals(1, acc.size());
7. acc = [SELECT Name FROM Account WHERE Name = 'Acme'];
8. System.assertEquals(0, acc.size());

1. insert new List<Account>{new Account(Name='Honeywell'), new Account(Name='LivCorp


')};
2. List<Account> acc = [SELECT Name FROM Account WHERE Name IN ('Honeywell', 'Liv
Corp')];
3. for(Account a: acc){
4. a.Name = a.Name+'-Updated';
5. }
6. update acc;
7. System.assertEquals(2, [SELECT Name FROM Account WHERE Name LIKE '%-
Updated'].size());

delete DML statements

The delete DML operation deletes one or more existing sObject records, such as individual accounts
or contacts, from your organization’s data

delete sObject

delete sObject[]

1. insert new Account(Name='Acme'


2. Account a = [SELECT Name FROM Account WHERE Name LIKE 'Acme%'];
39
3. delete a;
4. System.assertEquals(0, [SELECT Name FROM Account WHERE Name LIKE 'Acme%'].siz
e());

1. insert new List<Account>{new Account(Name='Honeywell'), new Account(Name='LivCorp


')};
2. List<Account> acc = [SELECT Name FROM Account WHERE CreatedDate = TODAY];
3. delete acc;
4. System.assertEquals(0, [SELECT Name FROM Account WHERE CreatedDate = TODAY].
size());

upsert DML statements

The upsert DML operation creates new records and updates sObject records within a single
statement, using a specified field to determine the presence of existing objects, or the ID field if no
field is specified

upsert sObject [opt_field]

upsert sObject[] [opt_field]

Note: You need to create an external id field named MyField (MyField__C) of Number type on
Account Object before executing the following programs:

1. insert new Account(Name='Demo-1', MyField__c=100);


2. Account a1 = new Account(Name='Demo-2', MyField__C=100);
3. upsert a1 MyField__c;
4. Account a2 = new Account(Name='Demo-3', MyField__C=100);
5. upsert a2;
6. for(Account a: [SELECT Name FROM Account WHERE Name LIKE 'Demo%']){
7. System.debug(a.Name);
8. }

Output:
Demo-2
Demo-3

40
1. List<Account> l1 = new List<Account>{new Account(Name = 'Account-
1', MyField__c = 1200),
2. new Account(Name = 'Account-2', MyField__c = 1300)};
3. insert l1;
4. List<Account> l2 = new List<Account>{new Account(Name = 'Account-
3', MyField__c = 1200),
5. new Account(Name = 'Account-4', MyField__c = 1600)};
6. upsert l2 MyField__c;
7.
8. for(Account a: [SELECT Name FROM Account WHERE Name LIKE 'Account%']){
9. System.debug(a.Name);
10. }

Output:
Account-3
Account-2
Account-4

Upsert uses records id or external id field to determine whether it should create a new record or
update an existing record

1. If the key is not matched, a new object is created

2. If the key is matched once , an existing object is updated

3. If the key is matched more than once , an error is generated and the object record is neither
inserted nor updated

Note:

 The upsert statement matches the sObjects with existing records by comparing values of one
field

 If you don’t specify a field when calling this statement, the upsert statement uses the
sObject’s ID to match the sObject with existing records in Salesforce

41
 Alternatively, you can specify a field to use for matching. For custom objects, specify a
custom field marked as external ID

 For standard objects, you can specify any field that has the idLookup attribute set to true

 For example, the Email field of Contact or User has the idLookup attribute set

 Also, you can use foreign keys to upsert sObject records if they have been set as reference
fields

 The optional field parameter, opt_field, is a field token (of type Schema.SObjectField)

 For example, to specify the MyExternalID custom field, the statement is

upsert sObjectList Account.Fields.MyExternalId__c;

undelete DML statements

The undelete DML operation restores one or more existing sObject records, such as individual
accounts or contacts, from your organization’s Recycle Bin

undelete sObject

undelete sObject[]

undelete ID

undelete ID[]

1. Account a=[SELECT Name FROM Account WHERE isDeleted=true AND Name LIKE 'Ac
me%' LIMIT 1 ALL ROWS];
2. Undelete a;
3. System.assertEquals(1, [SELECT Name FROM Account WHERE Name LIKE 'Acme%'].siz
e());

1. List<Account> a = new List<Account>{new Account(Name = 'Sample1'), new Account(Na


me = 'Sample2')};
2. insert a; delete a;
3. List<Account> acc = [SELECT Name FROM Account WHERE isDeleted=true AND Name
LIKE 'Sample%' ALL ROWS];
4. Undelete acc;

42
5. System.assertEquals(0, [SELECT Name FROM Account WHERE isDeleted=true AND Na
me LIKE 'Sample%' ALL ROWS].size());
6. System.assertEquals(2, [SELECT Name FROM Account WHERE Name LIKE 'Sample%' ].s
ize());

merge DML statements

The merge statement merges up to three records of the same sObject type into one of the records,
deleting the others, and re-parenting any related records

merge sObject sObject

merge sObject sObject[]

merge sObject ID

merge sObject ID[]

1. List<Account> l = new List<Account>{new Account(Name = 'Acme'),


2. new Account(Name = 'Acme Inc', NumberOfEmployees = 1200)};
3. insert l;
4. Account a = l[0];
5. l.remove(0);
6. merge a l;
7. for(Account acc: [SELECT Name, NumberOfEmployees FROM Account WHERE Name L
IKE 'Acme%']){
8. System.debug(acc.Name + ' - ' + acc.NumberOfEmployees);
9. }
Output:
Acme - null

The first parameter represent master record into which the other records are to be merged

The second parameter represent one or two records that should be merged and than deleted

We can pass these other records as single sObject record or list of two sObject record, ID or list of
ID

How merge works:

1. Place the three records into a list. The "surviving" record should be in index 0

43
2. Move any field data from the records in index 1 and/or 2, either through custom logic or user
intervention

3. Call the Merge statement, passing it the list of up to 3 records

4. The record in index 0 will have the new data, while the records in the other two indices will
be deleted

Note:

 Only leads, contacts, and accounts can be merged

 You can pass a master record and up to two additional sObject records to a single merge
method

 Using the Apex merge operation, field values on the master record always supersede the
corresponding field values on the records to be merged

 To preserve a merged record field value, simply set this field value on the master sObject
before performing the merge

 External ID fields can’t be used with merge

6.1 sObject that don’t support DML:

 AccountTerritoryAssignmentRule

 AccountTerritoryAssignmentRuleItem

 ApexComponent

 ApexPage

 BusinessHours

 BusinessProcess

 CategoryNode

 CurrencyType

44
 DatedConversionRate

 NetworkMember (allows update only)

45
Chapter - 7

TRIGGERS

A trigger is a feature of the Salesforce platform consisting of Apex code that executes before or after
DML operations

Apex can be invoked by using triggers. Apex triggers enable you to perform custom actions before
or after changes to Salesforce records

A trigger is Apex code that executes before or after the following types of operations:

 insert

 update

 delete

 undelete

For example, you can have a trigger run before an object's records are inserted into the database,
after records have been updated, before a record is deleted, or even after a record is restored from the
Recycle Bin

Fig.7.1 What,When,Why Trigger

46
More Definition of Triggers

 Trigger in Salesforce are programmatic event handlers which is an apex code that gets
executed when a record is saved.

 ApexTrigger is an object, where for each trigger we have written, salesforce will create a
record in ApexTrigger object

 Trigger is also a class which consists of 12 static variables known as Trigger Context
Variables. Use the Trigger class to access run-time context information in a trigger, such as
the type of trigger or the list of sObject records that the trigger operates on

 Apex Triggers execute on server side not on client side

 Trigger can handle DML Operation, execute SOQL and call custom apex methods

When to use Triggers

Apex Triggers are used when the requirement is not fulfilled by declarative operations such as
workflow, process builder etc.

As a best practice always look for declarative approach

As a practice go for the following in sequence:

1. Workflows

2. Flows

3. Process builder

4. Apex Triggers

7.1 Classification of Triggers

Before Trigger:

Before triggers are ones that get executed before the record is saved to the database

After Trigger:

After triggers are ones that get executed after the record is saved to the database

47
Usage of Before Triggers

 Can be used to perform validations and stop the creation / updation / deletion of records if
they are not satisfying the criteria.
 Data can be modified in before triggers only, hence record field auto population by the
system can be performed here

Usage of After Triggers

 By the time these triggers execute the record ID and the system generated fields such as
created by, modified by etc. are generated by the system and these fields such as ID can be
used to build relationships i.e. create relationship records
 These triggers are used access the fields values that are created by system (Ex: CreatedBy,
LastModifiedBy , Record Id etc.)

Note:

 Most of the Triggers we use are Before Triggers


 They’re simpler to use
 If you need to make any changes to a record entering your after trigger, you have to do a
DML statement
 This isn’t necessary in a before trigger – changes to records entering your trigger always
save!

7.2 DML Events for Triggers:

48
Fig.7.2.Dml Events For Trigger

Before Insert: Trigger that executes due to an insert operation and before the record is saved to the
database it is a before Insert trigger

BeforeUpdate: Trigger that executes due to an update operation and before the record is saved to the
database it is a before update trigger

BeforeDelete: Trigger that executes due to a delete operation and before the record is saved to the
database it is a before delete trigger

AfterInsert: Trigger that executes due to an insert operation but after the record is saved to the
database it is an after Insert trigger

AfterUpdate: Trigger that executes due to an update operation and after the record is saved to the
database it is an after update trigger

AfterDelete: Trigger that executes due to a delete operation and after the record is deleted from the
database it is an after delete trigger

AfterUndelete: Trigger that executes due to a undelete operation and after the record is undeleted
from the database it is an after undelete trigger

Note: Why Before Undelete is not a trigger event

 There is no Before Undelete because there will be no record available before Undelete to
update. But After Undelete you will be having a record to update something with that record
49
 Also if the record has the field isDeleted set to True, standard security make sure that these
records are not visible, either via the UI or Apex, so an undelete trigger wouldn't be able to
see the records that it needs

Context Variable of Triggers

VARIABLES USAGE

Returns true if the current context for the Apex code is a


isExecuting trigger, not a Visualforce page, a Web service, or an execute
anonymous() API call

Returns true if this trigger was fired due to an insert operation,


isInsert
from the Salesforce user interface, Apex, or the API

Returns true if this trigger was fired due to an update operation,


isUpdate
from the Salesforce user interface, Apex, or the API

Returns true if this trigger was fired due to a delete operation,


isDelete
from the Salesforce user interface, Apex, or the API

Returns true if this trigger was fired before any record was
isBefore
saved

isAfter Returns true if this trigger was fired after any record was saved

Returns true if this trigger was fired after a record is recovered


isUndelete from the Recycle Bin (that is, after an undelete operation from
the Salesforce user interface, Apex, or theAPI)

new Returns a list of the new versions of the sObject records

newMap A map of IDs to the new versions of the sObject records

50
old Returns a list of the old versions of the sObject records

oldMap A map of IDs to the old versions of the sObject records

The total number of records in a trigger invocation, both old


size
and new
TABLE 7.1

Context variables in Trigger

Trigger
Trigger.Old Trigger.New Trigger.OldMap Trigger.NewMap
Event
Before Insert    
AfterInsert    
Before  
 
Update
After Update    
Before Delete    
After Delete    
After  
 
Undelete
TABLE 7.2

Occurance of Events with respect to trigger type

51
Chapter - 8

WEBSERVICES

 Web service is a client server application or application component for communication

 Piece of software that makes itself available over the Internet or private (intranet) networks

 Is not tied to any one operating system or programming language

 Web service is a method of communication between two devices over network

 Web service is a software system for interoperable machine to machine communication

 Web service is a collection of standards or protocols for exchanging information between two
devices or application

 Uses a standardized XML messaging system

 Is self-describing via a common XML grammar

 Is discoverable via a simple find mechanism

Fig.8.1. Web Services

8.1 Components of web services:

Web service platform = XML (Extensible Markup Language) + HTTP (Hyper Text Markup
Language)

All the standard web services work using the following components −
52
 SOAP (Simple Object Access Protocol)
 UDDI (Universal Description, Discovery and Integration)
 WSDL (Web Services Description Language)

Protocol vs Achitecture Style:

A protocol defines what type of conversation can take place between two components of a
distributed application, by specifying messages, data types, encoding formats and so on

An architectural style is a coordinated set of architectural constraints that restricts the roles/features
of architectural elements and the allowed relationships among those elements within any architecture
that conforms to that style

8.2 How webservice works?

A web service enables communication among various applications by using open standards such as
HTML, XML, WSDL, and SOAP. A web service takes the help of −

 XML to tag the data

 SOAP to transfer a message

 WSDL to describe the availability of service

The steps to perform this operation are as follows −

 The client program bundles the account registration information into a SOAP message.

 This SOAP message is sent to the web service as the body of an HTTP POST request.

 The web service unpacks the SOAP request and converts it into a command that the
application can understand.

 The application processes the information as required and responds with a new unique
account number for that customer.

 Next, the web service packages the response into another SOAP message, which it sends
back to the client program in response to its HTTP request.

 The client program unpacks the SOAP message to obtain the results of the account
registration process
53
Types of Webservices:

There are mainly two types of web services.

1. SOAP web services


2. RESTful web services

SOAP

 SOAP stands for Simple Object Access Protocol

 It is a XML-based protocol for accessing web services

Advantages:

 WS Security

 Language Independent

 Platform Independent

Disadvantages:

 Slow

 WSDL Dependent

REST

 REST stands for REpresentational State Transfer

 It is a architectural style

 It is not a protocol like SOAP


54
8.3 Advantages:

 Fast

 Language Independent

 Platform Independent

 Can use SOAP

 Allows different data format

SOAP vs REST

No. SOAP REST

1) SOAP is a protocol REST is an architectural style

SOAP stands for Simple Object Access REST stands for REpresentational State
2)
Protocol Transfer

REST can use SOAP web services because it is


SOAP can't use REST because it is a
3) a concept and can use any protocol like HTTP,
protocol
SOA.

SOAP uses services interfaces to expose


4) REST uses URI to expose business logic
the business logic

JAX-WS is the java API for SOAP web JAX-RS is the java API for RESTful web
5)
services services

SOAP defines standards to be strictly REST does not define too much standards like
6)
followed SOAP

SOAP requires more bandwidth and REST requires less bandwidth and resource than
7)
resource than REST SOAP

RESTful web services inherits security


8) SOAP defines its own security
measures from the underlying transport

55
REST permits different data format such as
9) SOAP permits XML data format only
Plain text, HTML, XML, JSON etc

10) SOAP is less preferred than REST REST more preferred than SOAP

TABLE 8.1

SOAP V/s REST API

Advantage of Webservices

 Interoperability: By the help of web services, an application can communicate with other
application developed in any language

 Reusability: We can expose the web service so that other applications can use it

 Modularity: By the help of web service, we can create a service for a specific task such as
tax calculation etc

REST

REST callouts are based on HTTP. To understand how callouts work, it’s helpful to understand a
few things about HTTP. Each callout request is associated with an HTTP method and an endpoint.
The HTTP method indicates what type of action is desired

Fig.8.2 REST

The simplest request is a GET request (GET is an HTTP method). A GET request means that the
sender wants to obtain information about a resource from the server. When the server receives and
processes this request, it returns the request information to the recipient. A GET request is similar to
navigating to an address in the browser. When you visit a web page, the browser performs a GET
56
request behind the scenes. In the browser, the result of the navigation is a new HTML page that’s
displayed. With a callout, the result is the response object

TABLE 8.2

Some Common Http Method

The simplest request is a GET request (GET is an HTTP method). A GET request means that the
sender wants to obtain information about a resource from the server. When the server receives and
processes this request, it returns the request information to the recipient. A GET request is similar to
navigating to an address in the browser. When you visit a web page, the browser performs a GET
request behind the scenes. In the browser, the result of the navigation is a new HTML page that’s
displayed. With a callout, the result is the response object

Table 8.3
Annotations

57
Chapter - 9

ASYNCHRONOUS APEX

In Computer program asynchronous operation means that a process operates independent of other
processes

 Synchronous

 Immediate and fast actions

 Enforce single, serial, transactions

 Normal governor limits

 Asynchronous

 Actions that should not block the rest of the process

 Processes where duration is of lesser concern

 Higher governor limits

Fig.9.1. Sync and Async Process

Asynchronous Apex is used to run processes in a separate thread, at a later time

An asynchronous process is a process or function that executes a task "in the background" without
the user having to wait for the task to finish
58
User efficiency

With asynchronous processing the user can get on with their work, the processing can be done in the
background and the user can see the results at their convenience.

Scalability

By allowing some features of the platform to execute when resources become available at some point
in the future, resources can be managed and scaled quickly. This allows the platform to handle more
jobs using parallel processing

Higher Limits

Asynchronous processes are started in a new thread, with higher governor and execution limits

9.1 Types of Async Apex

Type Overview Common Scenarios

Future Methods Run in their own thread, and do not Web service callout.
start until resources are available.

Batch Apex Run large jobs that would exceed Data cleansing or archiving of
normal processing limits. records.

Queueable Apex Similar to future methods, but provide Performing sequential processing
additional job chaining and allow more operations with external Web
complex data types to be used. services.

Scheduled Apex Schedule Apex to run at a specified Daily or weekly tasks.


time.

Table 9.1

Type of Async Apex

Note: These different types of asynchronous operations are not mutually exclusive. For instance, a
common pattern is to kick off a Batch Apex job from a Scheduled Apex job
59
Increased Governor and Execution Limits

One of the main benefits of running asynchronous Apex is higher governor and execution limits

For example, the number of SOQL queries is doubled from 100 to 200 queries when using
asynchronous calls

The total heap size and maximum CPU time are similarly larger for asynchronous calls

Those governor limits are independent of the limits in the synchronous request that queued the async
request initially

Essentially, you have two separate Apex invocations, and more than double the processing capability

9.2 How Asynchronous Processing Works

The platform uses a queue-based asynchronous processing framework. This framework is used to
manage asynchronous requests for multiple organizations within each instance. The request lifecycle
is made up of three parts:

Enqueue

The request gets put into the queue. This could be an Apex batch request, future Apex request or one
of many others. The platform will enqueue requests along with the appropriate data to process that
request.

Persistence

The enqueued request is persisted. Requests are stored in persistent storage for failure recovery and
to provide transactional capabilities.

Dequeue

The enqueued request is removed from the queue and processed. Transaction management occurs in
this step to assure messages are not lost if there is a processing failure

60
The queue contains requests from multiple organizations. Each request can be associated with a job
that could vary in complexity and running time

As one request is completed, another request is removed from the queue and processed. Error
handling and failure recovery is built in (via request persistence) so the requests are not lost if a
queue failure or handler failure occurs

Ex:

13 Threads are available to process request

12 Threads can process request from one organization

Peak Set Size = 15

Org1 – 13 @ftr request

Org2 – 2 @ftr request

Org1 - 2@ftr request

Fig.9.2.Async Queue Store

61
Fig 9.3. Enqueue and Dequeue

Fig.9.4 Allocations of Queue

62
Fig 9.5 Peak Set

Since all of the requests in the peek set are from a single organization (organization 1), those 15
requests will be moved to the back of the queue with a specific delay. This is called an extended
delay.
63
The delay is different for each message. For example, for @future requests, the delay is 5 minutes.
That means a minimum of 5 minutes must elapse before those requests are eligible for processing.

When delayed requests become eligible for processing, it's possible for these requests to be acted
upon by flow control and again get moved to the back of the queue and delayed

Resource Conservation

Asynchronous processing has lower priority than real-time interaction via the browser and API

To ensure there are sufficient resources to handle an increase in computing resources, the queuing
framework monitors system resources such as server memory and CPU usage and reduce
asynchronous processing when thresholds are exceeded

This is a fancy way of saying that the multitenant system protects itself. If an org tries to “gobble up”
more than its share of resources, asynchronous processing is suspended until a normal threshold is
reached

The long and short of it is that there’s no guarantee on processing time, but it’ll all work out in the
end

64
Chapter - 10

GOVERNOR LIMIT

Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces limits to
ensure that runaway Apex code or processes don’t monopolize shared resources. If some Apex code
exceeds a limit, the associated governor issues a runtime exception that cannot be handled

10.1 Per Transaction Limits

These limits count for each Apex transaction. For Batch Apex, these limits are reset for each
execution of a batch of records in the execute method.

Description Synchronous Asynchronous


Limit Limit

Total number of SOQL queries issued1 100 200

Total number of records retrieved by SOQL queries 50,000

Total number of records retrieved 10,000


by Database.getQueryLocator

Total number of SOSL queries issued 20

Total number of records retrieved by a single SOSL query 2,000

Total number of DML statements issued2 150

Total number of records processed as a result of DML 10,000


statements, Approval.process, or database.emptyRecycleBin

Total stack depth for any Apex invocation that recursively 16


fires triggers due to insert, update, or delete statements3

Total number of callouts (HTTP requests or Web services 100


calls) in a transaction

Maximum cumulative timeout for all callouts (HTTP 120 seconds


requests or Web services calls) in a transaction

65
Maximum number of methods with the future annotation 50
allowed per Apex invocation

Maximum number of Apex jobs added to the queue 50


with System.enqueueJob

Total number of sendEmail methods allowed 10

Total heap size4 6 MB 12 MB

Maximum CPU time on the Salesforce servers5 10,000 60,000


milliseconds milliseconds

Maximum execution time for each Apex transaction 10 minutes

Maximum number of push notification method calls allowed 10


per Apex transaction

Maximum number of push notifications that can be sent in 2,000


each push notification method call

TABLE 10.1

Per Transaction Limits

1. In a SOQL query with parent-child relationship subqueries, each parent-child relationship counts
as an extra query. These types of queries have a limit of three times the number for top-level queries
in addition to static SOQL statements, calls to the following methods count against the number of
SOQL statements issued in a request.

 Database.countQuery
 Database.getQueryLocator
 Database.query

2. Calls to the following methods count against the number of DML statements issued in a request.

 Approval.process
 Database.convertLead
 Database.emptyRecycleBin
 Database.rollback
 Database.setSavePoint
66
 delete and Database.delete
 insert and Database.insert
 merge and Database.merge
 undelete and Database.undelete
 update and Database.update
 upsert and Database.upsert
 System.runAs

3. Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a
single invocation, with a single stack. Conversely, recursive Apex that fires a trigger spawns the
trigger in a new Apex invocation, separate from the invocation of the code that caused it to fire.
Because spawning a new invocation of Apex is a more expensive operation than a recursive call in a
single invocation, there are tighter restrictions on the stack depth of these types of recursive calls

4. Email services heap size is 36 MB.

5. CPU time is calculated for all executions on the Salesforce application servers occurring in one
Apex transaction. CPU time is calculated for the executing Apex code, and for any processes that are
called from this code, such as package code and workflows. CPU time is private for a transaction and
is isolated from other transactions. Operations that don’t consume application server CPU time aren’t
counted toward CPU time. For example, the portion of execution time spent in the database for
DML, SOQL, and SOSL isn’t counted, nor is waiting time for Apex callouts

10.2 Per-Transaction Certified Managed Package Limits

Certified managed packages—managed packages that have passed the security review for
AppExchange—get their own set of limits for most per-transaction limits

Certified managed packages are developed by Salesforce ISV Partners, are installed in your org from
Salesforce AppExchange, and have unique namespaces

Description Cumulative Cross-


Namespace Limit

Total number of SOQL queries issued 1,100

Total number of records retrieved by Database.getQueryLocator 110,000

Total number of SOSL queries issued 220

67
Total number of DML statements issued 1,650

Total number of callouts (HTTP requests or Web services calls) in 1,100


a transaction

Total number of sendEmail methods allowed 110

TABLE 10.2

Per-Transaction Certified Managed Package Limits

All per-transaction limits count separately for certified managed packages except for:

 The total heap size


 The maximum CPU time
 The maximum transaction execution time
 The maximum number of unique namespaces

These limits count for the entire transaction, regardless of how many certified managed packages are
running in the same transaction.

Also, if you install a package from AppExchange that isn’t created by a Salesforce ISV Partner and
isn’t certified, the code from that package doesn’t have its own separate governor limits

Any resources it uses count against the total governor limits for your org

10.3 Static Apex Limits

Description Limit

Default timeout of callouts (HTTP requests or Web 10 seconds


services calls) in a transaction

Maximum size of callout request or response (HTTP 6 MB for synchronous Apex or 12 MB


request or Web services call)1 for asynchronous Apex

Maximum SOQL query run time before Salesforce cancels 120 seconds
the transaction

Maximum number of class and trigger code units in a 5,000


deployment of Apex

68
For loop list batch size 200

Maximum number of records returned for a Batch Apex 50 million


query in Database.QueryLocator

TABLE 10.3

Static Apex Limits

1 The HTTP request and response sizes count towards the total heap size

10.4 Email Limits

Inbound Email Limits

Email Services: Maximum Number of Email Number of user licenses multiplied by 1,000;
Messages Processed maximum 1,000,000

(Includes limit for On-Demand Email-to-Case)

Email Services: Maximum Size of Email Message 10 MB1


(Body and Attachments)

On-Demand Email-to-Case: Maximum Email 25 MB


Attachment Size

On-Demand Email-to-Case: Maximum Number of Number of user licenses multiplied by 1,000;


Email Messages Processed maximum 1,000,000

(Counts toward limit for Email Services)

TABLE 10.4

Email Limits

1 The maximum size of email messages for Email Services varies depending on language and
character set. The size of an email message includes the email headers, body, attachments, and
encoding. As a result, an email with a 25 MB attachment likely exceeds the 25 MB size limit for an
email message after accounting for the headers, body, and encoding.

When defining email services, note the following:

 An email service only processes messages it receives at one of its addresses.


69
 Salesforce limits the total number of messages that all email services combined, including
On-Demand Email-to-Case, can process daily
 Messages that exceed this limit are bounced, discarded, or queued for processing the next
day, depending on how you configure the failure response settings for each email service
 Salesforce calculates the limit by multiplying the number of user licenses by 1,000;
maximum 1,000,000. For example, if you have 10 licenses, your org can process up to 10,000
email messages a day.
 Email service addresses that you create in your sandbox cannot be copied to your production
org.
 For each email service, you can tell Salesforce to send error email messages to a specified
address instead of the sender's email address.
 Email services reject email messages and notify the sender if the email (combined body text,
body HTML, and attachments) exceeds approximately 10 MB (varies depending on language
and character set).

Outbound Email: Limits for Single and Mass Email Sent Using Apex

Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses
per day based on Greenwich Mean Time (GMT)

There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your
org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.

When sending single emails, keep in mind:

 You can specify up to 100 recipients for the To field and up to 25 recipients for the CC and
BCC fields in each SingleEmailMessage.
 If you use SingleEmailMessage to email your org’s internal users, specifying the user’s ID in
setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying
internal users’ email addresses in setToAddresses means the email does count toward the
limit.
 You can send mass email to a maximum of 5,000 external email addresses per day per org
based on Greenwich Mean Time (GMT).

70
Note

The single and mass email limits don't take unique addresses into account

For example, if you have [email protected] in your email 10 times, that counts as 10 against
the limit.

You can send an unlimited amount of email to your org’s internal users, which includes portal users.

You can send mass emails only to contacts, person accounts, leads, and your org’s internal users.

In Developer Edition orgs and orgs evaluating Salesforce during a trial period, you can send mass
email to no more than 10 external email addresses per day

This lower limit doesn’t apply if your org was created before the Winter ’12 release and already had
mass email enabled with a higher limit

Additionally, your org can send single emails to a maximum of 15 email addresses per day.

10.5 Size specific apex limits

Description Limit

Maximum number of characters for a class 1 million

Maximum number of characters for a trigger 1 million

Maximum amount of code used by all Apex code in an 6 MB


org1

Method size limit 2 65,535 bytecode instructions in compiled


form

Table 10.5

Size specific apex limits

1 This limit does not apply to certified managed packages installed from AppExchange (that is, an
app that has been marked AppExchange Certified). The code in those types of packages belongs to a
namespace unique from the code in your org.

This limit also does not apply to any code included in a class defined with the @isTest annotation
2
Large methods that exceed the allowed limit cause an exception to be thrown during the execution
of your code

71
10.6 Push Notification Limits

The maximum push notifications allowed for each mobile app associated with your Salesforce org
depends on the type of app

Mobile application type Maximum notifications per app per


day

Provided by Salesforce (for example, Salesforce for 50,000


iOS)

Developed by your company for internal employee use 35,000

Installed from the AppExchange 5,000

TABLE 10.6

Push Notification Limits

72

You might also like