Salesforce Technology
Salesforce Technology
Salesforce Technology
INTRODUCTION
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
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.
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
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.
3
Chapter - 2
Cloud Computing
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.
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
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
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.
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.
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
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
Object-Oriented
Objects are discrete bundle of codes (data and related operations) modeled after things
in the real words
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
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 backward compatible (We can save our apex code against different versions
of Force.com API)
Commonalities:
Both have classes, inheritance, polymorphism and other common OOP features
Both are compiled strongly typed (any invalid reference quickly fails)
Differences:
Apex runs in its multitenant environment and is very controlled by its invocations and
governor limits
10
Apex is case-insensitive
Apex requires unit testing for deployment into the production environment
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
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:
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
Formula Fields,
Apex Controllers,
Business Logic Validation Rules,
Apex Triggers
Workflows and Approvals
TABLE 3.1
Declarative tools V/S Programmatic tools
13
Chapter - 4
VISUALFORCE
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
It can be easily mixed up with HTML markup, CSS style and Java libraries, etc.
Visualforce markup
A Visualforce controller
VisualForceMarkup:
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
Controllers also provide access to the data that should be displayed in a page, and can
modify component behavior
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
15
Extensions:
Extensions allow you to leverage the functionality of another controller while adding
your own custom logic
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
Add menu items, actions, and mobile cards in the Salesforce app
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
Concise syntax
Data-driven defaults
Hosted platform
Automatically upgradeable
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>
1. From the object management settings for accounts, go to Buttons, Links, and Actions
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
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.:
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
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
TABLE 5.1
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:
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]
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
|-------------------|----------|-----------------|---------------------------|------------|
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]
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]
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
Note:
Using String with Id field in Like clause gives Compile time error
26
List<Account> acc4 = [SELECT Name, Industry FROM Account WHERE Id LIKE
'Hello'];
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
When a dateTime value is returned in Salesforce, it’s adjusted for the time zone
specified in your org preferences
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
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
ERROR: value of filter criterion for field 'CreatedDate' must be of type dateTime and should
not be enclosed in quotes
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
Ex:
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:
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
30
COUNT_DISTINCT - Returns the number of distinct non-null field values matching the
query criteria
Note: If you are using a GROUP BY clause, use COUNT(fieldName) instead of COUNT()
SOQL provides syntax to support these types of queries, called relationship queries,
against standard objects and custom objects
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”
31
“Return all Opportunities and Tests created by Bob Jones”
Relationship Names:
32
Fig.5.2 Relationship Names
33
SELECT ID, Name, FirstName, LastName, Account.Name, Account.Industry
FROM Contact
FROM Course__c
FROM Contacts)
FROM Account
FROM Courses__r)
FROM Faculty__c
34
Right Inner Join (Child to Parent)
FROM Contacts)
FROM Account
35
WHERE ID IN (SELECT AccountID
FROM Contact)
FROM Courses__r)
FROM Faculty__c
FROM Course__c)
36
Left Anti Join (Parent to Child)
FROM Account
FROM Contact)
FROM 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.
insert upsert
update merge
delete undelete
The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to
your organization’s data
insert sObject
insert sObject[]
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[]
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[]
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
Note: You need to create an external id field named MyField (MyField__C) of Number type on
Account Object before executing the following programs:
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
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)
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());
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());
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 ID
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
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
4. The record in index 0 will have the new data, while the records in the other two indices will
be deleted
Note:
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
AccountTerritoryAssignmentRule
AccountTerritoryAssignmentRuleItem
ApexComponent
ApexPage
BusinessHours
BusinessProcess
CategoryNode
CurrencyType
44
DatedConversionRate
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
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
Trigger can handle DML Operation, execute SOQL and call custom apex methods
Apex Triggers are used when the requirement is not fulfilled by declarative operations such as
workflow, process builder etc.
1. Workflows
2. Flows
3. Process builder
4. Apex 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
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:
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
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
VARIABLES USAGE
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
50
old Returns a list of the old versions of the sObject records
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
51
Chapter - 8
WEBSERVICES
Piece of software that makes itself available over the Internet or private (intranet) networks
Web service is a collection of standards or protocols for exchanging information between two
devices or application
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)
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
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 −
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:
SOAP
Advantages:
WS Security
Language Independent
Platform Independent
Disadvantages:
Slow
WSDL Dependent
REST
It is a architectural style
Fast
Language Independent
Platform Independent
SOAP vs REST
SOAP stands for Simple Object Access REST stands for REpresentational State
2)
Protocol Transfer
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
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
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
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
Asynchronous
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
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.
Table 9.1
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
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:
61
Fig 9.3. Enqueue and Dequeue
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
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.
65
Maximum number of methods with the future annotation 50
allowed per Apex invocation
TABLE 10.1
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
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
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
67
Total number of DML statements issued 1,650
TABLE 10.2
All per-transaction limits count separately for certified managed packages except for:
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
Description Limit
Maximum SOQL query run time before Salesforce cancels 120 seconds
the transaction
68
For loop list batch size 200
TABLE 10.3
1 The HTTP request and response sizes count towards the total heap size
Email Services: Maximum Number of Email Number of user licenses multiplied by 1,000;
Messages Processed maximum 1,000,000
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.
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.
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.
Description Limit
Table 10.5
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
TABLE 10.6
72