0% found this document useful (0 votes)
4 views

APEXPROGRAMMINGMATERIAL-1 (1) (1)

Apex is an object-oriented, case-insensitive programming language used on the Force.com platform, which allows for custom application development and integration with external systems via APIs. It includes features such as a metadata repository for storing classes, a query language (SOQL), and a search language (SOSL), along with various programming paradigms like procedural, object-oriented, and service-oriented programming. Apex supports data manipulation, variable declaration, conditional statements, and provides built-in functions for debugging and executing code.

Uploaded by

Vamsi krishna M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

APEXPROGRAMMINGMATERIAL-1 (1) (1)

Apex is an object-oriented, case-insensitive programming language used on the Force.com platform, which allows for custom application development and integration with external systems via APIs. It includes features such as a metadata repository for storing classes, a query language (SOQL), and a search language (SOSL), along with various programming paradigms like procedural, object-oriented, and service-oriented programming. Apex supports data manipulation, variable declaration, conditional statements, and provides built-in functions for debugging and executing code.

Uploaded by

Vamsi krishna M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 214

APEX PROGRAMMING MATERIAL

- It is purely an Object Oriented Programming Language.


- It is not a Case Sensitive Programming.
- Apex is a Tightly Coupled Programming language.
i.e We have the define the variables first, before its usage.
- Each Statement in apex programming should be ends with a Semicolon(;).
- Each statement will be compiled by using Apex Compiler.
- Each apex class will store in Force.com platform. Force.com platform contains a
metadata repository, which holds all the compiled apex classes.
- Apex provides a set of Basic Programming building blocks to develop the custom
applications.

- We can implement Custom Business Logic and Complex Transactional


statements using Apex.

- We can integrate the Salesforce application with any External System using Apex
Programming(SOAP API, REST API).

- Using Apex Programming we can perform all the DML manipulations on the
records.

- Apex Programming is comes under Programmatic customizations.

- Apex Programming provides a Query language called as "SOQL - Salesforce


Object Query Language" in-order to retrieve the records from salesforce objects.

- It Provides a Search Language "SOSL - Salesforce Object Search Language" in-


order to search the content from salesforce objects

- Apex Programming Supports MVC Development Style.

Agile Methodology Scrum Training Videos:


http://www.scrumtrainingseries.com/

Types of Programming:

- While implementing the Custom applications, developer's has to apply any of


the programming approach as below.

1. Procedure Oriented Programming:


- In this approach each functionality / business login will be implemented in terms
of Procedures / Functions.
-Ex: Basic, Pascal, C programming languages.
- This approach will not provide the proper security for the code.
- The Functions / Procedures will be moving around the application. So Developer
can't restrict the code accessibility.

2. Object Oriented Programming:


- To avoid the Problems exist in the Procedure oriented programming, we are
using Object Oriented Programming approach.
- This approach provides the better code re-usability and security, by grouping the
Variables and Member functions into a Single Unit Called as "Class".
- We can provide the scope for each member in the class. i.e upto what level we
can access the member of the class.

- Each functionality in this approach is implemented in terms of classes and


Objects.

Ex: Java,C++, Python, Perl, C#.Net, VB.Net, Apex, etc..

3. Component Oriented Programming


- To provide the effective and dynamic user interface to the user, we need to use
Component Oriented Programming.

- Each functionality will be implemented in-terms of Components.


- Component is an User- Interface object, which contains Visual Appearance.
(TextBox, Label, Picklist, Checkbox, Button,...etc)
Ex: VB, VB.Bet, VC++, Swings, Visual Force.. etc.

4. Service Oriented Programming


- This approach is mainly used for Integrating the Applications with each other.
- This is not a new Technology, it is a very older approach to make the
communication between two different applications (developed by using diff.
technologies and running on diff. platforms)
- This approch provides the communication between two diff. applications by
using the Message Formats.(Message is called as Service)
- By using this approach we can provide the cross-platform communication.
- This approach inernally uses the XML format for the communication.

Note:
Implementation behind all the EAI Tools (Enterprise Application Integration
Like TIBCO, WEB METHODS, SEE BEYOND, BIZ TALK, etc) is Service Oriented
Approach.
- In Salesforce, We are using Two API's for the Service Oriented Communication.
Called as "SOAP API" and "REST API", for integrating the Salesforce with external
systems.
SOAP --> Simpe Object Access Protocol
REST --> Representational State Transfer
API --> Application Programming Interface

- Apex Programming provides a Set of Fundamental Building Blocks to develop the


custom business logic.

- Apex Programming provides a set of Datatypes, Which represents the Type of


the data to be inserted / retrieved from Salesforce objects.

Data Types in Apex Programming:


Datatype describes, 2 things as follows.
1. What type of Data the variable can Hold.
2. How much memory is required to store the value.

-Apex Provides 2 types of Data types.


1. Primitive Datatypes
2. SObject Data types

Primitive Datatypes:
- These are the Basic / Fundamental datatypes to store the values for temporary
usage. These are available in all programming languages.

Ex:
Integer: Requires 4 bytes of memory(Holds Only numerical Value).
Long: Occupies 8 bytes of memory
Double: This can hold a numerical value, which contains decimal point values
also.
We can store more than 2 digits after the decimal point.
Ex: double Pi= 3.1412;

Decimal: This can hold a Decimal value, which contains max of 2 digits after the
decimal point.
Ex: decimal balance = 24500.50;
Note: All Currency fields will refer Decimal Datatype by default.
- It requires 8 bytes of memory.
Char: It can hold only one character, which requires 2 bytes to store a character.
Boolean: It is used to hold True / False Values.
Byte: This datatype is used to store the bit value (0 / 1)
ID : This datatype is used to store an 18 characters ID generated by salesforce,
which is used to identify a record.
String: This datatype is used to store a collection characters including special
characters also.
Date: This Datatype is used to store the Date values.
Date/Time: This is used to hold Data Time stamp.(Date and Time)
Variable Declaration:
- Variable is a Programmatic element, which can hold a specific value for
temporary usage.

Syntax: [<AccessSpecifier>] <Datatype> <VariableName> [= <Value>;]


Ex: integer x;
integer accountNumber = 12345;
string customerName = ‘Ramesh Kumar’.

Note:
All primitive datatypes supports Static Memory Allocation.(i.e each data
type has a fixed size of memory, which will be allocated at the time of variable
definition. )
Note:
We can't increase / decrease the size at runtime.

SObject Datatypes:

- All Salesforce objects (both Standard & Custom) will be comes under SObject
Data Types.

- These will supports Dynamic Memory allocation, which will reserve the memory
during runtime of the application.

- Upon creating a New Custom object, salesforce will provides 2 classes.


Ex: Object Name : Position__C.

Class 1: Position__C --> To perform DML manipulations on the records in


that object (CRUD - Create / Read /Update / Delete)

Sharing Class: Position__Share --> Used to Share the Position__C object


records through apex programming.
Ex:
Account --> Account --> AccountShare
Contact --> Contact --> ContactShare
Lead --> Lead --> LeadShare
....
....
Customer__c --> Customer__c --> Customer__Share
Candidate__c --> Candidate__c --> Candidate__Share.
...
...

Variable Declaration:

Syntax: <Datatype> <Variable_Name>;

Account acc;
Contact con;
Position__C pos;
Candidate__c cnd;

Ways to Write Apex Programming:

- Salesforce provides the following ways to write apex programming code.

1. Standard Navigation.
2. Developer Console.
3. Execute Ananymous Window
4. Eclipse IDE.

Standard Navidation:

- Using this option, we can create user defined business logic interms of controller
classes and store into Force.com platform.

- All Apex classes will stored into Metadata Repository in Force.com platform.
Goto Setup --> Goto Build Menu --> Goto Develop --> Click on "Apex Classes".
1. Click on "New" button to create a New Apex Class.
2. Write the Business login in the editor provided by salesforce
3. Click on "Save" button.

Note:
1. When the user click on "Save" button, salesforce will forward the apex
class to Force.com platform.
2. Apex code will be compiled by using Apex Compiler, which resides in
Force.com platform.
3. If found any errors, it will immediately intimate to the user. If Not found
(Compiled successfully), Apex class will stored into Metadata Repository.

2. Execute Ananymouns Window:


- By using this editor, we can execute the adhoc code and will get the results to be
printed on "Developer console."

Goto Your Name --> Click on "Developer Console". It will open the
Developer console in a New Window.
1. Goto "Debug" menu
2. Click on "Execute Ananymouns Windows".
3. Write the Apex code to be get executed.
4. Click on "Execute" button to run the code.

Note: When the user click on "Execute" button, it will send the complete
code to Force.com platform to get it compiled.

Executing Selected Lines:

- Salesforce provides, to execute a portion of apex code by Selecting the


statements.
1. Select the statements to be get execute / Run by using mouse
pointers / arrow keys.

2. Click on "Execute Hightlighted" button, to run the selected lines of


code.

Comments:
These are used to ignoring few lines of code to get it compiled and execute / Run.

1. Single line Comments:


- To comment a Single line

Syntax:
// <Statements...>

Ex: // integer accountNumber;


// string customerName;

2. Multiline comments:
- We can comment a group of statements as below.

Syntax:
/*
...
... Statements..
...
*/

Ex:
/*
integer accountNumber;
string customerName;
*/
Variable Declaration:
- Variable is a Programming element to store some value for temporary
storage.
- We can define the variables in apex programming by using the below
syntax..

Syntax:
[<AccessSpecifies>] <DataType> <Var1>[,<var2>,<var3>,...etc];

Note: [] --> indicates, this is an optional statement.

Ex:
integer x, y;
string customerName, country;
boolean isExist;

SObject DataTypes:

Account acc;
Contact con;
Position__c pos;
Candidate__c objCandidate;
...
etc.;

Assignment Operations:

To assign the value for the variables, we need to use the assignment operators.

Operators in Apex Programming:

- Operator is nothing but a symbol, which performs some operations on operands.

-Apex programming provides the following operators


1. Arithmetic Operators:
Used to peform basic mathematical operations.

+ --> Addition
- --> Subtraction
* --> Multiplication
/ --> Division
Mod() --> Reminder

2. Relational Operators / Comparison Operators:


- These are used to compare the values of one variable with another.

Ex:
== --> Equals
= ==> Assignment
> --> Greater Than
>= --> Greater Than or Equals
< --> Less Than
<= --> Less Than or Equals
!= --> Not Equals

3. Assignment Operators:
- These are used to assign the values to the variables.

Ex:
= --> Assign the value to a variable
Ex: integer x =100
string customerName = 'Ramesh Kumar';
+= --> Incrementing the value and assign to a variable

-= --> Decrementing the values and assign to a variable

*= --> Multiply the value and assign to a variable.


/= --> Divide the values and assign to a variable

4. Logical operators:
- Logical Operators are used to prepare the compound conditions.

AND --> Verifies all the conditions are valid or not. If all the conditions are
satisfied it will return TRUE. Else return FALSE.

OR --> It returns TRUE, when any of the condition is satisfied. Returns


FALSE, if all the conditions are failed.

! --> It will convert the Positive to negative and vice versa.

5. Increment or Decrement Operators:


- These are used to increment / decrement the values automatically.

++ --> Increment the value by 1.


-- --> Decrement the value by 1.

Printing Statement:
-Salesforce Provides a built-in class called as "System". Which provides "Debug"
function to display / print the result of the statements on the developer console.

Ex:
system.debug('Welcome');
system.debug('Welcome to Apex Programming.');
Note: Apex code needs to be executed by Force.com Platform.
When user executes an apex program or code, force.com platform will compile
and execute the code and generates a “Log File”.
All log files will be stored in the location “Debug Logs” as below.
Goto Setup → Goto Monitor option in Left Panel → Goto Logs → Click on “Debug
Logs”. It will show the debug log files generated by salesforce.

// Write the Code in Execute Ananymous window and click on “Execute” button
system.debug('Welcome to Apex Programming.');
system.debug('This is my First Apex Program.');
system.debug('Debug Logs are Enabled.');

Write the Code in Execute Anonymous Window:

Goto Your Name --> Click on "Developer Console".


1. Goto the Debug Menu
2. Click on "Execute Anonymous Window" (Ctrl + E)
3. Write the apex program code.
4. Click on "Execute" button.

Note:
It will send the Apex program code to Force.com platform. It will compile
the code and execute. And send the response back to the client and display the
result in "Developer Console"

// Write an apex program to define the variables and print the values in
Developer console.

integer accountNumber;
string customerName;

accountNumber = 100001;
customerName = 'Ramesh Kumar';

// Priting the values..


system.debug(accountNumber);
system.debug(customerName);

// Printing values along with Comments..

system.debug('Account Number is....: ' + accountNumber);


system.debug('Customer Name is....: '+ customerName);
// Printing the values in a single line..

system.debug('Account Number is...: '+ accountNumber + ' --> Customer Name


is...: '+ customerName);

// Apex program to perform basic mathematical calculations...

integer firstNumber, secondNumber, result;

firstNumber = 400;
secondNumber = 20;

// Addition Operation..

result = firstNumber + secondnumber;


system.debug('Addition Result is....: ' + result);

// Subtraction Operation..
result = firstnumber - secondNumber;
system.debug('Subtraction result is....: '+ result);

// Multiplication Operation..
result = firstnumber * secondNumber;
system.debug('Multiplication result is....: '+ result);

// Division Operation..
result = firstnumber / secondNumber;
system.debug('Division result is....: '+ result);

// Apex program to calculate Simple Interest...

integer principleAmount, rateOfInterest, tenure, interestAmount;

principleAmount = 50000;
rateOfInterest = 5;
tenure = 10;

interestAmount = (principleAmount * rateOfInterest * tenure) / 100;

system.debug('Interest Amount to be Paid is...: ' + interestamount);


Conditional Statements:

- These are used to transfer the flow of execution of statements exist in the apex
program.

- By using this we can decide, which statements needs to be executed and which
should not to be executed by using a condition or filter.

- The user can prepare his own conditions to execute the statements.

- We can have one or more conditions, which can be combined by using logical
operators.

Note: Each condition should follow the below syntax.

Syntax:
<Variable_Name> <Operator> <value>

Ex:
fNumber == sNumber
fNumber > sNumber
sNumber > 0

Note: Apex Programming provides the below conditional statements.

1. IF Conditional Statements
2. Ternary Operator

Ex:
1. Providing 5% Discount, When bill amount is more than 4000.
2. Calculating the Grade, If the student got Passed.
3. Delete the Record, If it is exist

IF Condition:

Using this statement, we can change the execution flow of the application.

- While executing the condition, we can add one or more conditions.


Each condition should be with the below syntax.
<VariableName> <Operator> <Value>

Ex:
BillAmount > 4000. AnnualRevenue > 100000. Rating = 'Hot', etc..
- To Prepare the Multiple conditions (Compound conditions), we have to use
Logical Operators.

- IF statement provides the various formats as below.

Simple IF Condition:

Syntax:
If(<Conditions>)
{
Statements..
....
}

- If the conditions are satisfied, then it will execute the statements.


Note:
Each condition will have only one possible result. either TRUE or FALSE.
It returns TRUE, when the conditions are satisfied. Else it will return FALSE.

Ex:

integer firstNumber, secondNumber, result;


firstNumber = 200;
secondNumber= 0;

if(secondNumber > 0)
{
result = firstnumber / secondNumber;
system.debug('Division Result is....: ' + result);
}

IF Else Statement:

Syntax:
if(<Conditions>)
{
// TRUE Block Statements
....
}
else
{
// FALSE block Statements.
...
}

- If the conditions are satisfied, then the Immediate Block(TRUE Block) of


statements will be executed. Else it will execute the FALSE block statements.

Ex:

integer firstNumber, secondNumber, result;

firstNumber = 200;
secondNumber= 15;

if(secondNumber > 0)
{
result = firstnumber / secondNumber;
system.debug('Division Result is....: ' + result);
}
else
{
system.debug('Division Operation Cannot be performed');
}

// Apex program to find out the Biggest Number from the given two numbers.

integer firstNumber, secondNumber;

firstNumber = 200;
secondNumber= 1500;

if(firstNumber > secondNumber)


system.debug('First Number is Big.');
else
system.debug('Second Number is Big');

Else If Condition:

Syntax:
If(<Conditions>)
{
// Statements.
..
}
else if(<Conditions>)
{
// Statements.
...
}
else if(<Conditions>)
{
// Statements
}
...
...
else
{
// Statements..
...
}

Note:
1. If any of the condition is not satisfied, then it will execute the ELSE block
statements.
2. If one of the condition is satisfied, then it will execute that Condition
Block statements and comes out from the If condiions. (i.e. it won't check the
remaining conditions.)

Ex:

integer firstNumber, secondNumber;

firstNumber = 2000;
secondNumber= 2000;

if(firstNumber > secondNumber)


system.debug('First Number is Big.');
else if(firstnumber == secondnumber)
system.debug('Both Are Equals.');
else
system.debug('Second Number is Big');

Nested IF Condition:
Syntax:
IF(<Conditions>)
{
// Statements...
....
IF(<Conditions>)
{
// Statements..
...
}
else
{
// Statements...
}
}

- If we write one if condition into another, then it is called as Nested If Condition.

// Apex program to Peform basic mathematical calculations...

integer fNumber, sNumber, result;

fNumber = 100;
sNumber = 0;

result = fNumber + sNumber;


system.debug('Addition Result ....: ' + result);

result = fNumber - sNumber;


system.debug('Subtraction Result ....: ' + result);

result = fNumber * sNumber;


system.debug('Multiplication Result ....: ' + result);

// The below statement will cause "Divided By Zero Exception.."


result = fNumber / sNumber;
system.debug('Division Result ....: ' + result);

IF Condition Statement:

// Apex program to calculate Simple Interest...

integer fNumber, sNumber;

fNumber = 100;
sNumber = 0;

system.debug('Addition Result ....: ' + (fNumber + SNumber));


system.debug('Subtraction Result ....: ' + (fNumber - SNumber));
system.debug('Multiplication Result ....: ' + (fNumber * SNumber));

if(sNumber > 0)
{
system.debug('Division Result ....: ' + (fNumber / SNumber));
}
else
{
system.debug('Division Operation Cannot performed.');
}

=============================================
// Write an apex program to display the Biggest number from the given Two
numbers.

integer fNumber, sNumber;


fNumber = 1200;
sNumber = 500;

if(fNumber > sNumber)


{
system.debug('First Number is Biggest One.');
}
else
{
system.debug('Second Number is Bigest one');
}

=============================================
/* Write an apex program to print the Season Name based on Month Number as
below.
Month Numbers Season Name
-----------------------------------------------------
1-4 Winter
5-8 Summer
9-12 Spring
>12 or <1 Invalid Month Number
*/
integer monthNumber;

monthNumber = 14;

if(monthNumber >=1 && monthNumber <=4)


{
system.debug('This is Winter Season');
}
else if (monthNumber >=5 && monthNumber <=8)
{
system.debug('This is Summer Season');
}
else if (monthNumber >= 9 && monthNumber <= 12)
{
system.debug('This is Spring Season');
}
else
{
system.debug('Invalid Month Number.');
}

==============================================

/* Write an apex program to find out the Student's Grade based on the below
requirement.

Subjects -> Maths, Physics, Chemistry, English, Hindi.


1. Calculate the Total Marks of the Student.
2. Calculate Average Marks of the Student.
3. Findout the Result
3.1. PASS --> If the student got more than 40 marks in each subject.
3.1.1. Calculate the Grade of the Student as below.
a. Grade A -->If the Average marks are more than 60%.
b. Grade B --> If the Average marks between 50 - 59%.
c. Grade C --> If the average marks between 40 - 49%.
3.2. FAIL --> If he got less than 40 marks in any of the subject.

*/

integer maths, physics, chemistry, english, hindi, totalmarks, averagemarks;

maths = 50;
physics = 47;
chemistry = 39;
english = 90;
hindi = 75;
totalmarks = english + hindi + maths + chemistry + physics;
system.debug('Total Marks are....: ' + totalmarks);

averagemarks = totalmarks / 5;
system.debug('Average Marks are....: ' + averagemarks);

if(maths >= 40 && physics >= 40 && chemistry >= 40 && english >= 40 && hindi
>= 40)
{
system.debug('STUDENT GOT PASSED.');

if(averagemarks >=60)
{
system.debug('Student got - GRADE A');
}
else if(averagemarks >= 50 && averagemarks <= 59)
{
system.debug('Student got - GRADE B');
}
else if(averagemarks >=40 && averagemarks <=49)
{
system.debug('Student got - GRADE C');
}
}
else
{
system.debug('STUDENT GOT FAILED.');
}

Ternary Operator:

- It provides the optimized way of writing the conditional statements.


Syntax:

<VariableName> = (<Condition>)? <TrueBlock> : <FalseBlock>;

// Apex program to find biggest one from the given two numbers using Ternary
Operator

integer firstNumber, secondNumber, result;

firstNumber = 2000;
secondNumber= 4000;

result = (firstNumber > secondNumber) ? firstNumber : secondNumber;


system.debug('Biggest Number is...: ' + result);

Iterative Statements:

- These are used to execute a set of statements for the specified number of times.
- These are also called as Looping statements.

- Apex Programming provides the following iterative statements.

1. While Loop.
2. Do-While Loop.
3. FOr Loop.

While Statement:
----------------
syntax:
While(<Conditions>)
{
// Statements...
.....
}
- It is a Pre-checking iterative statement, which will check the condition first. If the
condition is satisfied, then it will enter into the block and execute the statements.
It will repeat the step till the condition is TRUE.
If the condition is FALSE, then it will comes out of the block.

// Write an apex program to display the first 100 Numbers.

integer counter;
counter=1;

while(counter <= 100)


{
system.debug(counter);
counter++;
}

// Apex Program to print First 100 Even Numbers.

integer counter;
counter=2;
while(counter <= 100)
{
system.debug(counter);
counter += 2; // Counter = counter + 2;
}

Do-While Loop:
Do-While is a PostChecking iterative statement, which will execute the statement
atleast once and then it will check the condition.
It will iterate the loop till the condition is satisfied. Once the condition is Failed, it
will comes out of the block.

Syntax:
Do
{
// Statements.
....
}While(<Conditions>);

// Apex Program to print the First 100 Numbers in Reverse Order.

integer counter;
counter=100;
do
{
system.debug(counter);
counter--;
}While(counter >= 1);

FOR Loop:
---------
- It is a Pre-checking iterative statement, which will execute the set of statements
for a specified number of times.
- It provides the optimized way of writing the iterative statements.

Syntax:
FOR(<InitializationPart> ;
<Conditional Part> ;
<Increment / Decremental Part>)
{
// Statements..
...
...
}

// Apex program to Print the First 100 Numbers using FOR loop.

for(integer counter = 1; counter <= 100; Counter++)


{
system.debug(counter);
}

// Write an apex program to print Odd Numbers falls between 1 - 100 using FOR
loop;

for(integer i = 1; i<=100 ; i=i+2 )


{
system.debug('Odd Number value is...: '+ i);
}

// Write an apex program to print the first 100 numbers using Do-While
statement.

integer counter;
counter =1;

do
{
system.debug('Value is...: ' + counter);
counter++;

}While(counter <= 100);

// Write an Apex Program to print the first 100 Prime Numbers.

// Write an apex program to print Even Numbers falls between 1 - 100;

integer startingValue;

startingValue = 2;

While(startingValue <= 100)


{
system.debug(startingValue);
startingValue +=2;
}

// Write an apex program to print First 100 Numbers in Reverse order.

integer counter;

counter = 100;

While(counter >= 1)
{
system.debug(counter);
counter--;
}

// Write an apex program to print First 100 Numbers.

integer counter;

counter =1;

while(counter <= 100)


{
system.debug(counter);
counter ++;
}

// Write an apex program to print a message 10 times.


integer counter;

counter =1;
while(counter <= 10)
{
system.debug('Welcome to Apex Proigramming.');
counter ++;
}

Arrays:
integer[] accountNumbers = new integer[5];

// Assigning values for Array Partitions...

accountNumbers[0] = 100;
accountNumbers[1] = 6780;
accountNumbers[2] = 1450;
accountNumbers[3] = 190;
accountNumbers[4] = 17800;

// Display Array elements...


system.debug('Value in Partition 1....: ' + accountNumbers[0]);
system.debug('Value in Partition 2....: ' + accountNumbers[1]);
system.debug('Value in Partition 3....: ' + accountNumbers[2]);
system.debug('Value in Partition 4....: ' + accountNumbers[3]);
system.debug('Value in Partition 5....: ' + accountNumbers[4]);

-------------------------

string[] months = new string[]


{'January','February','March','April','May','June','July','August','September','Octob
er','November','December'};

system.debug('Month 1 --> '+ months[0]);


system.debug('Month 2 --> '+ months[1]);
system.debug('Month 3 --> '+ months[2]);
system.debug('Month 4 --> '+ months[3]);
system.debug('Month 5 --> '+ months[4]);
system.debug('Month 11 --> '+ months[10]);
system.debug('Month 12 --> '+ months[11]);

-----------------------------------
string[] months = new string[]
{'January','February','March','April','May','June','July','August','September','Octob
er','November','December'};

system.debug('Collection Elements are....: ' + months);

// Display Collection size...


system.debug('Collection size is....: ' + months.size());

for(integer counter =0; counter < months.size(); counter ++)


{
system.debug('Collection Element is....: ' + months[counter]);
}

// Display the Collection Elements...

for(integer index = 0; index <= 11; index++)


{
system.debug('Element at Index ' + index + ' is .....: ' + months[index]);
}

------------------------------

string[] names = new string[] {'Ramesh


Kumar','Pawan','Suresh','Anand','Kartheek','Srinivas','Lakshman','Sandeep','Kishor
e'};
// Print the Collection Elements...
for(integer counter = 0; counter < names.size(); counter++)
{
system.debug('Person Name is...: ' +names[counter]);
}

// Sorting the Elements...


names.sort();

system.debug('After Sorting the Collection, Elements are....: ');


for(integer counter = 0; counter < names.size(); counter++)
{
system.debug('Person Name....: ' + names[counter]);
}

-----------------------------------------

string[] names = new string[] {'Ramesh


Kumar','Pawan','Suresh','Anand','Kartheek','Srinivas','Lakshman','Sandeep','Kishor
e'};

system.debug('Collection size is....: ' + names.size());

// Print the Elements.. using Enhanced FOR Loop..

for(string element : names)


{
system.debug('Element Value is....: ' + element);
}

Object Oriented Programming Principles:

- OOP provides the following basic principles needs to be followed during the
application development.
- In Object Oriented Programming, each functionality is provided in terms of
Classes and Objects.

1. Encapsulation:
- It Describes grouping of Data Members(Variables) and member functions
into a single unit called as "Class".
- It can be achieved by using Classes and Interfaces.
2. Abstraction:
- It describes, Providing the User Interface to the User, but with out
providing the complexity of the implementation.
-i.e. we can hide the backend implementation of the application.
- By using this we can achieve the "Data Hiding"
3. Inheritance:
- This is used to aquire the features of once class into another class, in-
order to avoid the duplicate code in the application.
- By using this we can achieve "Code Re-Usability"
4. Polymorphism:
- Poly means "Many", Morphism means "Forms"
- By using this, we can prepare multiple functions with Same Name, but the
functions should be differentiate in-terms of their Signature (i.e. Number of
Parameters, Order of Parameters and Type of the Parameters)

Class:
It is a blue print, which contains group of Variables and Functions together. A class
can have one or more members inside it like Variables, Functions, Constructors,
Properties, etc.

Class Syntax:
=============
<AccessSpecifiers> Class <ClassName>
{
// Class Members..
... Variable, Functions, Constructors, Properties...etc.
...
}

Ex:
Public Class SampleClass
{
integer acountNumber;
string customerName;
boolean isExist;
}

Note:
1. Class Name should be always Start with a "Capital Letter"
2. Class Name should be only OneWord. i.e. No spaces in the class name.
3. We can't create Duplicate Classes. (i.e each class should have a unique
name)

Note:
All Classes will be stored into the Metadata Repository in Force.com
platform.

Access Specifiers:
==================
- Access specifier, defines the Level of Access / Scope of the member or the Class.
- Using AccessSpecifiers, we can restrict the access of the Class or Class Members.
- Apex provides the below AccessSpecifiers
1. Private:
Private members of the class can be accesible from only within the
class.
- We can't access the members from out side of the class.
2. Public:
- Public members of the class can be accesible from within the class
and outside of the class also.
- These members can be accesible within the Entire application. But
can' accesible from Outside of the application
3. Protected:
- These members can be accesible from within the class and from the
Child or associated classes.
Note: We can't access from out side of the class.
4. Global:
- We can access these members from within the application and
Outside of the Application also.
- i.e. we can able to access these members from Extenal Systems
also.
-BatchApex Calsses, Schedule Apex Classes, Webservices should be
defined as "Global"

Note:
If the user didn't specify any access specifier for a member(Variable,
Function,...etc), then it will be Private by default.

Syntax:
--------

Public Class MyClass


{
// Variable Declaration..
// Methods / Functions...
// constructors ....
// Properties....
}

Ex:

public Class MySampleClass


{
public integer accountNumber;
public string customerName;
}

Creating Class using Developer Console:


---------------------------------------
Goto Your Name --> Click on "Developer Console"
1. Goto File Manu
2. Click on "New" Menu Item
3. Click on "Apex Class" from Sub Menu
4. Enter the Apex Class Name in the TextBox
5. Click on "Create / Save" button
6. Enter the Apex Class Code / Statements..
7. Click on "Save " / (CTRL + S)

Note:
Developer Console provides an Auto Save option, which saves the code in
Force.com platform by compiling the code automatically.

// Create an Apex Class to define Variables and Access the members by creating
object...

Creating Class:
---------------
public class MySampleClass
{
public integer accountNumber;
public string customerName;
}

Executing Class (Execute Anonymous Window)


------------------------------------------
// Creating Object of the class..
MySampleClass s = new MySampleClass();
// Accessing class members using object..
system.debug('Account Number is...: ' + s.accountNumber);
system.debug('Customer Name is....: '+ s.customerName);

Creating Apex Class using Standard Navigation:


----------------------------------------------
Goto Setup --> Goto Build Menu --> Goto Develop
1. Click on "Apex Classes"
2. Click in "New" button to create a new class
3. Write the Apex Class Code in the Text Area
4. Click on "Save" button.

- It will creates a New Apex Class with the specified name and send to the
Force.com Platform for compilation. If it is success, then it will Save the Apex Class
code in Metadata Repository.

Apex Class Code:


----------------
public class MySampleTestClass
{
public integer accountNumber;
public string customerName;
}

Execute the Class:


------------------
Goto the Developer Console --> Goto Debug --> Click on "Execute Ananymous
Window" (Ctrl+E)

// Creating Object of the class..


MySampleTestClass s = new MySampleTestClass();

// Accessing class members using object..


system.debug('Account Number is...: ' + s.accountNumber);
system.debug('Customer Name is....: '+ s.customerName);

// Assigning the Values to the Variables..


s.accountNumber = 10001;
s.customerName = 'Pawan Kumar';

// Display the Values of the Variables using object..


system.debug('Account Number is...: ' + s.accountNumber);
system.debug('Customer Name is....: '+ s.customerName);

// Apex Program to define members and access the values...

Creating Class:
---------------
Public class SampleApexClass
{

Public integer accountNumber;


public string customerName;
private string customerAddress;

Executing the class:


--------------------
// Create Object of the Class...

SampleApexClass sample = new SampleApexClass();

system.debug('Account Number is....: ' + sample.accountNumber);


system.debug('Customer Name is.....: ' + sample.customerName);

/* The below statement will cause the Exception "Variable cannot be visible - Due
to Private Access.." */
system.debug('Customer Address is....: ' + sample.customerAddress);

// Assigning values...
sample.accountNumber = 100001;
sample.customerName = 'Ramesh Kumar';

system.debug('Account Number is....: ' + sample.accountNumber);


system.debug('Customer Name is.....: ' + sample.customerName);

// Create an Apex Class from Developer Console..

Creating Class:
---------------

public class MyFirstApexClass


{
public string customerName;
public string customerAddress;

Executing class:
----------------
// Create Object of the Class...

MyFirstApexClass myclass = new MyFirstApexClass();

system.debug('Customer Name....: ' + myclass.customerName);


system.debug('Customer Address ...: ' + myclass.customerAddress);

SubPrograms:
============
-These are the part of the program, which can able to perform some task.
- SubPrograms are used to divide the large / complex functionality into various
small pieces to make it more understandable.

- SubPrograms are sub divided into 2 Types


1. Functions
2. Procedures

Procedure:
----------
- It contains one or more statements in order to perform a particular task.

Note: Procedure doesn't return any value to the calling environment.

Syntax:
-------
<AccessSpecifier> Void <ProcedureName> ([<ParametersList>])
{
// Statements..
....
}

Ex:

public void ShowMessage()


{
// Statements..
...
}

public void Addition(integer x, integer y)


{
// Statements...
...
}

// Write an Apex Program to Perform the Arithmetic operations and print the
result.

public class SampleArithmeticClass


{
public integer x= 100;
public integer y = 400;

public void ShowMessage()


{
system.debug('Welcome to Apex Programming.');
}

public void Addition()


{

system.debug('Addition Result is...: ' + (x+y));


}
public void Subtraction()
{
system.debug('Subtraction Result is...: '+ (x-y));
}

public void Multiply()


{
system.debug('Multiplication result is...: '+ (x*y));
}

public void Division()


{
system.debug('Division Result is...: '+ (x/y));
}
}

Executing the Class:


--------------------
// Creating Object of the class..
SampleArithmeticClass s = new SampleArithmeticClass();

// Accessing class members using object..


s.Addition();
s.Subtraction();
s.Multiply();
s.Division();

Parameterised Procedures:
-------------------------
- If the procedure doesn't have any parameters, then it will provide the static
behaviour.
i.e. whenever we call the procedure, it provides the same result.

- To make the procedure dynamic, we need to supply some input values in-terms
of Parameters.
- We can pass N number of Parameters. with different types of values.
- Each parameter, should indicate the "DataType" and "Parameter Name"

Ex: Integer x, integer y, string str,...etc

Syntax:
public void ProcedureName(<DataType> <Param1>, <DataType>
<Param>,.... ,<DataType> <ParamN>)
{
// Statements;
......
}
Note: While calling the procedure, the user has to supply the values to the
parameters in the Procedure in the same order and type as defined in the
Procedure Definition.

Ex:
public void Addition(integer x, integer y)
{
system.debug(x+y);
}

Calling:
<ObjectName>.Addition(100,450) --> Valid Statement
<ObjectName>.Addition(234, 'ABC') --> Invalid / Error

// Apex Program to perform the Mathematical and String Operations using


Procedures.

public class BasicMathOperations


{
public void Addition(integer x, integer y)
{
system.debug('Addition Result is....: '+ (x+y));
}

public void Subtraction(integer x, integer y)


{
system.debug('Subtraction Result is...: '+ (x-y));
}

public void Multiply(integer x, integer y, integer z)


{
system.debug('Multiply Result is....: '+ (x*y*z));
}
public void Division(integer x, integer y)
{
if(y>0)
system.debug('Division Result is...: '+ (x/y));
else
system.debug('Division Operation Cannot be poerformed');
}

public void Concatenate(string s1, string s2)


{
system.debug('Concatenation Result is....: '+(s1+s2));
}

public void Checkequals(string s1, string s2)


{
if(s1 == s2) // It will ignore the case
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals');
}

public void CheckEqualsWithCase(string s1, string s2)


{
if(s1.equals(s2)) // It will comparing with case sensitive
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals');
}

}
Execution:
-----------
// Creating Object of the class..
BasicMathOperations s = new BasicMathOperations();

// Accessing class members using object..


s.Addition(100,580);
s.Addition(2345,6789);

s.CheckEquals('Ameerpet','ameerpet'); // using "==" operator


s.CheckEqualsWithCase('Ameerpet','ameerpet'); // using "Equals()"

Functions:
==========
It is also a SubPrograms, which contains one or more statements to perform a
particular task, and will return the result to the calling environment.

- We can pass one or more parameters to the function.


- function should have the return type other than "Void"

Note:
Function should return the value by using "Return" statement.

Syntax:
-------
<AccessSpecifier> <DataType> <FunctionName> ([<Parameters>])
{
// Statements..
....

Return <Result Value>;


}

// Apex Class to demonstrate Functions...

public class FunctionsSample


{
public integer Addition(integer x, integer y)
{
return (x+y);
}

public integer Multiplication(integer x, integer y, integer z)


{
return (x*y*z);
}

public string Concatenate(string s1, string s2)


{
return (s1+s2);
}

public Boolean CheckEquals(string s1, string s2)


{
return s1.equals(s2);
}

Execution:
---------
// Creating Object of the class..
FunctionsSample s = new FunctionsSample();

// Accessing class members using object..

integer result;
result = s.Addition(123,478);
system.debug('Addition Result is...: '+ result);

integer addResult = s.Addition(1254,7895);


system.debug('Addition Result is....: '+ addResult);
system.debug('Addition Result is....: ' + s.Addition(9000,34555));

// Calling CheckEquals Function...


Boolean isEquals = s.CheckEquals('Salesforce','Salesforce');
if(isEquals)
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals');

// Concatenation Function...
system.debug('Concatenation result is....: '+ s.Concatenate('Welcome ', 'To
Salesforce'));

Constructors:
=============
- Constructor is a Special Member Function, which will execute automatically
whenever the user creates an object of the class.
- Constructors are used to assign some pre-defined values to the variables, while
loading the application

While creating the constructors,we have to follow the following rules.

1. Constructor Name should be same as the Class Name.


2. Constructor should be always "Public"
3. It doesn't accept any return type even "Void"
4. We can pass the parameters to the constructors
5. We can have one / more constructors in a class.
6. If the constructor contains any parameters, then we have to supply the values
for the parameters while creating the object of the class.
7. Constructor doesn't return any value.

Note:
While compiling the class code, Apex Compiler will verify wether the user
has provided the default constructor for the class or not.
If yes, then it will execute the userdefined constructor.
Else, the Apex Compiler will creates a Default constructor for the class and
execute the statements.

Example:
public class ConstructorSample
{
public ConstructorSample()
{
system.debug('This is the Default Constructor.');
}

public ConstructorSample(string str)


{
system.debug('This is Parameterized constructor..: ' + str);
}

public ConstructorSample(integer accountNumber, string customerName)


{
system.debug('This is Parameterized constructor with 2 Parameters.');
system.debug('Account Number ---> ' + accountNumber);
system.debug('Customer Name ---> ' + customerName);
}
}

Execution:
----------
// Creating Object of the class..
ConstructorSample s = new ConstructorSample();

ConstructorSample s1 = new ConstructorSample();

ConstructorSample s2 = new ConstructorSample();


// Calling Parameterized constructor...
ConstructorSample s3 = new ConstructorSample('Welcome');

// Calling Parameterized constructor...


ConstructorSample s4 = new ConstructorSample(10001, 'Suresh Kumar');

DML Statements in Salesforce:


=============================
- Using DML Statements we Can Performs operations on the records in the Object
- We can perform the operation on either one record or on multiple records
- We can perform the operations on records of Standard Obejct or Custom Object

CRUD --> C (Create / Inse) , R (Read), U (Update / Edit), D(Delete)

Salesforce provides the following DML Statements...

1. Insert:
- USed to insert the new records
- Used to insert one or more records into an object

Syntax: insert <Object_Name>;

To Insert One Record:


Syntax: Insert <Object_Name>;
To Insert Multiple Records:
Syntax: Insert <List_Object_Name>; list<Account> acc = new
list<Account>();
Insert acc;

- While Inserting the Records, insert statement will maintain the


Transactions
- Transaction: It is a Logical container, which contains one or more
operations
-Transaction should be either "Commit" or "Rollback"
- Commit: Saving Permanently in the Database
- Rollback : Cancel's the previous operations
- Transaction will be committed, when all the operations are successfully
completed
- Transaction will be Rolledback, if any of the operation fails.

2. Update:
- USed to update the existing records in the object
- We can update one or more records

Syntax:
Update <Object_Name>;

Note: Before Updating the record, we need to fetch the record values(using
SOQL Query) and update with the new values.

3. Delete:
- Used to Delete the existing records from an object
- We can Delete one or more records from the object
Note: To delete the record, ID of the record is enough

Note: Deleted records will be stored into the RecycleBin for 30 days.
If any of the deleted records is older than 30 days, then it will be deleted
permanently from the salesforce

Syntax:
Delete <Object_Name>;

To Delete One Record:


Syntax : Delete <Object_Name>;

To Delete Multiple Records:


Syntax: Delete <List_Object_Name>;

4. Upsert:
- It is a combination of Insert + Update
- If the record is exist, then it will update the record
- IF the record is not exist, then it will create the new record

Syntax:
Upsert <Object_Name>;

5. Undelete:
- USed to Re-store the deleted records from the RecycleBin to actual object

Syntax:
Undelete <Object_Name>;

===========================================
//Inserting Records using Apex DML Statements:

// Inserting a Record....
Account acc = new Account();

acc.Name = 'Apex Record';


acc.rating = 'Hot';
acc.site='IT Department';
acc.Industry = 'Finance';
acc.pan_number__C = 'alppb-4343-r';
acc.passport_number__C = '2342343';
acc.annualrevenue = 200000;
acc.Type = 'Prospect';
acc.active__C = 'Yes';
acc. Delete__c = True;
acc.sic = '23423';

insert acc;
system.debug('Account Record ID is....: '+ acc.id);

// Inserting 2nd Record...


Account acc1 = new Account();

acc1.Name = 'New Record';


acc1.rating = 'Warm';
acc1.site='Admin Department';
acc1.Industry = 'Healthcare';
acc1.pan_number__C = 'alppb-4343-r';
acc1.passport_number__C = '2342343';
acc1.annualrevenue = 400000;
acc1.Type = 'Prospect';
acc1.active__C = 'No';
acc1.sic = '23423';

insert acc1;
system.debug('Account Record ID is....: '+ acc1.id);

// Apex Program to Create a New Record in the Customer Object (Custom Object)

Customer__c cust = new Customer__c();


cust.Name = 'James';
cust.email_id__C = '[email protected]';
cust.contact_number__C = '4455662211';
cust.Country_name__c = 'India';
cust.State_name__c = 'Telangana';
cust.pan_number__C = 'alppb-9293-e';
cust.passport_number__C = '34567iuytr';
cust.mailing_address__c = '#309, SR Nagar, Hyderabad, 500038';

insert cust;

system.debug('Customer Record id is...: '+ cust.id);


--------------------------
// Apex Program to insert 100 records into Account Object using DML Statements.
for(integer counter = 1; counter<=100 ; counter++)
{
// Creating Object for the Account Class
Account acc = new Account();
// Assigning the values for the fields..

acc.Name = 'BulkRecordTest - '+ counter;


acc.Rating = 'Hot';
acc.Industry = 'Healthcare';
acc.Type = 'Prospect';
acc.Active__C = 'Yes';
acc.Site = 'Banking Department';
acc.annualrevenue = 230000;
acc.ssn_number__c = '123456';
acc.Passport_number__C = 'ALPPB9439E';
acc.fax= '4477885522';

// Inserting the record...


insert acc;

// Print the Record Id, if Record inserted...


system.debug('Record Inserted Successfully. Record id is...: '+ acc.id);
}
-----------------------------
// Apex Program to Create an Account Records and and Associated Contact
Record also.

// Inserting a Record....
Account acc = new Account();

acc.Name = 'Parent Record';


acc.Rating = 'Warm';
acc.Industry = 'Chemical';
acc.Type = 'Customer Direct';
acc.Active__C = 'Yes';
acc.Site = 'Admin Department';
acc.annualrevenue = 850000;
acc.Passport_number__C = 'ALPPB9439E';
acc.fax= '4477885522';
acc.ssn_number__c = '2255887744';

insert acc;

system.debug('Account Record ID is....: '+ acc.id);

// Creating Contact Record..

Contact con = new Contact();

con.firstname = 'Suraj';
con.lastname = 'Kumar';
con.email = '[email protected]';
con.Phone = '1233225588';
con.HomePhone = '7788995577';
con.mobilephone = '9955660000';
con.fax = '8855998855';
con.ssn_number__c = '2255887744';

con.accountid = acc.id; // Make this contact to be associated to this


account record

insert con;

system.debug('Contact Record Id is...: '+ con.id);

------------------------
// Apex Program to Create a Contact and Associated to an Account, with
Hardcoded Account Id value.
// Creating Contact Record..

Contact con = new Contact();


con.firstname = 'Ananad';
con.lastname = 'Tripathi';
con.email = '[email protected]';
con.Phone = '1233225588';
con.HomePhone = '7788995577';
con.mobilephone = '9955660000';
con.fax = '8855998855';
con.ssn_number__c = '2255887744';

con.accountid = '00128000004VHBR'; // Make this contact to be associated


to this account record

insert con;

system.debug('Contact Record Id is...: '+ con.id);


-----------------------
// Apex Program to Create an Opportunity and Associated to an Account, with
Hardcoded Account Id value.

Opportunity oppty =new Opportunity();

oppty.Name = 'Sample Opportunity';


oppty.amount = 45000;
oppty.closedate = system.Today().AddDays(5);
oppty.Stagename = 'Need Analysis';

// Hardcode Account Id value.


oppty.Accountid = '00128000004VHBR';

insert oppty;
Governor Limits:
================
- Salesforce provides a shared infrastructure to all the users, so that they can
install their required applications and accessed by their customers.

- If one user making the Salesforce server busy, by performing some continuous
operations, then other users will be in waiting stage. i.e other users are affecting.

To avoid these problems, salesforce introduced "Governor Limits".

These limits are applicable to all the users, who are accessing the salesforce
server.

Note:
While writing the code / Business logic, the developer has to keep in mind
about the governor limits.

Ex:
We can perform max. of 150 DML Operations in a Single Transaction.
Else, salesforce will raise "System.LimitException", which indicates
that you are crossing the Governor Limits for DML operations.

Sol:
To avoid this Exceptions, As a Best Practice, it is always
recommended to avoid the usage of DML statements inside the FOR loop.

- To implement these scenarios, we have to use "Collection classes".

Arrays(Disadvantages):
===============
SubPrograms:
============
-These are the part of the program, which can able to perform some task.
- SubPrograms are used to divide the large / complex functionality into various
small pieces to make it more understandable.

- SubPrograms are sub divided into 2 Types


1. Functions
2. Procedures

Procedure:
----------
- It contains one or more statements in order to perform a particular task.

Note: Procedure doesn't return any value to the calling environment.

Syntax:
-------
<AccessSpecifier> Void <ProcedureName> ([<ParametersList>])
{
// Statements..
....
}

Ex:

public void ShowMessage()


{
// Statements..
...
}

public void Addition(integer x, integer y)


{
// Statements...
...
}
// Write an Apex Program to Perform the Arithmetic operations and print the
result.

public class SampleArithmeticClass


{
public integer x= 100;
public integer y = 400;

public void ShowMessage()


{
system.debug('Welcome to Apex Programming.');
}

public void Addition()


{

system.debug('Addition Result is...: ' + (x+y));


}
public void Subtraction()
{
system.debug('Subtraction Result is...: '+ (x-y));
}

public void Multiply()


{
system.debug('Multiplication result is...: '+ (x*y));
}

public void Division()


{
system.debug('Division Result is...: '+ (x/y));
}
}
Executing the Class:
--------------------
// Creating Object of the class..
SampleArithmeticClass s = new SampleArithmeticClass();

// Accessing class members using object..


s.Addition();
s.Subtraction();
s.Multiply();
s.Division();

Parameterised Procedures:
-------------------------
- If the procedure doesn't have any parameters, then it will provide the static
behaviour.
i.e. whenever we call the procedure, it provides the same result.

- To make the procedure dynamic, we need to supply some input values in-terms
of Parameters.
- We can pass N number of Parameters. with different types of values.
- Each parameter, should indicate the "DataType" and "Parameter Name"

Ex: Integer x, integer y, string str,...etc

Syntax:
public void ProcedureName(<DataType> <Param1>, <DataType>
<Param>,.... ,<DataType> <ParamN>)
{
// Statements;
......
}
Note: While calling the procedure, the user has to supply the values to the
parameters in the Procedure in the same order and type as defined in the
Procedure Definition.

Ex:
public void Addition(integer x, integer y)
{
system.debug(x+y);
}

Calling:
<ObjectName>.Addition(100,450) --> Valid Statement
<ObjectName>.Addition(234, 'ABC') --> Invalid / Error

// Apex Program to perform the Mathematical and String Operations using


Procedures.

public class BasicMathOperations


{
public void Addition(integer x, integer y)
{
system.debug('Addition Result is....: '+ (x+y));
}

public void Subtraction(integer x, integer y)


{
system.debug('Subtraction Result is...: '+ (x-y));
}

public void Multiply(integer x, integer y, integer z)


{
system.debug('Multiply Result is....: '+ (x*y*z));
}
public void Division(integer x, integer y)
{
if(y>0)
system.debug('Division Result is...: '+ (x/y));
else
system.debug('Division Operation Cannot be poerformed');
}

public void Concatenate(string s1, string s2)


{
system.debug('Concatenation Result is....: '+(s1+s2));
}

public void Checkequals(string s1, string s2)


{
if(s1 == s2) // It will ignore the case
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals');
}

public void CheckEqualsWithCase(string s1, string s2)


{
if(s1.equals(s2)) // It will comparing with case sensitive
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals');
}

}
Execution:
-----------
// Creating Object of the class..
BasicMathOperations s = new BasicMathOperations();
// Accessing class members using object..
s.Addition(100,580);
s.Addition(2345,6789);

s.CheckEquals('Ameerpet','ameerpet'); // using "==" operator


s.CheckEqualsWithCase('Ameerpet','ameerpet'); // using "Equals()"

Functions:
==========
It is also a SubPrograms, which contains one or more statements to perform a
particular task, and will return the result to the calling environment.

- We can pass one or more parameters to the function.


- function should have the return type other than "Void"

Note:
Function should return the value by using "Return" statement.

Syntax:
-------
<AccessSpecifier> <DataType> <FunctionName> ([<Parameters>])
{
// Statements..
....

Return <Result Value>;


}

// Apex Class to demonstrate Functions...

public class FunctionsSample


{
public integer Addition(integer x, integer y)
{
return (x+y);
}

public integer Multiplication(integer x, integer y, integer z)


{
return (x*y*z);
}

public string Concatenate(string s1, string s2)


{
return (s1+s2);
}

public Boolean CheckEquals(string s1, string s2)


{
return s1.equals(s2);
}

Execution:
---------
// Creating Object of the class..
FunctionsSample s = new FunctionsSample();

// Accessing class members using object..

integer result;
result = s.Addition(123,478);
system.debug('Addition Result is...: '+ result);

integer addResult = s.Addition(1254,7895);


system.debug('Addition Result is....: '+ addResult);

system.debug('Addition Result is....: ' + s.Addition(9000,34555));


// Calling CheckEquals Function...
Boolean isEquals = s.CheckEquals('Salesforce','Salesforce');
if(isEquals)
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals');

// Concatenation Function...
system.debug('Concatenation result is....: '+ s.Concatenate('Welcome ', 'To
Salesforce'));

Constructors:
=============
- Constructor is a Special Member Function, which will execute automatically
whenever the user creates an object of the class.
- Constructors are used to assign some pre-defined values to the variables, while
loading the application

While creating the constructors,we have to follow the following rules.

1. Constructor Name should be same as the Class Name.


2. Constructor should be always "Public"
3. It doesn't accept any return type even "Void"
4. We can pass the parameters to the constructors
5. We can have one / more constructors in a class.
6. If the constructor contains any parameters, then we have to supply the values
for the parameters while creating the object of the class.
7. Constructor doesn't return any value.

Note:
While compiling the class code, Apex Compiler will verify wether the user
has provided the default constructor for the class or not.
If yes, then it will execute the userdefined constructor.
Else, the Apex Compiler will creates a Default constructor for the class and
execute the statements.

Example:
public class ConstructorSample
{
public ConstructorSample()
{
system.debug('This is the Default Constructor.');
}

public ConstructorSample(string str)


{
system.debug('This is Parameterized constructor..: ' + str);
}

public ConstructorSample(integer accountNumber, string customerName)


{
system.debug('This is Parameterized constructor with 2 Parameters.');
system.debug('Account Number ---> ' + accountNumber);
system.debug('Customer Name ---> ' + customerName);
}
}

Execution:
----------
// Creating Object of the class..
ConstructorSample s = new ConstructorSample();

ConstructorSample s1 = new ConstructorSample();

ConstructorSample s2 = new ConstructorSample();

// Calling Parameterized constructor...


ConstructorSample s3 = new ConstructorSample('Welcome');

// Calling Parameterized constructor...


ConstructorSample s4 = new ConstructorSample(10001, 'Suresh Kumar');

DML Statements in Salesforce:


=============================
- Using DML Statements we Can Performs operations on the records in the Object
- We can perform the operation on either one record or on multiple records
- We can perform the operations on records of Standard Obejct or Custom Object

CRUD --> C (Create / Inse) , R (Read), U (Update / Edit), D(Delete)

Salesforce provides the following DML Statements...

1. Insert:
- USed to insert the new records
- Used to insert one or more records into an object

Syntax: insert <Object_Name>;

To Insert One Record:


Syntax: Insert <Object_Name>;
To Insert Multiple Records:
Syntax: Insert <List_Object_Name>;

- While Inserting the Records, insert statement will maintain the


Transactions
- Transaction: It is a Logical container, which contains one or more
operations
-Transaction should be either "Commit" or "Rollback"
- Commit: Saving Permanently in the Database
- Rollback : Cancel's the previous operations
- Transaction will be committed, when all the operations are successfully
completed
- Transaction will be Rolledback, if any of the operation fails.

2. Update:
- USed to update the existing records in the object
- We can update one or more records

Syntax:
Update <Object_Name>;

Note: Before Updating the record, we need to fetch the record values(using
SOQL Query) and update with the new values.

3. Delete:
- Used to Delete the existing records from an object
- We can Delete one or more records from the object
Note: To delete the record, ID of the record is enough

Note: Deleted records will be stored into the RecycleBin for 30 days.
If any of the deleted records is older than 30 days, then it will be deleted
permanently from the salesforce

Syntax:
Delete <Object_Name>;

To Delete One Record:


Syntax : Delete <Object_Name>;

To Delete Multiple Records:


Syntax: Delete <List_Object_Name>;

4. Upsert:
- It is a combination of Insert + Update
- If the record is exist, then it will update the record
- IF the record is not exist, then it will create the new record
Syntax:
Upsert <Object_Name>;

5. Undelete:
- USed to Re-store the deleted records from the RecycleBin to actual object

Syntax:
Undelete <Object_Name>;

===========================================
//Inserting Records using Apex DML Statements:

// Inserting a Record....
Account acc = new Account();

acc.Name = 'Apex Record';


acc.rating = 'Hot';
acc.site='IT Department';
acc.Industry = 'Finance';
acc.pan_number__C = 'alppb-4343-r';
acc.passport_number__C = '2342343';
acc.annualrevenue = 200000;
acc.Type = 'Prospect';
acc.active__C = 'Yes';
acc.sic = '23423';

insert acc;
system.debug('Account Record ID is....: '+ acc.id);

// Inserting 2nd Record...


Account acc1 = new Account();

acc1.Name = 'New Record';


acc1.rating = 'Warm';
acc1.site='Admin Department';
acc1.Industry = 'Healthcare';
acc1.pan_number__C = 'alppb-4343-r';
acc1.passport_number__C = '2342343';
acc1.annualrevenue = 400000;
acc1.Type = 'Prospect';
acc1.active__C = 'No';
acc1.sic = '23423';

insert acc1;
system.debug('Account Record ID is....: '+ acc1.id);

// Apex Program to Create a New Record in the Customer Object (Custom Object)

Customer__c cust = new Customer__c();

cust.Name = 'James';
cust.email_id__C = '[email protected]';
cust.contact_number__C = '4455662211';
cust.Country_name__c = 'India';
cust.State_name__c = 'Telangana';
cust.pan_number__C = 'alppb-9293-e';
cust.passport_number__C = '34567iuytr';
cust.mailing_address__c = '#309, SR Nagar, Hyderabad, 500038';

insert cust;

system.debug('Customer Record id is...: '+ cust.id);


--------------------------
// Apex Program to insert 100 records into Account Object using DML Statements.

for(integer counter = 1; counter<=100 ; counter++)


{
// Creating Object for the Account Class
Account acc = new Account();
// Assigning the values for the fields..

acc.Name = 'BulkRecordTest - '+ counter;


acc.Rating = 'Hot';
acc.Industry = 'Healthcare';
acc.Type = 'Prospect';
acc.Active__C = 'Yes';
acc.Site = 'Banking Department';
acc.annualrevenue = 230000;
acc.ssn_number__c = '123456';
acc.Passport_number__C = 'ALPPB9439E';
acc.fax= '4477885522';

// Inserting the record...


insert acc;

// Print the Record Id, if Record inserted...


system.debug('Record Inserted Successfully. Record id is...: '+ acc.id);
}
-----------------------------
// Apex Program to Create an Account Records and ans Associated Contact
Record also.

// Inserting a Record....
Account acc = new Account();

acc.Name = 'Parent Record';


acc.Rating = 'Warm';
acc.Industry = 'Chemical';
acc.Type = 'Customer Direct';
acc.Active__C = 'Yes';
acc.Site = 'Admin Department';
acc.annualrevenue = 850000;
acc.Passport_number__C = 'ALPPB9439E';
acc.fax= '4477885522';
acc.ssn_number__c = '2255887744';

insert acc;

system.debug('Account Record ID is....: '+ acc.id);

// Creating Contact Record..

Contact con = new Contact();

con.firstname = 'Suraj';
con.lastname = 'Kumar';
con.email = '[email protected]';
con.Phone = '1233225588';
con.HomePhone = '7788995577';
con.mobilephone = '9955660000';
con.fax = '8855998855';
con.ssn_number__c = '2255887744';

con.accountid = acc.id; // Make this contact to be associated to this


account record

insert con;

system.debug('Contact Record Id is...: '+ con.id);

------------------------
// Apex Program to Create a Contact and Associated to an Account, with
Hardcoded Account Id value.

// Creating Contact Record..

Contact con = new Contact();


con.firstname = 'Ananad';
con.lastname = 'Tripathi';
con.email = '[email protected]';
con.Phone = '1233225588';
con.HomePhone = '7788995577';
con.mobilephone = '9955660000';
con.fax = '8855998855';
con.ssn_number__c = '2255887744';

con.accountid = '00128000004VHBR'; // Make this contact to be associated


to this account record

insert con;

system.debug('Contact Record Id is...: '+ con.id);


-----------------------
// Apex Program to Create an Opportunity and Associated to an Account, with
Hardcoded Account Id value.

Opportunity oppty =new Opportunity();

oppty.Name = 'Sample Opportunity';


oppty.amount = 45000;
oppty.closedate = system.Today().AddDays(5);
oppty.Stagename = 'Need Analysis';

// Hardcode Account Id value.


oppty.Accountid = '00128000004VHBR';

insert oppty;

Governor Limits:
================
- Salesforce provides a shared infrastructure to all the users, so that they can
install their required applications and accessed by their customers.
- If one user making the Salesforce server busy, by performing some continuous
operations, then other users will be in waiting stage. i.e other users are affecting.

To avoid these problems, salesforce introduced "Governor Limits".

These limits are applicable to all the users, who are accessing the salesforce
server.

Note:
While writing the code / Business logic, the developer has to keep in mind
about the governor limits.

Ex:
We can perform max. of 150 DML Operations in a Single Transaction.
Else, salesforce will raise "System.LimitException", which indicates
that you are crossing the Governor Limits for DML operations.

Sol:
To avoid this Exceptions, As a Best Practice, it is always
recommended to avoid the usage of DML statements inside the FOR loop.

- To implement these scenarios, we have to use "Collection classes".

Arrays (Disadvantages)

1. It supports similar type of elements


2. Array size can't be shrink / grow dynamically at runtime (i.e fixed size)
3. Supports static memory allocation.
4. we cannot insert the elements in middle of the array at run time.
5. No ready made functions to perform the operations on array elements.

- To avoid the above peroblems, salesforce provides Collection classes.

Collection Classes:
===================
Collection classes provide the following benifits.

1. We can perform the operations on the group of elements of different type


2. Collection size can be grow / Shrink dynamically at run time.
3. Collections supports the dynamic memory allocation
4. We can insert / update / delete the elements from the collections using ready
made functions

Salesforce provides the following Collection classes


1. List
2. Set
3. Map

List Collection Class:


======================
- Used to perform the operations on group of elements of heterogeneous types.
-List will support the values of Premitive Types, Collection Types, SObject Types,
Apex Types and User Defined Types.
- List is an Ordered Collection. i.e. Elements will be avialable in the collection, in
the same order in which we have inserted.
- Each element in the collection will be identified by using "Index position"
- List Collection elements index will be starting from "Zero"
- List supports Dynamic Memory allocation, in order to utilize the memory
efficiently.
- List Collection size can Grow / Shrink at run time.
- List Collection class provides a set of readymade methods to perform the
operations on the elements.
- List will accept Duplicate Elements also.

Syntax:
List<DataType> <ObjectName> = new List<DataType>();
or
List<DataType> <ObjectName> = new List<DataType>{<elements
collection>};

Ex:
List<string> lstNames = new List<string>(); --> Collection of string elements

List<Account> lstAccounts = new List<Account>(); --> Collection of Account


Records

List<Position__c> lstPositions = new List<Position__c>(); --> Collection of


Position Records

List<List<string>> lstCol = new List<List<string>>();

Note: We can able to create the Nested List (i.e. one List onto another List), upto
5 Levels.

Ex: List<List<List<List<List<>>>>> lst = new List<List<List<List<List<>>>>>();

Note:
List Collection will accept the Duplicate elements also.

Methods:
--------
1. Add(<ElementName>)
- This method will add the specified element at the end of the collection.
- Once the element is added to the collection, List will generates the index
position for the element.

Ex: lstNames.Add('Welcome');
lstNames.Add('Salesforce');
lstNames.Add('12345');

2. Add(elementName, integer indexposition)


- This method will insert the specified element at the given index position in
the collection.

Ex: lstNames.Add('Hyderabad',1);

3. AddAll(<CollectionName>)
- This method will add All the elements avialable in the specified collection
to the end of the list.

4. Get(indexposition)
- It will return the element exist in the specified index position in collection.

Ex: lstNames.get(2);

5. Sort()
- It will arrange the collection elements in the ascending order.

Ex: lstNames.Sort();

6. integer Size()
- It will returns an integer, which indicates the number of elements
available in the collection.

Ex: lstNames.size();

7. Remove(<indexposition>)
- This method will remove the element from the collection exist at the
specified index position.

Ex: lstNames.Remove(2);

8. Clear()
- It will remove all the elements from the collection.

Ex: lstNames.Clear();
9. Set(index postition, elementName)
- It will update the elementName with the specified value exist at the
specified index position.

Ex: lstNames.Set(2, 'Apex Programming');

Sample Example:
---------------
// Creating the Object for List Collection class...
List<string> lstNames = new List<string>();

// Print the collection size...


system.debug('Collection size is.....: ' + lstnames.size());

// Adding Elements to collection...

lstnames.Add('Ramesh Kumar');
lstnames.Add('Welcome');
lstnames.Add('Salesforce');
lstnames.Add('Hyderabad');
lstnames.Add('India');

// Print the collection size...


system.debug('After inserting elements Collection size is.....: ' + lstnames.size());

// check for Collection is Empty or not?


if(lstnames.isEmpty())
system.debug('Collection is Empty');
else
system.debug('Collection is Not Empty');

// Adding Duplicate Elements...


lstnames.Add('Salesforce');
system.debug('After inserting Duplicate, Collection size is.....: ' + lstnames.size());
// Adding Group of elements...
string[] countries = new string[]{'India','USA','UK','Japan','Germany','Austraslia'};
lstnames.AddAll(countries);
system.debug('After inserting Bulk, Collection size is.....: ' + lstnames.size());

// Print the Collection Elements..


system.debug('Collection Elements are....: ' + lstnames);

// Print the Elements in seperate lines...


system.debug('Collection Elements are....: ');
for(integer index=0; index < lstnames.size(); index++)
{
system.debug('Element Name ---> '+ lstnames.get(index));
}

// Print the Elements using Enhanced FOR loop..

system.debug('Collection Elements (using Enhanced FOr Loop)');


for(string st : lstnames)
{
system.debug('Element Name : ' + st);
}

// Print the Element exist at specified Index position..


system.debug('Element At Index Position 4 is....: ' + lstnames.get(4));

// Insert the element at the specified position...

lstnames.Add(4, 'Russia');
system.debug('Collection Elements After inserting in middle...: ');
for(string st : lstnames)
{
system.debug('Element Name : ' + st);
}
// Remove an element from the collection...
lstnames.remove(4);
system.debug('After Removing Elements...: ');
for(string st : lstnames)
{
system.debug('Element Name : ' + st);
}

// Sorting the Elements...


lstnames.sort();
system.debug('After Sorting Elements are...: ');
for(string st : lstnames)
{
system.debug('Element Name : ' + st);
}

// Updating Element value...


lstnames.Set(2, 'Praksah Kumar');
system.debug('After Updating Elements are...: ');
for(string st : lstnames)
{
system.debug('Element Name : ' + st);
}

// Remove all elements from collection..


lstnames.clear();
system.debug('Collection Elements are....: ' + lstnames);

SET Collection Class:


=====================
- It also provides the ability to manage a group of elements.
- Set is an UnOrdered collection. i.e. it won't preserve the insertion order.
- Set supports the Dynamic memory allocation.
- Set collection supports to manage the elements of type Premitive Types,
Collection Types, SObject Type, Apex Types and User Defined Types.

Note:
SET collection, doesn't allow the duplicate elements.
i.e. If the user insert's a duplicate element, then SET doesn't add that
element into the collection. And It won't display any error message.

- SET doen't maintain any index for the elements.

SET Collection class provides the below methods..

Syntax:
Set<DataType> <ObjectName> = new Set<DataType>();

Ex:
Set<Id> idSet = new Set<Id>();
Set<String> namesSet = new Set<String>();

Note:
SET and LIST collection classes will treat each element as an Object by
default.

1. Add(<ElementName>):
- This method will add a new element to the collection.

Ex: namesSet.Add('Welcome');

2. AddAll(<List / SET Collection>):


- This method will add all the elements available in the collection to the SET
elemements.
- If the source collection is having any duplication, it will eleminate the
duplicate elements.

Ex:
namesSet.AddAll(coutrySet); // Set Collection
namesSet.AddAll(cityList); // List Collection

3. Boolean isEmpty()
- It returns TRUE, the Set Collection is Empty. Else it returns FALSE.

Ex: namesSet.isEmpty();

4. integer Size()
- It returns an integer, which counts the number of elemements exist in the
collection.

Ex: namesSet.Size();

5. Remove(<elementName>)
- It remove the specified elemement from the collection

Ex:
namesSet.Remove('Welcome');

6. Clear()
- It remove all the elemements from the collection.

Ex: namesSet.Clear();

7. Clone()
- It creates a copy of the Set collection.

Ex: namesSet.Clone();

// Eample...

// Creating Object for Set Collection...


Set<string> namesSet = new Set<string>();
// Print the Collection size...
system.debug('Collection size is....: ' + namesSet.size());

//Cehck whether the collection is Empty or Not?


Boolean isSetEmpty = namesSet.isEmpty();
if(isSetEmpty)
system.debug('Collect is Empty.');
else
system.debug('Collection is Not Empty.');

// Adding Elements to the Collection...


namesSet.Add('Welcome');
namesSet.Add('India');
namesSet.Add('Salesforce');
namesSet.Add('Hyderabad');
namesSet.Add('Australia');
namesSet.Add('Collection Classes');

// Print the Collection elements...


system.debug('Collection elements are....: '+ namesSet);

// Print the Elements...


system.debug('Collection Elements....: ');
for(string st : namesSet)
{
system.debug('Element Name ---> '+st);
}

// Print the Collection size...


system.debug('Collection size is....: ' + namesSet.size());

// Adding Duplicate elements to Collection...


namesSet.Add('Salesforce');
// Print the Collection size...
system.debug('After Adding Duplicate Collection size is....: ' + namesSet.size());

// Adding Duplicate elements to Collection(With LowerCase letters)...


namesSet.Add('hyderabad');

// Print the Collection size...


system.debug('After Adding With CaseSensitive Collection size is....: ' +
namesSet.size());

// Remove Elements from Collection...


namesSet.Remove('Salesforce');
system.debug('After Removal Collection Elements are....: ');
for(string st : namesSet)
{
system.debug('Element Name ---> '+st);
}

// Remove all elements from collection...


namesSet.Clear();
system.debug('After Removing all Elements Collection size is....: ' +
namesSet.size());

MAP Collection class:


=====================
- It is a Key-Value pair collection, where each elemement contains two parts (Key
and a Value)

- Map supports dynamic memory allocation.


- We can add one or more elemements to the collection
- Key should be a unique always in MAP collection.
- Value may be Unique / Duplicate also.

--> Key should be always a Premitive Type (String / ID / Boolean / Integer....etc)


--> Value may be either Premitive / Collection Type / SObject Type / Apex Type /
User Defined Type.

Note:
To get the elments from the collection, we have to pass the KEY.

Syntax:
Map<Key,Value> mapObject = new Map<Key, Value>();

Ex:
Map<string, string> lstNames = new Map<string, string>();

Map<ID,Account> mapAccounts = new Map<ID, Account>();

Map<ID,List<Account>> mapAcc = new Map<>(id, List<Account>);

Map collection provides the following functions..

1. Put(<Key>,<Value>)
- This function will add the new elemement to MAP collection.

Ex: mapNames.Put('Welcome','Salesforce');

2. Integer Size()
- It returns an ineger, which indicates number of elements exist in the
collection.

Ex: mapNames.size()

3. Set<> KeySet()
- It returns all the Key's exist in the map collection interns of SET collection.

Ex:
Set<string> keys = mapNames.KeySet();
4. List<> Values()
- It returns all the Values exist i the map collection interms of List
Collection.

Ex: List<string> valuespair = mapNames.values();

5. Get(<KeyName>)
- It returns the value of the given Key element.

Ex: mapNames.Get('Welcome');

6. Bollean isEmpty();
- It returns TRUE, when the collection is Empty. Else it returns FALSE.

Ex: mapNames.isEmpty();

7. Remove(<KeyName>)
- It will remove the elemement from the collection, which is associated with
the given Key.

Ex: mapNames.Remove('Welcome');

8. Clear()
- It remove all the elemements from the collection.

Ex: mapNames.Clear();

// Example....

// Creating Object for Map Collection...


Map<string, string> namesMap = new Map<string, string>();

// Print the Collection Size...


system.debug('Collection Size is....: ' + namesMap.size());
// Check whether collection is Empty or Not...
Boolean hasElements = namesMap.isEmpty();
if(hasElements)
system.debug('Collection is Empty.');
else
system.debug('Collection is Not Empty.');

// Adding Elements to Collection...


namesMap.Put('Black','Grapes');
namesMap.Put('Yellow','Banana');
namesMap.Put('Red','Cherry');
namesMap.Put('Green','Mango');
namesMap.Put('Orange','Orange');

system.debug('Collection Elements are....: ' + namesMap);

// Get the Element values based on Key..


system.debug('Fruit Name for the Color Black is...: ' + namesMap.get('Black'));

// Adding Duplicate Key with a New Value...


namesMap.Put('Red','Apple');
system.debug('After Adding Duplicate - Collection Elements are....: ' +
namesMap);

// Get All Key's Collection...


Set<string> keysCollection = namesMap.KeySet();

// Print Alll Elements...


for(string st : keysCollection)
{
system.debug('Key : ' + st + ' ----> Value is :' + namesMap.Get(st));
}

// Print All Element values...


for(string elementValue : namesMap.values())
{
system.debug('Eelement value is....: ' + elementValue);
}

// Remove element from the collection...

namesMap.Remove('Red');

system.debug('After removing the element....: ');


for(string elementValue : namesMap.values())
{
system.debug('Eelement value is....: ' + elementValue);
}

// Remove all elements from collection...


namesMap.Clear();

system.debug('Collection Size is....: ' + namesMap.size());

Bulkify DML Operations:

- While performing the DML operations, salesforce provides the governor limits,
which allows us to perform max. of 150 DML operations in a single transaction.
- To perform more DML operations, we have to use "Bulkify DML operations",
which can be implemented by using collection classes.
- Always it is recommended to use "List" collection class to peform the DML
statements.

Example... To insert 200 records using List Collection..


==========
// Creating List Collection to store Account Records...
List<Account> lstAccount = new List<Account>();

// Add Elements to Collection...


for(integer counter =1 ; counter <= 200; counter++)
{
// Creating Object for the Account Class
Account acc = new Account();

// Assigning the values for the fields..


acc.Name = 'Bulkify Test Record - '+ counter;
acc.Rating = 'Hot';
acc.Industry = 'Healthcare';
acc.Type = 'Prospect';
acc.Active__C = 'Yes';
acc.Site = 'Banking Department';
acc.annualrevenue = 230000;
acc.ssn_number__c = '123456';
acc.Passport_number__C = 'ALPPB9439E';
acc.fax= '4477885522';

// Add record to Collection...


lstAccount.Add(acc);

// Insert the Records into Object...


insert lstAccount;

Database Class:

- Used to Perform the Dynamic Operations in the Database.


- Used to perform the operations in the Database Records.
- We can perform the SOQL operations, DML Operations and Transaction
statements.
Methods:

Database.Query(<Select Query>) --> USed to Retrieve the data from the object by
using the Query

Database.Insert(<OjectName>) --> Insert the records into the object

Database.Update(<ObjectNAme>) --> Update the Records in the Database

Database.Delete(<Object Name>) --> Delete the Records from Object

Database.Upsert(<OjectName>) --> To Perform Insert / Update operation in the


object

Database.SaveResult --> To get the Status of the Inserted Records (Inserted /


Failed)

Database.Insert():
==================
- We can insert one / more records at a time.
- Provides the option to allow partial processing.
- we can track the result of each operation (Success / Failed)

Syntax:
Database.insert(<ListObjectname>, boolean allowPartialProcessing);

ListObjectname : Specify the ObjectName, which requires to be insert.


Boolean allowPartialProcessing : To Indicate allow the partial processing
TRUE: Rollback the Transaction, if any of the record fails.
FALSE: Continue with the remaining records, if any operation fails.

Note: Default value is TRUE.

Tracking the Record Status: During Insertion.


=====================================
Database.SaveResult:

- This class is used to track the status of each operation


- we can track whether the record is inserted or failed.

Methods:

isSuccess() -- Returns TRUE, if the record is successfully inserted. Else returns


FALSE
getID() -- To get the ID of the inserted record.
Database.Error getErrors() -- To get all the errors occured during record
insertions.
Return type of this method is "Database.Error".

Database.Error: Class
--------------------
- To track the Error messages occured during the record processing.

Methods:
1. getFields() --> Returns the fields which causes the errors
2. getErrorMessage() --> Returns the Error Message
3. getStatusCode() --> return the Status code of the error.

Example...
----------
// Creating List Collection to store Account Records...
List<Account> lstAccount = new List<Account>();

// Add Elements to Collection...


for(integer counter =1 ; counter <= 200; counter++)
{
// Creating Object for the Account Class
Account acc = new Account();

// Assigning the values for the fields..


if(counter != 195)
{
acc.Name = 'Insert Bulk Records - '+ counter;
}
acc.Rating = 'Hot';
acc.Industry = 'Healthcare';
acc.Type = 'Prospect';
acc.Active__C = 'Yes';
acc.Site = 'Banking Department';
acc.annualrevenue = 230000;
acc.ssn_number__c = '123456';
acc.Passport_number__C = 'ALPPB9439E';
acc.fax= '4477885522';

// Add record to Collection...


lstAccount.Add(acc);

// Insert the Records into Object...


Database.SaveResult[] results = Database.insert(lstAccount,false);

// Track the Results...


for(Database.SaveResult res : results)
{
if(res.isSuccess())
{
System.debug('Record Inserted Successfully. Record Id is...: ' +
res.getID());
}
else
{
for(Database.Error err : res.getErrors())
{
system.debug('Error Message Is....: ' + err.getMessage());
system.debug('Error Status Code is...: ' + err.getStatusCode());
system.debug('Field Effected are....: ' + err.getFields());
}
}
}

SOQL Queries:
SOQL --> Salesforce Object Query Language.

-SOQL Queries are used to retrieve the records from salesforce objects(Standard /
Custom).

- We can retrieve one or more records from the object based on user defined
conditions to filter the records.

- We can fetch the records from one or more salesforce objects.

- To get the required records, we need to prepare an SOQL Query with the
reruired conditions.

Query:
------
Query is a request to the database to fetch records from database objects
based on required filters.

- We need to prepare the SOQL query by using the below syntax.

- SOQL Queries can be prepared by using "SELECT" statement.


Syntax:
-------
SELECT <Column_Names> FROM <ObjectName>
[ WHERE <Conditions> ] // Optional..
[ GROUP BY <Column_Names> ] // Optional..
[ HAVING <Conditions> ] // Optional..
[ ORDER BY <Column_Names> <ASC/DESC> ] // Optional..
[ LIMIT <Number Of Records To Display> ] // Optional..
[ OFFSET <Number Of Records to Skip> ] // Optional..
[ ALL ROWS ] // Optional..
[ FOR UPDATE ] // Optional..

Note:
Column_Names : Use "Field Name" value of the field (Standard Field). If it is a
Custom field, then use "API Name (postfixed by __c)".

ObjectName : Use API Name of Object, if it is defined by user.

Note: We can retrieve the data from multiple columns. Where column names has
to be seperated by a comma.

Syntax:

SELECT <Column1>, <Column2>, <Column3>, .....<ColumnN> FROM


<ObjectName>.

// SOQL Query to retrive Account Name, Rating, Industry and AnnualRevenue


value from the Account object.

SELECT name, rating, industry, annualrevenue from Account.

Executing SOQL Queries using Developer Console:


===============================================
Goto your Name --> Click on "Developer Console".
1. Click on "Query Editor" Tab in the bottom Tab Bar of Developer Console.
2. Write the SOQL Query.
3. Click on "Execute" button.
4. View the results in result window.

Governor Limits:
----------------
1. We can have maximum of 100 SOQL Queries in a single transaction.

2. Each SOQL Query can return maximum of 50,000 records.

// SOQL Query to display Contact FirstName, lastname, emailid, phone number,


title and fax of the contact records.

select firstname, lastname, email, phone, fax, title, mobilephone from contact.

// SOQL Query to display Account Name, Rating, Id, Active Status, Pan Number
from account object.

select id, name, rating, active__C, pan_number__c from account.

// SOQL Query to retrieve Position Id, Name, Status, Location, close date and
maximum pay values from position object.

select position_id__C, name, position_status__c, location__c, maximum_pay__c,


close_date__C from position__C.

SOQL Query Types:


=================
-Salesforce provides 2 types of SOQL Queries
1. Static SOQL Queries
2. Dynamic SOQL Queries.

Static SOQL Statements:


-----------------------
- By using Static SOQL, we can retrieve records from one or more objects by using
user defined conditions.

Note:
Static SOQL query should be enclosed in "[ ]" (Square Braces)

Syntax:
[ <SOQL Query> ];

Static SOQL statements will be executed automatically by the force.com platform.

Ex:
[ select id, name, rating, industry from account ];
[ select firstname, lastname, phone, email, fax from contact];
[ select position_id__c, name, location__c, position_status__C from
position__c ];

LIMIT Clause:
=============
This clause is used to restrict the number of records to be returned by an SOQL
statement.

Syntax:
[ LIMIT <Number Of Records To Return> ];

Note: Limit clause is an optional statement in SOQL Query.


We need to specify a Number, which indicates the number of records to be
returned by SOQL query. If the user didn't specify any number, then SOQL query
will return all records from the object upto max of 50000 records.

Ex: limit 10, limit 1 , limit 5, limit 100, limit 2.

Ex:
1. select id, name, rating, industry from account limit 1

2. select position_id__C, name, position_status__c, location__c,


maximum_pay__c, close_date__C from position__C limit 5

Note: While executing static SOQL Query, it may return either one or mor records.

1. IF SOQL Query Returns Only One Record:


-----------------------------------------
If the Quer returns only one record, then we need to create an object of
the associated record and store the result into the object.

Ex:
Account acc = [select id, name, rating, industry from account limit 1];

We need to display the record values by using below syntax


Syntax:
<object name>.<Field Name>

Ex:
system.debug('Account Id is....: ' + acc.id);
system.debug('Account Name is....: ' + acc.name);
system.debug('Account Rating is....: ' + acc.rating);

// write an Apex Program to fetch Position record and display the record values.

Note: Write the below code in "Execute Ananymous window" and execute it.
Position__C pos = [select position_id__c, name, location__C, position_status__c,
close_date__c, maximum_pay__c from position__c limit 1];

if(pos != null)
{
system.debug('Position Id is.....: ' + pos.position_id__c);
system.debug('Position Name is....: ' + pos.name);
system.debug('Position Location ....: '+ pos.location__c);
system.debug('Position Status is....: ' + pos.position_status__c);
system.debug('Close Date is......: ' + pos.close_date__c);
system.debug('Maximum Pay is.....: ' + pos.maximum_pay__c);
}

2. IF SOQL Query Returns multiple Records:


-----------------------------------------
- If the SOQL query returns more than one record, then we need to store the
result in a collection object.

- Once all the records has stored inside the collection, we need to fetch each
record from the collection and get the values from the record.

Syntax:
List<SObjectType> <ObjectName> = [ <SOQL Query returns more
records> ];

Ex:
List<Account> lstAccounts = [select id, name, rating, industry from account
limit 5 ];

List<Account> lstAccounts = [select id, name, rating, industry from account


limit 2 ];
List<Account> lstAccounts = [select id, name, rating, industry from
account];

// Write an apex program to display first 10 records from Account object.

List<Account> lstAccounts = [select name, rating, industry, annualrevenue, type,


active__c from account limit 10];

system.debug('Collection size is....: ' + lstAccounts.size());

// Display records....
if(! lstAccounts.isEmpty())
{
for(Account acc : lstAccounts)
{
system.debug('Account Name is....: ' + acc.name);
system.debug('Account Rating is....: ' + acc.rating);
system.debug('Account Type is....: ' + acc.type);
system.debug('Industry Name is....: ' + acc.industry);
system.debug('Annual Revenue is....: ' + acc.annualrevenue);
system.debug('Active Value is....: ' + acc.active__C);
system.debug('-----------------------------------------------');
}

// Write an apex program to display first 10 records from Lead object.

List<Lead> lstLeads = [select firstname, lastname, email, fax, phone, status from
lead limit 10];

system.debug('Collection size is....: ' + lstLeads.size());

if(!lstLeads.isEmpty())
{
for(lead ld : lstLeads)
{
system.debug('Lead First Name is....: ' + ld.firstname);
system.debug('Last Name is....: ' + ld.lastname);
system.debug('Email Id is....: ' + ld.email);
system.debug('Phone Number is....: ' + ld.phone);
system.debug('Lead Status is....: ' + ld.status);
system.debug('-----------------------------------');
}
}

// Write an apex program to display first 10 leads from Lead object using MAP
collection.

Map<Id, Lead> mapLeads = new Map<Id, Lead>([select id, firstname, lastname,


email, phone, status from lead limit 10]);

system.debug('Collection size is....: ' + mapLeads.size());

if(! mapLeads.isEmpty())
{
for(Lead ld : mapLeads.Values())
{
system.debug('Lead Id is....: ' + ld.id);
system.debug('Lead First Name is....: ' + ld.firstname);
system.debug('Last Name is .....: ' + ld.lastname);
system.debug('Email Id is.....: ' + ld.email);
system.debug('Phone Number is....: ' + ld.phone);
system.debug('Lead Status is.....: ' + ld.status);
system.debug('------------------------------------------');
}

}
// Write an Apex program to display the first 5 opportunity records from
opportunity object using Enhanced FOR Loop.

for(Opportunity oppty : [select id, name, stagename, closedate from opportunity


limit 5])
{
system.debug('Opportunity Id is.....: ' + oppty.Id);
system.debug('Opportunity Name is.....: ' + oppty.Name);
system.debug('Opportunity Stage is.....: ' + oppty.Stagename);
system.debug('Opportunity Close Date is....: ' + oppty.closedate);
system.debug('---------------------------------------------------');
}

WHERE Clause:

- WHERE clause is used to filter the records, returned by SOQL query.


- To filter the records, we can use one or more conditions.
- We have to add the conditions to Where clause, which is appended to SOQL
query.

Note:
1. Using WHERE clause is an optional statement in SOQL Queries.

2. If the user didn't use the WHERE clause, then SOQL query will returns all
the records from the object.

Note: While using the Multiple conditions / Compound Conditions, we need to


use Logical operators.

- User needs to define his own conditions based on one or more columns as
below.

Syntax:
[WHERE <Conditions>]

Ex: [WHERE <condition1> <Logical Operator> <Condition2>


<Logical Operator> ...... <ConditionN>]

Note: Each condition should be prepared with the below syntax.


Syntax:
<Column Name> <Operator> <Value>

Ex: Rating = 'Hot'


Industry = 'Banking'
AnnualRevenue > 100000

// Write an Apex Program to display Account Name, Rating, Industry, Annual


Revenue, Active Status field values from Account object Whose Rating is
'Warm'.

Query:

select name, rating, industry, annualrevenue, active__c from account where


rating = 'Warm'

Code:
-----
List<Account> lstAccounts = [select name, rating, industry, annualrevenue,
active__c from account where rating =: 'Warm'];

system.debug('Resultset Count.....: ' + lstAccounts.size());

if(!lstAccounts.isEmpty())
{
for(Account acc : lstaccounts)
{
system.debug('Account Record is.....: ' + acc);
}
}

// Write an Apex Program to display position records information, whose status


is "New Position".

for(Position__C pos : [select position_id__c, name, position_status__C,


location__C, close_date__c from position__C where position_status__C =: 'New
Position' ] )
{
system.debug('Position Id is....: ' + pos.position_id__C);
system.debug('Position Name is....: '+ pos.name);
system.debug('Position Location ....: ' + pos.location__c);
system.debug('Position Status is.....: ' + pos.position_status__c);
system.debug('Close Date is.....: ' + pos.close_date__c);
system.debug('-------------------------------------------');
}

// Write an Apex Program to display Account records, which are "InActive" and
Whose AnnualRevenue is morethan 100000.

Map<ID, Account> mapAccounts = new Map<ID, Account>([select id, name,


rating, annualrevenue, active__C,recordtype.name from account where active__c
=: 'No' and Annualrevenue > 100000 ]);
system.debug('Collection Size is....: ' + mapAccounts.size());

if(!mapAccounts.isEmpty())
{
for(Account acc : mapAccounts.values())
{
system.debug('Account Id is.....: ' + acc.id);
system.debug('Account Name is....: ' + acc.name);
system.debug('Account Rating Value is....: ' + acc.rating);
system.debug('Annual Revenue is.....: ' + acc.annualrevenue);
system.debug('Active Status is......: ' + acc.active__C);
system.debug('Record Type Name is....: ' + acc.recordtype.name);
system.debug('-------------------------------------------');
}
}

// Write an Apex program to display All recordtypes associated with Account


Object.

List<RecordType> lstRecTypes = [select id, name, sobjecttype from recordtype


where sobjecttype =: 'Account'];

if(!lstRecTypes.isEmpty())
{
for(RecordType rType : lstRecTypes)
{
system.debug('Record Type Id...: ' + rType.ID + ' ----> Name : ' +
rType.Name);
}
}

// Write an Apex Program to display Account Records which are associated with
"Existing Customer RecordType".

// Write an Apex Program to display all contacts and Opportunities associated


with the Account 'Edge Communications'.

// Fetching Account Record ID....


Account acc = [select id from account where name =: 'Edge Communications' limit
1];

Id accId = acc.Id;
if(accID != null)
{
// Fetch contact records...
List<Contact> lstContacts = [select firstname, lastname, email, phone, fax from
contact where accountid =: accid];

if(!lstContacts.isEmpty())
{
for(Contact con : lstContacts)
{
system.debug('Contact First Name....: ' + con.firstname);
system.debug('Contact Last Name......: ' + con.lastname);
system.debug('Email ID ......: ' + con.email);
system.debug('Phone Number is.....: ' + con.phone);
system.debug('Fax Number is.....: ' + con.fax);
system.debug('----------------------------------');
}
}
// Fetch Opportunity records...
List<Opportunity> lstOpptys = [select name, stagename, closedate from
opportunity where accountid =: accId];
if(! lstOpptys.isEmpty())
{
for(Opportunity oppty : lstOpptys)
{
system.debug('Opportunity Name : ' + oppty.Name);
system.debug('Opportunity Stage Name ....: ' + oppty.StageName);
system.debug('Close Date is.....: ' + oppty.closedate);
system.debug('--------------------------------------');
}
}
}
// Write an Apex Program to fetch all Candidate details, who has applied for the
position "Java Developer".

// Write an Apex Program to fetch all activities(Task and Event) associated with
the account "Reliance Industries".

Order By Clause:

- This Clause is used to sort / arrange the resultset records either in Ascending /
Descending order, based on one or more columns.

Note:
Order By Clause is an optional statement in SOQL Query.

Syntax:
[ ORDER BY <Column Names> [ <Ascending / Descending> ] ]

Note:
Specifying the Sorting order (Asc / Desc) in Order by clause is optional.

If the user specify any order (Asc / Desc), then the records will be sorted
based on the specified order.
Else it will sort the records in Ascending order by default.

Ex:
Order by <Column Name> [<Asc / Desc>].

Order By Rating Desc.


Order by Name // Default order will be Ascending.
Order by Industry Asc.

// Write an Apex Program to display the Position records and arrange the records
based on Name column in Ascending Order.
List<Position__C> lstPos = [select position_id__C, name, location__C,
position_status__C, close_date__C, maximum_pay__c from position__C order by
name ];

if(! lstPos.isEmpty())
{
for(Position__C pos : lstPos)
{
system.debug('Position Name ....: ' + pos.Name);
system.debug('Position Id is....: ' + pos.id);
system.debug('Location is.....: ' + pos.location__C);
system.debug('Position Status is...: ' + pos.position_status__C);
system.debug('Close Date is.....: ' + pos.close_date__C);
system.debug('----------------------------------------');
}
}

// Write an Apex Program to display All Account records associated with Banking
industry and Whose Annual Revenue is not null and arrange the records in
Descending order based on Created date.

List<Account> lstAccounts = [select id, name, rating, industry, annualrevenue,


createddate from account where industry =: 'Banking' and annualrevenue != null
ORDER BY createddate DESC];

SYSTEM.debug('Collection Size is.....: ' + lstAccounts.size());

if(!lstAccounts.isEmpty())
{
for(Account acc : lstAccounts)
{
system.debug(acc.Name + ' -- ' + acc.Createddate + ' -- ' + acc.Rating + ' -- '+
acc.industry);
}
}

// write an apex program to display all the position records and the associated
candidate records(applied candidates) in descending order based on created
date.

without using SOQl inside for loop


map<id,position__c> mappos = new map<id,position__c>([select id from
position__c]);
list<candidate__c> lstcan =[select name,id__c, location__c, positionName__c,
createddate from candidate__c where positionname__c IN:mappos.keyset()
order by createddate desc];
for(position__c pos:mappos.values())
{
system.debug(pos);
for(candidate__c can:lstcan)
{
if(can.positionname__c == pos.id)
{
system.debug(can);
}
}
}
using SOQL inside for loop:
list<Position__c> lstpos = [select id from position__c];
system.debug(lstpos);
if(!lstpos.isempty())
{
for(position__c pos:lstpos)
{
system.debug(pos);
list<Candidate__c> lstcans = [select
name,Location__c,id__c,PositionName__c,createddate from Candidate__c where
PositionName__c =:pos.id order by createddate];
if(!lstcans.isempty())
{
for(Candidate__c can:lstcans)
{
system.debug(can);
}
}
else
{
system.debug('No candidates found');
}
}
}

ALL ROWS:

- ALL ROWS Clause is used to retrieve the records information, which are exist in
the object or removed from the object (i.e Display in Recycle Bin).

- By using ALL ROWS clause we can display deleted records also from recycle bin.

Note: ALL ROWS statement is an optional statement in SOQL Query.

Note: All Rows statement should be the last statement in SOQL Query.

Note: Each Salesforce Object contains a Hidden field called as "isDeleted", which
is a Boolean field. Which indicates whether the record is deleted from the object
or not.

- If the record is deleted from the object, then the record will hold the value for
this field as "TRUE". Else the record will hold the value for this field as "FALSE".
i.e isDeleted = TRUE --> Deleted Record.(Exist in Recycle Bin)
isDeleted = FALSE --> Record Not deleted(Exist in the Object)

// Write an Apex Program to display all position records (Both exist in the object
and deteted from the object.)

List<Position__C> lstPosition = [select name, position_id__C, location__C,


position_status__C from position__C ALL ROWS ];

system.debug('Position Records Count.....: ' + lstPosition.size());

if(! lstPosition.isEmpty())
{
for(Position__c pos : lstPosition)
{
system.debug(Pos.Name + ' -- '+ pos.position_id__C + ' -- '+ pos.Location__c);
}
}

// Write an Apex program to display deleted records from Position Object.

List<Position__C> lstPosition = [select name, position_id__C, location__C,


position_status__C from position__C where isDeleted =: true ALL ROWS];

system.debug('Deleted Position Records Count.....: ' + lstPosition.size());

if(! lstPosition.isEmpty())
{
for(Position__c pos : lstPosition)
{
system.debug(Pos.Name + ' -- '+ pos.position_id__C + ' -- '+ pos.Location__c);
}
}
Dynamic SOQL Queries:
- Dynamic SOQL Queries are used to prepare the SELECT statement at run time
based on the user input.

- We need to add the conditions to SOQL Query at run time and store the query in
a string variable.

Ex:
string soqlQuery = 'select id, firstname, lastname, email, phone, fax from
contact ';
.....
.....
Statements..
.....
soqlQuery += ' Where email=: <value>';

Once, SOQL Query has been prepared, then we need to execute the Query at Run
time by using "Database" class .

-Database class provides a "Query()" method to execute SOQL statements


dynamically at run time. And it produce the results in terms of a "List" collection.

List<SObjectType> lstContacts = Database.Query(<SOQL Query>);

Note: Always Database.Query() method will returns the resultset in terms of List
Collection.

// Write an Apex Program to display all candidate records associated with


"Hyderabad" location.

string candLocation = 'Hyderabad';

string candQuery = 'select id, name, location__C, contact_Number__c,


email_id__c from candidate__C where location__C =: candLocation';
List<Candidate__C> lstCands = Database.Query(candQuery);

if(!lstCands.isEmpty())
{
for(Candidate__C cnd : lstCands)
{
system.debug('Candidate Id is....: ' + cnd.id);
system.debug('Candidate Name is....: ' + cnd.name);
system.debug('Location is....: ' + cnd.location__C);
system.debug('Contact Number is....: '+ cnd.contact_Number__c);
system.debug('Email Id is.....: '+cnd.email_id__c);

system.debug('-------------------------------');
}
}

// Write an Apex program to display all contact records based on the user input.
Note: We need to check the input is in the form on Email or a string.

1. If it is in Email Format, then add condition based on Email field.


2. If it is a string, get records based on last name.

string userInput = '[email protected]';

string soqlQuery ='select id, firstname, lastname, email, fax, phone from contact
where ';

if(userInput != null && userInput != '')


{
if(Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}', userInput))
{
system.debug('User Input is a Email ID.');
soqlQuery +=' email =: userInput';
}
else
{
system.debug('User Input is a String.');
soqlQuery += ' lastname =: userInput';
}
}

List<Contact> lstContacts = Database.query(soqlquery);

if(!lstContacts.isempty())
{
for(Contact con : lstContacts)
{
system.debug('Contact Id is.....: '+ con.id);
system.debug('Contact First Name is....: '+ con.firstname);
system.debug('Contact Last Name.....: '+ con.lastname);
system.debug('Email Id is.....: ' + con.email);
system.debug('Phone Number is....: ' + con.phone);
system.debug('-------------------------------------');
}
}

LIKE Operator:

- LIKE operator is used to retrieve the similar kind of information from the
database object.

- It can applied on one or more columns in the table.

Note: LIKE operator should be used along with the WHERE clause always.

Syntax:
<Column Name> LIKE <Expression>
- While using the Like operator, we need to specify the expression, based on
which we need to search the information from table column.

Note: Expression can be perpared with the help of "Wild Card Characters".

SOQL supports the below wild card characters.


1. "%" --> Which refers to Zero or More characters.
2. "_" (Underscore) --> Which refers to one character.

Ex:
Where name LIKE 'Rame%';

// Write an Apex program to display all the position records which related to
"java" programing.

string progName ='Java%';

string soqlQuery = 'select position_id__c, name, location__c, position_status__c,


close_date__c from position__C where name like : progName';

List<Position__c> lstPos = Database.query(soqlquery);

system.debug('Collection Size is.....: '+lstPos.size());

if(!lstPos.isEmpty())
{
for(Position__C pos : lstPos)
{
system.debug('Position Id is.....'+pos.id);
system.debug('Position Name is....: ' + pos.name);
system.debug('Location......: '+pos.location__c);
system.debug('Position Status.....: '+ pos.position_status__c);
system.debug('Close Date is.....: '+ pos.close_date__C);
system.debug('-------------------------------------------');
}
}

// Write an Apex program to display all the contact records, whose names are
ends with the word "Kumar".

string nameEndsWith = '%kumar';

string soqlQuery ='select id, firstname, lastname, name, email, fax, phone from
contact where name like : nameEndsWith';

List<Contact> lstContacts = Database.query(soqlquery);

if(!lstContacts.isempty())
{
for(Contact con : lstContacts)
{
system.debug('Contact Id is.....: '+ con.id);
system.debug('Contact First Name is....: '+ con.firstname);
system.debug('Contact Last Name.....: '+ con.lastname);
system.debug('Email Id is.....: ' + con.email);
system.debug('Phone Number is....: ' + con.phone);
system.debug('-------------------------------------');
}
}

// Write an Apex program to Delete All the Accounts whose names arfe starts
with "Database".

string accountNameWith = 'Database%';

string selectQuery = 'select id from account where name like : accountNameWith';

List<Account> lstAccounts = Database.query(selectquery);


system.debug('Matching Records Count is.....: ' + lstAccounts.size());
if(! lstAccounts.isEmpty())
{
delete lstAccounts;
}

// Position and Candidates Sample Code


Map<Id, Position__C> mappos= new Map<ID, position__C>([select id,
position_id__C, name, location__C, position_status__C from position__C]);

List<Candidate__C> lstCands = [select id, name, email_id__c, contact_Number__c


from candidate__C where position__C IN : mappos.keyset()];

for(position__C pos : mappos.values())


{
system.debug('Position Record is...: ' + pos);
for(Candidate__C can : lstCands )
{
if(can.Position__C == pos.id)
{
system.debug(Can);
}
}

if(!lstPositions.isEmpty())
{
for(Position__C pos : lstPositions)
{
system.debug('Position Record.....: ' + pos);
List<Candidate__C> lstCan = [select id, name, email_id__c,
contact_Number__c from candidate__C where position__c =: pos.Id];

if(!lstCan.isEmpty())
{
for(candidate__C can : lstCan)
{
system.debug(can);
}
}
else
{
system.debug('No Candidates Found.');
}

}
}

Database Class Methods:

- Apex Programming provides a Readymade class called as "Database", which


provides a set of STATIC functions by which we can interact with the Database
objects and perform the manipulations on the records.

Note: Database class Provides the flexibility to Perform the Partial Processing.
i.e. We can continue with the other records, even though it encounter
some errors while execution.

By using Database class, we can able to TRACK the result of each operation.

It provides the following methods...

1. To Insert the records into the object...


Database.Insert(<ObjectName> / <ListObjectName>)
Database.Insert(<List_ObjectName>, boolean AllORNothing);

Note:
The Return Type of thise methods is "Database.SaveResult[]"

Ex:

Database.SaveResult[] result = Database.Insert(<List_ObjectName>,


boolean AllORNothing);

2. To Update the Existing Records values..


Database.Update(<ObjectName> / <ListObjectName>)
Database.Update(<List_ObjectName>, boolean AllORNothing);

Note:
The Return Type of thise methods is "Database.SaveResult[]"

Ex:

Database.SaveResult[] result = Database.Update(<List_ObjectName>,


boolean AllORNothing);

3. To Delete the Existing Records from the Object


Database.Delete(<ObjectName> / <ListObjectName>)
Database.Delete(<List_ObjectName>, boolean AllORNothing);

Note:
The Return Type of thise methods is "Database.DeleteResult[]"

Ex:

Database.DeleteResult[] result = Database.Delete(<List_ObjectName>,


boolean AllORNothing);
4. To Upsert the Records into the Object..
Database.Upsert(<ObjectName> / <ListObjectName>)
Database.Upsert(<List_ObjectName>, boolean AllORNothing);

Note:
The Return Type of thise methods is "Database.UpsertResult[]"

Ex:

Database.UpsertResult[] result = Database.Upsert(<List_ObjectName>,


boolean AllORNothing);

5. To Restore the records back the object from Recyclebin.


Database.UnDelete(<ObjectName> / <ListObjectName>)
Database.UnDelete(<List_ObjectName>, boolean AllORNothing);

Note:
The Return Type of this methods is "Database.UndeleteResult[]"

Ex:

Database.UndeleteResult[] result =
Database.UnDelete(<List_ObjectName>, boolean AllORNothing);

6. To execute the SOQL Query Dynamically at runtime...


List<ObjectName> Database.Query(string SOQLQuery)

7. To get the Resultset count value..


Integer recordsCount = Database.countQuery(<SOQL Query>);

8. Database.QueryLocator Database.getQueryLocator(string SOQL Query)

9. Database.QueryLocator

10. Database.EmptyRecycleBin(List<ID>)
Database.EmptyRecycleBinResult[] result = Database.EmptyRecycleBin(List<Id>);

This method is used to remove the specified records from the RecycleBin.

// Write an Apex Program to update the Ownership field value as "Private" for all
the account records
//starts with "Account Insert"

string accNamesStartsWith = 'Account Insert%';


string selectQuery = 'select id, name, rating, ownership from account where name
like : accNamesStartsWith';

List<Account> lstAccounts = Database.query(selectquery);


system.debug('Collection size is....: ' + lstAccounts.size());

if(! lstAccounts.isEmpty())
{
for(Account acc : lstAccounts)
{
acc.Ownership = 'Private';
}

update lstAccounts;
}

// write an Apex Program to update the Rating value as "Warm" and Industry as
"Finance" for the Account "Edge Communications".

string accName = 'Edge Communications';


string selectQuery = 'select id, name, rating, Industry, ownership from account
where name =: accName';

List<Account> lstAccounts = Database.query(selectquery);


system.debug('Collection size is....: ' + lstAccounts.size());
if(!lstAccounts.isEmpty())
{
for(Account acc : lstAccounts)
{
acc.Industry = 'Finance';
acc.Rating = 'Warm';
}

update lstAccounts;
}

// Write an Apex Program to update All Associated Contacts Phone number value
with the Account Record's Phone value, upon updating Account Records Phone
Number.

Account acc =[select id, name, rating, Industry,Phone, ownership from account
where name =: 'Edge Communications'];
system.debug('Account Record value is....: ' + acc);
acc.Phone = '1122334455';
Update acc;

if(acc.id != null)
{
Id accRecordId = acc.id;
List<Contact> lstContacts = [select id, firstname, lastname, phone from contact
where accountid =: accRecordId];
if(!lstContacts.isEmpty())
{
for(Contact con : lstcontacts)
{
con.Phone = acc.Phone;
}
Database.SaveResult[] results = Database.update(lstContacts);

for(Database.SaveResult res : results)


{
if(res.isSuccess())
{
system.debug('Record Updated Succesfully. Record Id is...: ' +
res.getID());
}
else
{
for(Database.Error err : res.getErrors())
{
system.debug('Error MEssage is....: ' + err.getMessage());
system.debug('Error Status Code is.....: ' + err.getStatusCode());
system.debug('Effected Fields are....: ' + err.getFields());
}
}
}

}
}

GROUP BY Clause:
================
- Group By clause is used to group the records information based on either one or
more columns.

- Group by clause can be implemented by using "Aggregate Functions".

Aggregate Functions:
--------------------
These functions will receive a collection of records as an input and generate only
one value as a Result.

Salesforce offers the below Aggregate Functions by default

1. SUM(<ColumnName>)
It will return the Sum of all the values exist in the specified column.

Ex:
Select Sum(AnnualRevenue) from account group by Rating.

2. AVG(<ColumnName>)
It returns Average of all the values exist in the specified column.

3. MIN(<ColumnName>)
It returns the smallest value exist in the specified column.

4. MAX(<ColumnName>)
It returns the Largest value exist in the specified column.

5. COUNT()
It counts the number of records exist in the object.

6. COUNT(<ColumnName>)
It returns the count of values exist in the specified column.

Note: It won't count the NULL values exist in the column

7. COUNT_DISTINCT(<ColumnName>)
It returns the count of values exist in the specified column.

Note:
It won't count the NULL Values and Duplicate Values exist in the
specified column.
Note:
Group By clause is an optional statement in SOQL Query.

Syntax:

[GROUP BY <ColumnName1, ColumnName2,....>]

// Apex Program to Display the Account Records by grouping based on Rating


field.

string selectQuery = 'select Rating, Count(id) RecordsCount from account Group


By Rating';

AggregateResult[] aggResults = Database.query(selectquery);

if(aggResults.size() > 0)
{
for(AggregateResult result : aggResults)
{
system.debug('Rating : ' + result.get('Rating') + ' -----> Record Count : ' +
result.get('RecordsCount'));
}
}

Note:
While retrieving the records by using Aggregate Functions in the Query,
then the ResultSet should be of type "AggregateResult[]" class.

We have to iterate the AggregateResult Collection and get the result of


each record by using the "GET" method.

// Write an Apex Program to display the number of records exist in the Account
object.
//Static SOQL Query..

integer recordsCount = [select count() from account];

system.debug('Account Records Count.....: ' + recordsCount);

// Dynamic SOQL Query...

string selectQuery = 'select count() from account';

integer accountRecordsCount = Database.countQuery(selectquery);

system.debug('Account Records Count....: ' + accountRecordsCount);

HAVING Clause:
==============
- Having clause is used to Add the Filters / Conditions along with the Group by
clause.

- Having Clause is completely dependant on "Group By" clause.

i.e Without Group By clause, we can't use Having clause.

- While grouping the records using "Group By clause", we can apply the conditions
with the help of "Having Clause".

Syntax:
[ Having <Conditions>]

// Apex Program to display the Account Records Count based on Rating, Whose
Record Count is more than 20 records.

string selectQuery = 'select Rating, Count(Id) RecordCount from Account group by


Rating Having Count(id) > 20';

AggregateResult[] aggResult = Database.query(selectquery);


system.debug(aggResult.size());

for(AggregateResult result : aggResult)


{
system.debug('Rating Value ....: ' + result.get('Rating') + ' -----> RecordCount :
'+ result.get('RecordCount'));
}

// Apex Program to display the Duplicate Records exist in the Account Object.

string selectQuery = 'select Name, Count(Id) RecordCount from Account group by


Name Having Count(id) > 1';

AggregateResult[] aggResult = Database.query(selectquery);

system.debug(aggResult.size());

for(AggregateResult result : aggResult)


{
system.debug('Account Name ....: ' + result.get('Name') + ' -----> RecordCount :
'+ result.get('RecordCount'));
}

Relationship Queries:
=====================
Relationship queries are used to retrieve the data from two or more salesforce
objects which are associated with each other.

- By using relationship queries, we can retrieve the data from both standard
objects and custom objects.

Note:
While using relationship queries, the target objects should be associated with
each other by using either Lookup or Master-Detail Relationship.
- We need to use a single SOQL Query to retrieve records from multiple objects.

- Relationship queries can be implemented by using "Inner Queries".

- We can fetch the record information from Parent to Child Record or from Child
Record to Parent Records.

Relationship Queries with Standard Objects:


-------------------------------------------
- While fetching the records from multiple objects, we can navigate the objects in
Bi-Directional way.
i.e. we can fetch the data from
1. Parent Record to Child records
2. Child Record to Parent Record

Parent To Child:
----------------
-This approach provides the ability to retrieve the Parent Record Details and along
with its associated child record details also.

- To implement this approach we have to use "Inner Queries".


Note:
1. While writing the inner query, it should be enclosed with a braces.
2. Inner query is used to retrieve the child records.
3. In Inner Query, child object name has be mentioned with "Plural Name"
of the object.
Ex: (select id, firstname, lastname from Contacts)
(select id, Name, Amount, Stagename from oppportunities)

// Apex Program to Display the Account Record, along with its associated Contact
records using relationship queries.

string accountName ='Aethna Home Products';


string selectQuery = 'select id, name, rating,industry, type, annualrevenue, (select
firstname, lastname, phone, email, fax from contacts) from account where name
=: accountname';

List<Account> lstAccounts = database.query(selectquery);

if(lstAccounts.size() > 0)
{
for(Account acc : lstAccounts)
{
system.debug('Account Id ....: ' + acc.id);
system.debug('Account Name ....: ' + acc.name);
system.debug('Account Rating ....: ' + acc.rating);
system.debug('Account Type ....: ' + acc.type);
system.debug('Account AnnualRevenue ....: ' + acc.AnnualRevenue);

system.debug('Contact Records....');
system.debug('Contacts Count.....: ' + acc.contacts.size());

for(Contact con : acc.contacts)


{
system.debug('Contact First Name ....: '+con.firstname);
system.debug('Contact Last Name ....: '+con.lastname);
system.debug('Contact Phone Number ....: ' + con.phone);
system.debug('Contact Email ID ....: '+con.Email);
system.debug('Contact Fax ....: '+con.fax);
}
}
}

// Apex Program to display Account Record and its associated Contact and
Opportunities also..
List<Account> lstAccount = [ select id, name, Rating, Active__c, annualrevenue,
industry,
(select id, firstname, lastname, email, phone, fax from
Contacts),
(select id, name, closedate, amount, stagename from
opportunities)
from account ];

system.debug('Account Records Count....: ' + lstAccount.size());

if(!lstAccount.isEmpty())
{
for(Account acc : lstAccount)
{
system.debug('Account Record is....: '+ acc);

// To Print Contact Records...


if(acc.Contacts.size() > 0)
{
system.debug('Contact Records are....: ' + acc.contacts.size());
for(Contact con : acc.Contacts)
{
system.debug(' ---> Contact Record is....: '+ con);
}
}

// To Print Opportunity Records...


if(acc.Opportunities.size() > 0)
{
system.debug('Opportunity Records are....: ' + acc.Opportunities.size());
for(Opportunity opp : acc.Opportunities)
{
system.debug(' &&&& Opportunity Record is....: '+ opp);
}
}

system.debug('--------------------------------------');
}

Child To Parent:
----------------
-This approach provides the ability to retrieve the Child Record Details and along
with its associated Parent record details also.

- We need to refer the Parent Object fields as below.


<ParentObjectName>.<FieldName>

Ex:
Account.Rating, Account.Type, Account.AnnualRevenue, etc.

// Apex Program to Fetch the Contact Record and along with it's Parent Account
Record Details also.

string selectQuery = 'select id, firstname, lastname, phone, email, fax,


Account.Name,Account.Rating,Account.Type, Account.AnnualRevenue from
contact';

List<Contact> lstcontacts = Database.query(selectquery);

if(lstContacts.size() > 0)
{
system.debug('Resultset Count....: ' + lstContacts.size());

for(Contact con : lstContacts)


{
system.debug('Contact FirstName....: '+ con.firstname);
system.debug('Contact Last Name .....: ' + con.lastname);
system.debug('Phone Number .....: ' + con.Phone);
system.debug('Email ID ......: ' + con.email);
system.debug('Fax Number .....: ' + con.fax);

// Print Account Record Details...


system.debug('Account Record Name .....: ' + con.Account.Name);
system.debug('Account Rating.....: ' + con.Account.Rating);
system.debug('Account Type .....: ' + con.Account.Type);
system.debug('Account Annual Revenue ....: ' + con.Account.Annualrevenue);
system.debug('------------------------------------');
}

/*
Write an Apex Program to display All Opportunity Records and along with all
associated Account Records,Whose Rating is "Warm" and AnnualRevenue is >
200000.
*/

Map<Id,Opportunity> mapOpptys = new Map<Id,Opportunity>([ select id, name,


Stagename,
closedate, amount,Account.Name, Account.Rating,
Account.AnnualRevenue from Opportunity
where Account.Rating =: 'Warm' and
Account.AnnualRevenue > 200000 ]);

system.debug('Collection size is....: ' + mapOpptys.size());

if(!mapOpptys.isEmpty())
{
for(Opportunity oppty : mapOpptys.values())
{
system.debug('Opportunity Name ....: ' + oppty.Name);
system.debug('Close Date is.....: ' + oppty.CloseDate);
system.debug('Amount is.....: ' + oppty.Amount);
system.debug('Opportunity Stage is....: ' + oppty.Stagename);
system.debug('Account Name is....: ' + oppty.Account.Name);
system.debug('Account Rating ....: ' + oppty.Account.Rating);
system.debug('Account Annual Revenue is....: ' +
oppty.Account.AnnualRevenue);
system.debug('--------------------------------------------------');
}
}

Note:
Always Inner queries will execute first. Based on the result returned by the
inner query, Outer query will get execute.

SOSL Statements:
================

- Salesforce provides a Search Language, in-order to search the information from


Salesforce Objects(i.e in both Standard and Custom Objects).

- By using this SOSL Statements, we can search for the information from 20
objects at a time by using a single query.

- SOSL statements can interact with either one or more objects at a time.

- SOSL Query will search the keyword in all the fields available in the object. Or
else we can specify the field names in which we want to search.

- SOSL Query can be prepared by using "FIND" keyword.

Governor Limits:
----------------
1. We can have max. of 20 SOSL Queries in a Single Transaction.
2. Each SOSL Query can returns max. of 2000 records.
3. One SOSL Query can search the keyword in 20 objects

Note:
SOSL Queries can't be supported in Triggers. i.e. we can implement the
SOSL queries only in Apex Classes.

-Salesforce provides 2 types of SOSL Queries


1. Static SOSL Queries
- These Queries has to be enclosed in "[ ]".
- We can't change the Search Keyword dynamically at run time.
i.e. query should be a static query.

Ex: [ < SOSL Query > ]

2. Dynamic SOSL Queries


- We can prepare the Search Query Dynamically at rum time by
adding the search keyword.

- We need to execute the Dynamic SOQL Query by using


"Search.Query()" method.

Ex:
Search.Query(<SOSL Query>);

Note:
SOSL Statements will return the results in the form of "List<List<SObject>> "

Ex:
Static SOSL Query:
-------------------
List<List<SObject>> lstObject = [ < SOSL Query>];

Dynamic SOSL Query:


-------------------

List<List<SObject>> lstObject = Search.Query(<SOSL Query>);

Static SOSL Query:


==================
Syntax:
[ FIND 'SearchKeyword%' IN ALLFIELDS RETURNING
<ObejctName1> (<FieldName1, FieldName2,...., FieldNameN>),
<ObejctName2> (<FieldName1, FieldName2,...., FieldNameN>)
<ObejctName3> (<FieldName1, FieldName2,...., FieldNameN>)
....
....
<ObejctName20> (<FieldName1, FieldName2,...., FieldNameN>)
];

- We can get the resultset which contains the records information from max of 20
objects.

- FIND keyword will search the required keyqord "SearchKeyword%" in all the
fields exist in the specified objects.
If any of the record in the objects found the search keyword, then it will return
the record will the specified fields information.

Ex:
[ FIND 'test*' IN ALLFIELDS RETURNING
Account(Name, Rating, Industry, Type, Site),
Contact(firstname, lastname, email, phone, fax),
Opportunity(name, amount, stagename, closedate),
Case(name, status, priority, description),
....
....
upto 20 objects.
]

//Static SOSL Example...

List<List<SObject>> lstObjects = [
FIND 'apex*' IN ALL FIELDS RETURNING
ACCOUNT(Name, Rating, Industry, AnnualRevenue, Active__c),
Contact(firstname, LastName, Email, Phone, fax),
Opportunity(Name, stagename, closedate, amount),
Position__C(name, position_status__C, location__c, close_date__c,
maximum_pay__C),
Candidate__C(Name, Email_id__c, contact_number__c)
];

List<Account> lstAccounts = (List<Account>) lstObjects.get(0);


List<Contact> lstContacts = (List<Contact>) lstObjects[1];
List<Opportunity> lstOppty = (List<Opportunity>) lstObjects[2];
List<Position__c> lstPos = (List<Position__c>) lstObjects[3];
List<Candidate__c> lstCand = (List<Candidate__C>) lstObjects[4];

if(!lstAccounts.isEmpty())
{
system.debug('Account Records Size....: ' + lstAccounts.size());

for(Account acc : lstAccounts)


{
system.debug('Account Record....: ' + acc);
}
}
if(!lstContacts.isEmpty())
{
system.debug('Contact Record Count....: ' + lstContacts.size());
for(Contact con : lstContacts)
{
system.debug('Contact Record....: ' + con);
}
}

if(!lstOppty.isEmpty())
{
system.debug('Opportunity Records size....: ' + lstOppty.size());
for(Opportunity oppty : lstOppty)
{
system.debug('Opportunity Record...: ' + oppty);
}
}

if(!lstPos.isEmpty())
{
system.debug('Position Records Count....: ' + lstPos.size());
for(Position__c pos : lstPos)
{
system.debug('Position Record....: ' + pos);
}
}

if(! lstCand.isEmpty())
{
system.debug('Candidate Records Count...: ' + lstCand.size());
for(Candidate__C c : lstCand)
{
system.debug('Candidate Record is....: ' + c);
}
}

Assignment:
===========
1. Create an Apex Class to Manage Account Records
1.1. We can able to search the Account with the Name / ID
1.2. CreateNewAccount() method.
This should receive the required parameters as an input, and insert
the record into the Account Object.
Note: It should not accept the Duplicate Records. (Can be identified by
using Account Name)
1.3. Update the Account Records with the New Values.
1.3.1. We can update either Single Record
1.3.2. We can update Group of Records.
1.4. SearchAccountRecords(FromDate, ToDate) Methods.
- This method has to display all the Account records which has been
created between the Two Specified dates.

1.5. Delete the Account Records from RecycleBin, which are older than 10
days.

Implementation:
===============
public class AccountsUtility
{
public boolean IsAccountExistByName( string accountName)
{
integer recordsCount = [select count() from account where name =:
accountName];
if(recordsCount > 0)
return true;
else
return false;
}

public boolean IsAccountExistByID( ID accountID)


{
integer recordsCount = [select count() from account where id =: accountId];
if(recordsCount > 0)
return true;
else
return false;
}

public Id CreateNewAccount(string accName, string accRating, string


accIndustry, string accType, string accSic, integer accRevenue, string accActive,
string accSSN, string accPassport, string accSite, string accFax )
{

boolean checkDuplicate = IsAccountExistByName(accName);

if(checkDuplicate) // Record Exist...


{
return null;
}
else // Record Not Exist...
{
Account acc= new Account();
acc.Name = accName;
acc.Rating = accRating;
acc.Industry = accIndustry;
acc.Site = accSite;
acc.AnnualRevenue = accRevenue;
acc.Type = accType;
acc.Sic = accSIC;
acc.Active__c = accActive;
acc.SSN_Number__c = accSSN;
acc.Passport_Number__c = accPassport;
acc.Fax = accFax;

insert acc;
return acc.id;
}

Testing the Code:


----------------
// Creating the Object of the Class..
AccountsUtility accUtil = new AccountsUtility();

ID recordID = accUtil.CreateNewAccount('Puli Movie','HOT','Foods and


Beverages', 'Prospect','34567',345000, 'Yes','3453453','34534534','IT
Department','45645645' );

if(recordId != null)
system.debug('Account Record Inserted Successfully. Record Id is...: ' +
recordId);
else
system.debug('Duplicate Account record.');

// Calling the Search Method...


boolean isExist = accUtil.IsAccountExistById('00128000003shez');

if(isexist)
system.debug('Account Record Exist.');
else
system.debug('Account Record Not Found.');
Triggers:

- These are the Custom Business Logic, Which execute based on DML Operations
- Trigger will perform the Asynchronous operations
- By using Trigger we can implement complex business logic
- We can implement complex validation Rules.

- Using Triggers, We can able to perform the DML manipulations


- Triggers will be fired based on the DML Events.

Workflow:

1. We can automate the actions using workflow. We can automate the actions as
below
1. Send Email Notification
2. Assign a New Task
3. Update the Field
4. Send an Outbound Message

2. Workflow will be executed based on the below evaluation criteria


1. Created
2. Created, every time it is edited
3. Created, any time it is edited and meeting subsequent criteria.

Can't Do with WorkFlows:

1. We can't insert a new record using workflow


2. We can't delete the record using workflow
3. We can update the field in the same object / in the master object which is in
master detailed relationship.
i.e We can't update the record from Parent to Child
4. We can't update the record, which requires to update more field values.(i.e.
We need to add more actions, which degrades the performance of the
application).
5. WorkFlows will be executed always after performing the operations. (Not
before the operation)
6. We can't perform DML operations using WorkFlows.

Trigger Events:

- Triggers will be fired, based on the following events..

1. Before Insert
2. Before Update
3. Before Delete
4. After Insert
5. After Update
6. After Delete
7. After UnDelete

- We can execute a separate business logic on each event of the trigger.


- To segregate the business logic to be fired based on event, Apex provides the
Trigger Context Variables.

Syntax:
Trigger <Trigger_Name> ON <Object_Name> ( <Trigger Events>)
{
// Business Logic..

Example:

Trigger SendEmailToLeads ON Lead ( before insert, after insert)


{
// Business Logic for Validation..

// Business Logic to take Backup of Lead Record..


// Business Logic to Send an Email..

Trigger Context Variables:


- This will indicate the current state of the Trigger, based on which it can perform
the operations.

1. Trigger.IsInsert:
- It returns TRUE, when the trigger has fired on Insert Operation. Else it
returns FALSE.

2. Trigger.IsUpdate:
It returns TRUE, when the trigger has fired on Update Operation. Else it
returns FALSE.

3. Trigger.IsDelete:
It returns TRUE, when the trigger has fired on Delete Operation. Else it
returns FALSE.

4. Trigger.IsUnDelete:
It returns TRUE, when the trigger has fired on UnDelete Operation. Else it
returns FALSE.

5. Trigger.IsBefore:
It returns TRUE, when the trigger has fired on Before performing the DML
Operation. Else it returns FALSE.

6. Trigger.ISAfter:
It returns TRUE, when the trigger has fired on After performing the DML
Operation. Else it returns FALSE.

Ex:

Trigger SendEmailToLeads ON Lead ( before insert, after insert)


{
if(Trigger.IsInsert && Trigger.IsBefore)
{
// Business Logic for Validation..
}

if(Trigger.IsInsert && Trigger.IsAfter)


{
// Business Logic to take Backup of Lead Record..

// Business Logic to Send an Email..

Trigger.New:
------------
- It Contains the Current Context Records, while performing the Insert & Update
Operations in the Object.

- It contains the records in List format.

Note: In Delete Operation, Trigger.New will not be available

Trigger.Old:
------------
- It Contains the Previous Context Records, while performing the Update, Delete
and UnDelete operations in the object.

- It contains the records in List format.

Note: In Insert Operation, Trigger.Old will not be available.

Trigger.NewMap:
---------------
It Contains the Current Context Records in the form of MAP collection.
Note:
It will be availabe in After Insert, Before Update and After Update Events.
(Not applicable for "Before Insert" event)

i.e MAP is a Key, Value pair collection.


KEY --> It contains the ID of the record
VALUE --> It contains the Whole Record

Trigger.OldMap:
---------------
It Contains the Previous Context Records in the form of MAP Collection.
i.e MAP is a Key, Value pair collection.

KEY --> It contains the ID of the record


VALUE --> It contains the Whole Record

Note: While writing the Trigger, it should handle operations on both Single record
as well as Bulk Records also.

- To handle the bulk records, we have to make the Trigger "Bulkify".

Bulkifying the Triggers:


- Tigger.New / Trigger.Old contains the records in List format.
- To bulkify the Trigger, We have to use the FOR Loop.

Ex:
Object Name: Account
Operation : Inserting the new records.
Event : Before

for(Account acc : Trigger.New)


{
// Perform the validation
}
// Insert the records as group...

Ex:
Object Name: Candidate__C
Operation : Deleting the records.
Event : Before / After

for(Candidate__C cnd : Trigger.Old)


{
// Perform the validation
}
// Delete the records using List...

Creating Triggers:
- We have the Following ways to create the Trigger.

1. Standard Navigation:
Goto Setup --> Got to Build --> Click on Develop --> Click on "Apex Triggers"
--> Write the Trigger Code --> Save.

2. Developer Console:
Goto Your Name --> Click on "Developer Console" --> Click on File Menu --
> Select the New Menu Item --> Click on Apex Trigger Menu Item --> Enter the
Trigger Name --> Select the Object Name from the Picklist --> click on OK.

3. Eclipse IDE.

// Create a Trigger to make Customer Record should be unique by using


CustomerName value.

Object Name : Customer__c


Event : Before Insert, Before Update

trigger PreventDuplicateCustomers on Customer__c (before insert, before


update)
{
for(Customer__c cust : Trigger.New)
{
system.debug('Customer Name ....: ' + cust.name);

integer customerCount = [select count() from customer__c where


name =: cust.name];

if(customerCount > 0 )
{
cust.Name.AddError('Customer Record is Already Exist. Please
select a New Name.');
}

}
}

// Create a Trigger to make Phone Number, Email Id and Fax Number on Contact
Record is Mandatory..

trigger ValidateFieldsOnContact on Contact (before insert)


{
if(Trigger.IsInsert && Trigger.IsBefore)
{
for(Contact con : Trigger.New)
{
if(con.email == null || con.phone == null || con.Fax == null)
{
con.AddError('Please enter the Mandatory Fileds upon Contact
Creation.');
}
}
}
}
// Trigger to Update the Location based on the Phone Number's STD Code.

trigger UpdateLocationBySTDCode on Contact (before insert, before update)


{
if((Trigger.IsInsert || Trigger.IsUpdate) && Trigger.isBefore )
{
for(Contact con : Trigger.New)
{
if(con.phone != null)
{
string stdCode = con.phone.substring(1,4);
system.debug('@@@@@@@ STD Code...: ' + stdCode);

if(stdcode == '040')
con.Location__c = 'Hyderabad';
else if(stdcode == '080')
con.Location__c = 'Bangalore';
else if(stdcode == '044')
con.Location__c = 'Chennai';
else if(stdcode == '020')
con.Location__c = 'Pune';
else if(stdcode == '022')
con.Location__c = 'Mumbai';
else if(stdcode == '012')
con.Location__c = 'Noida';
else if(stdcode == '048')
con.Location__c = 'Kochi';
}
}
}
}
/* Trigger To delete the associated Contact records upon deleting the Parent
Account Record. And Make the Associated opportunities as it is, upon deleting
the parent account.
*/

Trigger RemoveContactsForAccount on Account(Before Delete)


{
if(Trigger.isBefore && Trigger.isDelete)
{
/*
Set<ID> idsSet = new Set<ID>();
for(Account acc : Trigger.Old)
{
idsSet.Add(acc.id);
}
List<Contact> lstContacts = [select id, firstname, lastname from contact where
accountid IN : idsSet ];
*/

// Logic to Delete the associated coantacts..

List<Contact> lstContacts = [select id, firstname, lastname from contact where


accountid IN : Trigger.OldMap.KeySet()];

if(! lstContacts.isEmpty())
Delete lstContacts;

// Logic to make the Opportunities exist as it is..

List<Opportunity> lstOppty = [select id, name, accountid from opportunity


where accountid IN : Trigger.OldMap.KeySet()];

if(! lstOppty.isEmpty())
{
for(Opportunity opp : lstOppty)
{
opp.accountid = null;
}

update lstOppty;
}
}
}

Custom Settings:
- Custom Settings are also like as Custom Objects, Where we can store the
information by creating the fields.
1. Salesforce.com introduced Custom Setting, which allows you to store custom
data sets and associate them on an org-wide, profile or user basis.

2. Custom Settings are essentially custom objects that are exposed in the
applications cache and are accessible via their own API.

3. You can certainly build your own custom objects to store settings but using
custom settings is much quicker (again they are stored in the application cache)
and do not count against SOQL limits when fetched.

4. You can also use custom settings in formula fields, validation rules, Apex code
and the Web Services API.

Custom settings come in two flavors:


1. List Custom Settings.
1.1.List custom settings allow you to store org-wide static data that is
frequently used
1.2. List Custom Settings can't be accessible in Formula Fields.
2. Hierarchy Custom Settings:
2.1. Hierarchy Custom Settings allows you to store Profile / User
Specific data.
2.2. These can be accesible from Formula Fields using
"$Setup.<CustomSettingName>.<FieldName>"

Note: When you create a new custom settings the platform creates a custom
object in the background for you (notice the API Name field). You then add
additional fields to the custom setting in the same manner that you do for custom
objects

- Always it is recommended to use the Custom Settings while storing the Static
information. Instead of wasting one Custom Object.
- In Custom object, we have to retrieve the data by writing the SOQL Queries.

Note:
1. Whereas in Custom Settings, We can retrieve the Data without writing
any SOQL queries.

2. Custom Settings Data will be storing into the Application Cache. So that
we can efficiently use the records.

3. We can store max of 2 MB of data in Custom Settings.


4. We can access the Custom Settings data in Formula Fields, Apex Code
and Visual Force pages.

Creating Custom Settings:

Goto Setup --> Goto Develop --> Click on Custom Settings --> Click on "New"
Button
- Enter the Custom Setting Label and Unique Name
- Select the Type as "List"
- Select the Accessibility as "Public"
- Click on "Save"

Create the Fields in the Custom Settings:


- We can able to create the new fields in the custom setting in-order to store the
data.
Note: We can create up to 300 fields in Custom Settings

Creating Field 1:
- Goto the Custom Field Section
- Click on New, Select the Field Type as "Text" Enter the Name : "Region
Name"
- Click on Save

Creating Field 2:
- Goto the Custom Field Section
- Click on New, Select the Field Type as "Text" Enter the Name : "Region
Manager Name"
- Click on Save

Storing the Data in Custom Settings:

- Goto the Custom Setting Page --> Click on "Manage"


- Click on "New" to create a new record
- Enter the Details for the Region Name and Region Manager Name fields.
Ex: Asia --> Yashwanth Kumar
Americas --> David Dodson
Europe --> Rajesh Kumar.
....
....

Accessing the Custom Setting Data:


Methods in Custom Settings:
1. GetAll()
2. GetInstance(CustomSettingRecordName)
3. GetValue(CustomSettingKeyName)

- To Access the Custom Setting Data, we have to use "getAll()" function.


- The Return type of the custom setting is MAP.
Key: Region Name is the Key
Value : The Whole Record of that Region

Syntax:
Map<string,Custom_Setting_Name> <objName> =
<Custom_Setting_Name>.getAll();

Ex:
Map<string, QEdgeRegionalInformation__c> =
QEdgeRegionalInformation__c.getAll();

QEdgeRegionalInformation__c reg =
QEdgeRegionalInformation__c.getInstance(‘Americas’);

QEdgeRegionalInformation__c reg =
QEdgeRegionalInformation__c.getValues(‘Americas’);

// Create a Trigger on Customer object to Auto Populate the Region Manager


Name based on Region name value(using Custom Settings).

trigger PopulateRegionDetails on Customer__c (before insert, before update)


{
if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isBefore)
{
for(Customer__c cust : Trigger.New)
{
Map<string,RegionDetails__c> mapRegions =
RegionDetails__c.getAll();

cust.Region_Manager_Name__c =
mapRegions.get(cust.Region_Name__c).Manager_Name__c;

}
}
}

// Apex Trigger to Prevent the Deletion of Active Contacts.

Trigger PreventActiveAccountDeletion on Account(Before Delete)


{
if(Trigger.isBefore && Trigger.isDelete)
{
for(Account acc : Trigger.old)
{
if(acc.Active__c == 'Yes')
acc.AddError('You are not Authorised to Delete an Active Account.');
}
}
}
---------------------------

/**
@Author: Feroz Beg
@name: StaffMethods
@CreateDate:
@Description: This class provides the ability to get All Active users.
@Version: 1.0
@reference:
*/

Public class StaffMethods


{
/**
* This Method will return All the Active User Records in Map Collection.
* @name: GetActiveStaffUsers
* @param:
* @return: Map<Id,User>
* @throws:
*/
Public static Map<Id,User> GetActiveStaffUsers()
{
Map<Id,User> mapActiveUsers = new Map<Id,User>([select id,
username, isActive from User where isActive = true]);

return mapActiveUsers;
}
}

----------------------------
/**
@Author: Feroz Beg
@name: LeadHandler
@CreateDate:
@Description: This class provides the ability to Handle the Lead to Prospect
Synchronization.
@Version: 1.0
@reference:
*/

public class LeadHandler


{
// This Method is used to Convert the Lead Automatically, upon updating Lead
Status as "Closed - Converted"
Public static Void AutoLeadConversion(Map<Id,Lead> mapLeads)
{
LeadStatus status = [select id, masterlabel from leadstatus where isconverted
= true limit 1 ];
List<Database.LeadConvert> lstConverts = new
List<Database.LeadConvert>();
if(!mapLeads.isEmpty())
{
for(Lead l : mapLeads.values())
{
if(l.Status == 'Closed - Converted')
{
Database.LeadConvert lc = new Database.LeadConvert();
lc.SetLeadId(l.Id);
lc.SetConvertedStatus(Status.MasterLabel);
lc.setSendNotificationEmail(false);

if(l.Do_Not_Create_Opportunity__c == true)
{
lc.SetDoNotCreateOpportunity(true);
}

lstConverts.add(lc);
}
}

List<Database.LeadConvertResult> lcResults= new


List<Database.LeadConvertResult>();

if(!lstConverts.isEmpty())
{
try
{
lcResults = Database.convertLead(lstConverts);
}
Catch(DMLException d)
{
system.debug('DML Exception Occured during Lead Conversion.' +
d.getMessage() + '-- StackTrace string :'+ d.getStackTraceString());
}
Catch(Exception e)
{
system.debug('Exception Occured during Lead Conversion.' +
e.getMessage() + '-- StackTrace string :'+ e.getStackTraceString());
}

}
}

// This method will create an associated Prospect Record, upon creating a


new Lead.
Public static void AfterInsert(List<Lead> lstLeads)
{
List<Prospect__c> lstProspects = new List<Prospect__c>();

for(Lead ld : lstLeads)
{
Prospect__c p = new Prospect__c();

p.FirstName__c = ld.FirstName;
p.Name = ld.LastName;
p.Phone__C = ld.Phone;
p.Email__c = ld.Email;
p.Fax__c = ld.Fax;
p.Rating__c = ld.rating;
p.Industry__C = ld.Industry;
p.Lead_Source__C = ld.LeadSource;
p.Passport_Number__c = ld.Passport_Number__c;
p.ssn_Number__c = ld.ssn_Number__c;
p.Product_interest__c = ld.ProductInterest__c;
p.Primary__c = ld.Primary__c;
p.Company__c = ld.Company;
p.Website__C = ld.Website;
p.Annual_Revenue__c = ld.annualrevenue;
p.Lead__C = ld.id;

lstProspects.Add(p);
}

try
{
if(!lstProspects.isEmpty())
insert lstProspects;
}
catch(DMLException dex)
{
system.debug('DML Exception Occured during Prospect Creation.' +
dex.getMessage() + '-- StackTrace string :'+ dex.getStackTraceString());
}

// This method will update the associated Prospect Record, upon updating
the Lead record.
Public static void AfterUpdate(Map<Id,Lead> mapLeads, Map<Id,Lead>
oldLeads)
{
List<Prospect__c> prospectsToUpdate =new List<Prospect__C>();

Map<Id,User> mapActiveStaff = StaffMethods.GetActiveStaffUsers();

List<Prospect__c> lstProspects = [select id,FirstName__c


,Name ,Email__c,Fax__c,Rating__c,
Industry__C,Passport_Number__c
,ssn_Number__c,Product_interest__c,Primary__c
,Company__c ,Website__C, ownerid
,Annual_Revenue__c, lead__C from Prospect__C where
lead__c IN : mapLeads.keySet()];

if(!lstProspects.isEmpty())
{
for(Prospect__C p : lstProspects)
{
for(Lead l : mapLeads.values())
{
if(p.Lead__c == l.id)
{
p.FirstName__c = l.FirstName;
p.Name = l.LastName;
p.Phone__C = l.Phone;
p.Email__c = l.Email;
p.Fax__c = l.Fax;
p.Rating__c = l.rating;
p.Industry__C = l.Industry;
p.Lead_Source__C = l.LeadSource;
p.Passport_Number__c = l.Passport_Number__c;
p.ssn_Number__c = l.ssn_Number__c;
p.Product_interest__c = l.ProductInterest__c;
p.Primary__c = l.Primary__c;
p.Company__c = l.Company;
p.Website__C = l.Website;
p.Annual_Revenue__c = l.annualrevenue;

// Trasfering Prospect to another user...


if((oldLeads.get(l.Id).Prospect_owner__C !=
mapLeads.get(l.Id).Prospect_owner__c) &&
mapActiveStaff.containsKey(l.Prospect_owner__C))
{
p.OwnerId = mapLeads.get(l.Id).Prospect_owner__c;
}

prospectsToUpdate.Add(p);
}
}
}

try
{
if(!prospectsToUpdate.isEmpty())
update prospectsToUpdate;
}
catch(DMLException e)
{
system.debug('DML Exception Occured during Prospect Creation.' +
e.getMessage() + '-- StackTrace string :'+ e.getStackTraceString());
}
}
}
}

// Apex Trigger to Create / Update Prospect record based on Lead Record.

Trigger LeadTrigger On Lead(After Insert, After Update)


{
if(Trigger.isInsert && Trigger.isAfter)
{
LeadHandler.AfterInsert(Trigger.New);
}

if(Trigger.isAfter && Trigger.isUpdate)


{
LeadHandler.AfterUpdate(Trigger.NewMap, Trigger.oldMap);
//LeadHandler.AutoLeadConversion(Trigger.NewMap);
}
}

Email Programming:
==================
-There may be situations in which you would not want a workflow email alert,
because either your criteria to send an email may be too complex or the person
whom you want to send an email has to be determined dynamically.

-In such situations you can choose to send an email from a Apex Class.

- Salesforce allows us to send the email notifications to the users or external


systems / to receive the emails from the users.

- While sending/ Receiving the emails, we can add the Attachments also.

- We have 2 Types of Email Services in Salesforce


1. Inbound Email Messaging
2. Outbound Email Messaging

Note: All Email Classes are available in the "Messaging" name space.

Governor Limits:
In s single transaction, we can have 10 email invocations.
i.e Maximum of 10 Messaging.SendEmail() methods per Transaction.

Inbound Email:
--------------
- This service is used to receive the Emails from the users or external systems.
i.e Email is coming into our Salesforce instance.

- It provides a class called as "Messaging.InboundEmailHandler" in-order to


receive the email from the user and store the email content in the associated
object along with the attachment.
Outbound Emails:
----------------
- Used to send the Emails to the users based on the ToAddress and with the
required Subject and the Content

- We can able to send the Email Content in PlainText or HTML format

- We have 2 ways to send the Outbound Emails.

1. Messaging.SingleEmailMessage Class
2. Messaging.MassEmailMessage Class

Messaging.SingleEmailMessage:
----------------------------
- This class is used the send the Email to the specified user with the user defined
content and Subject.

Methods:

1. SetToAddresses(<Collection>)
To specify the To Address in terms of String Array or List collection.
Note: The maximum allowed ToAddresses is 100.
2. SetCCAddresses(<Collection>)
To specify the one or more CC Email Addresses.
Note: The maximum allowed is 25
3. SetBccAddresses(<Collection>)
To specify one or more BCC Email Addresses
Note: The maximum allowed is 25
4. SetReplyTo(string)
To specify the Reply-To Email Address
5. setSenderDisplayName(string)
To specify the Sender Display Name "Ex: Salesforce Support"
6. SetSubject(string EmailSubject)
To specify the Email Subject
7. SetPlainTextBody(string emailContent)
To specify the Email Content in plain text format.
8. SetHTMLBody(string emailHTMLContent)
To specify the email Content in HTML format

Messaging.SendEmail(SingleEmailMessageObject): To send the Email to the


specified user along with the content.

Messaging.MassEmailMessage:
---------------------------
- This class is used to send the Bulk Email to the Salesforce users(Contacts/
Accounts / Leads).

- We can send email upto 250 users in a single instance


- We have to add all the users ID's in the list in-order to send the Email
Notification.

Note: While sending the Email, We can use EmailTemplates also.

Methods:
--------
1. SetTargetObjectIDs(List<ID>): We have to pass the list of users/Contacts
id's to send the mass emails

2. SetEamilTemplateID(EmailTemplate ID): We have to pass the Email


Template ID, in-order to send the Email.

Getting Email Template ID's:


SOQL Query: select id, name from EmailTemplate

======================================================
Email Class:
============
// Apex Class to send the mail to the specified recipients..

public class EmailOnCandidateStatusChange


{
public void SendEmailToCandidate(string candidateName, string
toAddress,string fromAddress,string status, string subject)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();

string emailSubject = subject;


string emailContent = 'Dear <b>'+ candidateName +'</b>, <br><br>Thanks
for your interest in our organization.<br><br>Your Interview Status is : <b>'+
status+ '</b><br> <p>As per our subsequent discussions, we are decided to
move forward with your candidature.<p><b>Thanks,</b><br>ABC Technologies.';
string[] toAddresses=new string[2];
toAddresses[0] = toAddress;
toAddresses[1] = fromAddress;

email.setSubject( emailSubject );
email.setToAddresses( toAddresses );
email.setHtmlBody(emailContent );
Messaging.SendEmailResult [] result =
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
System.debug('*****' + emailContent);
System.debug('****** Email Has been sent successfully to the candidate.');
}
}

------------------------------------
email.setHtmlBody('Your Account has been Created. Account Id is..: <b>' + accId
+ '</b>.<p> To View Your Account Click on the below link. <a
href=https://ap2.salesforce.com/'+accId+'> Click Here </a>');

--------------------

Public class EmailMessagingClass


{
public static void SendEmail(List<string> toAddress,
string emailSubject,
string emailContent,
string accountID)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();

string[] ccAddress = new string[]


{'[email protected]','[email protected]'};

List<string> bccAddress = new List<string>();


bccAddress.Add('[email protected]');
bccAddress.Add('[email protected]');

email.setToAddresses(toAddress);

email.setCCAddresses(ccAddress);

email.setBccAddresses(bccAddress);

email.setReplyTo('[email protected]');

email.setSenderDisplayName('QEdge Technologies Support');

email.setSubject(emailSubject);
email.setPlainTextBody(emailContent);

email.setHtmlBody('Your Account has been Created. Account Id is..:


<b>' + accountID + '</b>.<p> To View Your Account Click on the below link. <a
href=https://ap2.salesforce.com/'+accountID+'> Click Here </a>');

Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});


}

public static void SendMassEmail()


{
List<contact> lstContacts = [select id, lastname from contact where accountid
= null];
List<ID> lstId ;

if(lstcontacts.size() > 0)
{
lstId = new List<Id>();

for(contact con : lstContacts)


{
lstId.add(con.id);
}

Messaging.reserveMassEmailCapacity(4);
Messaging.MassEmailMessage email = new
Messaging.MassEmailMessage();
email.SetTargetObjectIds(lstId);
email.SetTemplateId('00X28000000MAJTEA4');
Messaging.sendEmail(new Messaging.MassEmailMessage[] {email});
}
}
}
// Sending Attachments...

public class EmailClass


{
public void SendEmail()
{
Candidate__c cnd = [select id, name, candidate_id__c, location__C,
interviewstatus__c, contact_no__C, email_id__c from Candidate__c where name
= 'Naveen Tripathi' limit 1];
ID candID;
candID = cnd.id;

Messaging.SingleEmailMessage email = new


Messaging.SingleEmailMessage();

string[] toAddress = new string[1];


toAddress[0] = cnd.email_id__c;
email.SetToAddresses(toAddress);

email.SetSubject('Your Candidature has been applied.');

email.SetPlainTextBody('Dear Candidate, Your Candidature has been applied


for the position.');

string htmlBody = 'Your Candidature is...: <a


href=https://ap2.salesforce.com/'+ cnd.candidate_id__c+'> Click Here </a>';

email.setHtmlbody(htmlBody);

List<Attachment> att = [select id, name, body, contenttype from attachment


where parentid =: candID];
system.debug(att.size());
List<Messaging.EmailFileAttachment> fileatt = new
List<Messaging.EmailFileAttachment>();

if(att.size() > 0)
{
for(Attachment at : att)
{
Messaging.EmailFileAttachment file = new
Messaging.EmailFileAttachment();
file.setFileName(at.name);
file.setBody(at.Body);
file.setContentType(at.contenttype);
fileatt.add(file);
}
}

email.setFileAttachments(fileatt);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

}
}

// Apex Class to send Email Notifications..

Public class SendEmailToHiringManager


{
public static void SendEmail(Position__c posRecord, string emailSubject)
{
string[] toAddresses;
if(posRecord != null)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();
if(posRecord.HiringManagerName__c != null)
{
HiringManager__C hManager= [select id, name,
email_id__c from HiringManager__C where id=:
posRecord.HiringManagerName__c limit 1];

if(hManager != null)
{
toAddresses = new string[2];
toAddresses[0] = hManager.Email_ID__c;
toAddresses[1] = '[email protected]';
}

email.SetToAddresses(toAddresses);
//email.SetFromAddres('[email protected]');
email.Subject = emailSubject;

string emailContent = 'Dear <b>'+ hManager.Name +'</b>, <br><br>We


got a New Open Position in our Organization.<br><br> Please recruite the
candidates for this position : <b>'+ posRecord.Name +
'</b><br> <p>Please close the position as per the close
date.<p><b>Thanks,</b><br>ABC Technologies.';

email.SetHTMLBody(emailContent);
}

Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
}
}
}

// Trigger to Send Email Notification to Hiring Manager, upon Creating a New


Position / Updating the Position Status Value.
trigger SendEmailTriger on Position__c (after insert, after update)
{
if(Trigger.isInsert && Trigger.isAfter)
{
for(Position__c pos : Trigger.New)
{
if(pos.HiringManagerName__c != null && pos.Position_Status__c == 'New
Position')
{
string eSubject = 'New Open Positions in our Organization';
SendEmailToHiringManager.SendEmail(pos, eSubject);
}

}
}

if(Trigger.isAfter && Trigger.isUpdate)


{
for(Position__c pos : Trigger.New )
{
if(pos.HiringManagerName__c != null &&
(Trigger.OldMap.get(pos.id).Position_status__c !=
Trigger.NewMap.get(pos.id).position_status__c ))
{
string eSubject = 'Position Details has been updated - Status
Changed';
SendEmailToHiringManager.SendEmail(pos, eSubject);
}

}
}
}
// Apex Class to send Email Notifications...

Public Class MessagingUtility


{
Public static void SendEmailTocandidate(Candidate__C cndRec, string
emailSubject)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();

if(cndRec != null)
{
Candidate__C cnd = [select id, name, email_id__C, Location__c,
PositionName__c from Candidate__C where id =: cndRec.id limit 1];

Position__c pos= [select id, name from position__c where id =:


cnd.PositionName__c];

string[] toAddress = new string[]{cnd.email_id__C, '[email protected]'};

email.SetToaddresses(toAddress);

email.SetSubject(emailSubject);
email.SetReplyTo(cnd.email_id__C);
email.SetSenderDisplayName('QEdge Support Center');

/*
// To Send the Plain Text Information..

string emailContent = 'Hi '+ cnd.Name + 'Thanks for apllying for the position
' + pos.Name + '. We will have a look into your profile and out HR Team will get
back to you shortly. Thanks & Regards, ABC Technologies ';
email.SetPlainTextBody(emailContent);

// This is having Hard Coded value for BaseURL..


string emailHTMLContent = 'Dear ' + cnd.Name + '<br><br>' + 'Thanks for
Appying the Position for <b>' + pos.Name + '</b>. <br> <br>' + 'We will review
your profile and come back to you if any suitable matching requirement. <b> Here
is your Candidature Record. <a href=https://ap2.salesforce.com/'+ cnd.Id +'> Click
Here </a> . <br> Thanks and Regards,<br> <b> ABC Technologies</b>';
*/

string emailHTMLContent = 'Dear ' + cnd.Name + '<br><br>' + 'Thanks for


Appying the Position for <b>' + pos.Name + '</b>. <br> <br>' + 'We will review
your profile and come back to you if any suitable matching requirement. <b> Here
is your Candidature Record. <a href='+
System.Url.getSalesforceBaseUrl().ToExternalForm() + '/'+ cnd.Id +'> Click Here
</a> . <br> Thanks and Regards,<br> <b> ABC Technologies</b>';
email.SetHTMLBody(emailHTMLContent);

Messaging.SendEmail(new Messaging.SingleEmailMessage[]{email});

}
}
}

Best Practices of Trigger:


====================

1. Trigger should support bulk records as well - Always use "For Loop" to process
records inside the trigger

2. Always check for null pointer exceptions

3. Always try to use try and catch block in the trigger


4. Differentiate events with separate blocks to avoid usage of trigger.new and
trigger.old

5. Do not use DML operations inside the for loop. Add them to the list and
update/insert/delete the list out side the for loop.

6. Do not use SOQL and SOSL statements inside for loop.

7. Write the Proper Test Classes for the Trigger. And maintain minimum 1% of
code coverage for each trigger. And Overall organization wide, we have to
maintain 75% of code coverage while moving the code from sandbox to
production environment.

8.Avoid recursiveness in triggers by putting the proper conditions.

Note:
Recursive Triggers can be avoided by using the "Static Boolean" variables.

Do not execute the trigger on all the update. Only execute the trigger on
specific update.
Here the trigger will get executed on update of stagename field only and
will not trigger on other field's update

To avoid recursive use the below code:

if(Trigger.isUpdate && opp.stagename == 'Qualification' &&


opp.stagename != Trigger.oldMap.get(opp.id).stagename)
opptyIds.add(opp.Id);

Error Code:
if(Trigger.isUpdate && opp.stagename == 'Qualification')
opptyIds.add(opp.Id);
9. As a Best Practice, it is Recommended to maintain only One Trigger per an
Object. Because, We dont have the option in salesforce to control the execution
order of triggers.

10. It is recommended to maintain Trigger Handler Factory.(i.e instead of writing


the Trigger code inside the Trigger, we can write the code in a Class and call the
class from the trigger.)

Order of Execution in Triggers in Salesforce:


====================================
1. The original record is loaded from the database (or initialized for an insert
statement)
2. The new record field values are loaded from the request and overwrite
the old values
3. All before triggers execute (TRIGGERS)
4. System validation occurs, such as verifying that all required fields have a non-
null value, and running any user-defined validation rules (VALIDATIONS)
5. The record is saved to the database, but not yet committed
6. All after triggers execute
7. Assignment rules execute
8. Auto-response rules execute
9. Workflow rules executed (WORKFLOW)
10. If there are workflow field updates, the record is updated again.
11. If the record was updated with workflow field updates, before and after
triggers fire one more time (and only one more time) along with Standard
Validation Rules. (Note: In this case, Custom validation rules will not fire.)
12. Escalation rules execute.
13. All DML operations are committed to the database
14. Post-commit logic executes, such as sending email

========== Object Oriented Programming Samples ==============

// Apex Class to demonstrate the Procedures...


Public class SampleClass
{
Public void ShowMessage()
{
System.debug('This is ShowMessage Procedure.');
}

Public void Display()


{
system.debug('Welcome to Apex Programming.');
}

Public void Addition(integer x, integer y)


{
system.debug('Addition Result is....: ' + (x+y));
}

Public void Division(integer x, integer y)


{
if(y>0)
{
system.debug('Division Result is....: '+ (x/y));
}
else
system.debug('Division Operation cannot be performed.');
}

Public void CheckEqual(string s1, string s2)


{
if(s1 == s2)
system.debug('strings are Equals.');
else
system.debug('strings are not equals.');
if(s1.equals(s2))
{
system.debug('Both strings are Equal.');
}
else
{
system.debug('Not Equal.');
}
}
}

// Calling the methods by creating object..


SampleClass sample = new SampleClass();

sample.ShowMessage();
sample.Display();

Sample.Addition(400,2300);
sample.Division(500,40);
sample.CheckEqual('Hyderabad','hyderabad');
--------------------------------
// Sample Static Method...
Public class StaticDemoClass
{
Public string customerName;

public static string country;

Public static void GetLength(string s)


{
system.debug('String Length is....: ' + s.length());
}
}
---------
// Testing the class (Execute Anonymouw window...)

StaticDemoClass s = new StaticDemoClass();

/*
StaticDemoClass s;
s = new StaticDemoClass();

*/

s.customerName = 'Ramesh Kumar';


system.debug('Customer Name is....: ' + s.customername);

// Static Member...
StaticDemoClass.country = 'India';
system.debug('Country Name is.....: ' + StaticDemoClass.country);

// creating another object...


StaticDemoClass s1 = new StaticDemoClass();
system.debug('Customer Name is....: ' + s1.customername);

// Static Member...
system.debug('Country Name is.....: ' + StaticDemoClass.country);

//Calling Static methods...


StaticDemoClass.GetLength('Welcome to Apex Programming.');

Functions:
==========
// Apex class to demonstrate the Functions...

Public class MathsClass


{
Public integer Addition(integer x, integer y)
{
return (x+y);
}

Public integer Multiplication(integer x, integer y, integer z)


{
return (x * y * z);
}

Public integer GetLength(string str)


{
return str.Length();
}
}
------------
// Calling Functions (From Execute Anonymous Window..)
// Create object of class...

MathsClass m = new MathsClass();

integer result = m.Addition(200,560);


system.debug('Addition Result is....: ' + result);

Integer mulResult;
mulResult = m.Multiplication(200,34,45);
system.debug('Multiplication Result is....: '+ mulResult);

system.debug('Characters Count is.....: ' + m.GetLength('Welcome to


Hyderabad.'));

=========================================
// Apex class to perform string operations...

Public class StringOperationsClass


{
Public string Concatenate(string s1, string s2)
{
return (s1 + s2);
}

Public static Boolean CheckEqualsIgnoreCase(string s1, string s2)


{
if(s1 == s2)
return true;
else
return false;

// return ( s1 == s2) ? true : false;

Public static Boolean CheckEquals(string s1, string s2)


{
if(s1.equals(s2))
return true;
else
return false;
}
}

--------------- Execution....

// Creating object of the class...

StringOperationsClass st = new Stringoperationsclass();

string result = st.Concatenate('Welcome','Hyderabad');


system.debug('Concatenation result is.....: ' + result);

// Accessing Static methods...


Boolean isEquals =
StringOperationsClass.CheckEqualsIgnoreCase('Welcome','welcome');
if(isEquals)
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals.');

// Accessing Static methods...


Boolean isSame = StringOperationsClass.CheckEquals('Welcome', 'welcome');
if(issame)
system.debug('Strings are Equals');
else
system.debug('Strings are Not Equals.');

================================
// Apex class to manage the Account Details...

Public class AccountsHelper


{
Public static Account GetAccountById(Id recordId)
{
Account acc;

if(recordId != null)
{
acc= [select id, name, rating, industry, type, annualrevenue, active__c from
account where id =: recordId limit 1];
}

return acc;

Public static List<Contact> GetContacts(Id accID)


{
List<Contact> lstContacts;

if(accId != null)
{
lstContacts = [select id, firstname, lastname, email,
phone, fax from contact where accountid =: accId];
}

return lstContacts;
}

Public static List<Opportunity> GetOpportunities(Id accId)


{
List<Opportunity> lstOppty;
if(accId != null)
{
lstOppty = [select id, name, stagename,
amount, closedate from opportunity
where accountid =: accId];

}
return lstOppty;
}
}

// Execution:
============
// Calling the class method...
Account acc = AccountsHelper.GetAccountById('0012800000EWQ2r');
if(acc != null)
{
system.debug('Account Id is....: ' + acc.id);
system.debug('Account Name is....: ' + acc.name);
system.debug('Account Rating is....: ' + acc.Rating);
system.debug('Industry is....: ' + acc.industry);
system.debug('Type is....: ' + acc.type);
system.debug('Annual Revenue is.....: ' + acc.annualrevenue);
}

// Getting Contacts...
List<Contact> lstCon = AccountsHelper.GetContacts('001280000076fw2');
if(!lstCon.isEmpty())
{
for(Contact con : lstCon)
{
system.debug('Contact Record is....: ' + con);
}
}

// Getting Opportunity records...


List<Opportunity> lstOppty =
AccountsHelper.GetOpportunities('001280000076fw2');
if(!lstOppty.isEmpty())
{
for(Opportunity opp: lstOppty)
{
system.debug('Opportunity is....: '+ opp);
}
}

Batch Apex Programming:


- Batch Apex is used to perform the operation on the bulk records.
- We can perform all the DML operations on the records using Batch Apex.
- In SOQL Queries, we can able to perform the DML operations upto 50000
records only. Where it perform the operations in a single instance.
- Batch Apex will perform DML operations on maximum of 50 million records,
Where it will divide the records into various small chunks called Batch and
perform DML statement on each batch.

- To implement the Batch Apex, we have to implement our class with an Interface
called as "Database.Batchable<sobject>".

Note: Batch Apex class should be defined as "Global". Because these Batch /
Schedule classes should be executed by the other resources of Salesforce.

Syntax:
Global Class <Class_Name> implements Database.Batchable<Sobject>
{
// Write Business Logic..
}

- Batchable Interface provides the following methods.

1. Global Database.QueryLocator Start(Database.BatchableContext <RefName>)


- This method will get all the records by executing the SOQL query and store
the record into the Cache, and store the memory address of the records in the
QueryLocator.

- It divide the all the records into the various batches of specified size.
- Batch size can be between 1 to 2000. Default batch size is 200.
- It will pass each batch records to the "Execute" method to perform the
DML operations / for further processing.

2. Global Void Execute(Database.BatchableContext <RefName>):


- This method contains the actual business logic to perform the DML
operations on the records.
- Once it is done with the operations on the Batch records, it will indicate
the Start method, So that Start() method will provide the next batch records.
This process will continue upto the last batch.

Note: Each Batch will be executed as a Discrete Transaction.(i.e. it doesn't


remember the information about the previous batch records)

- Once the Batch has been executed with the Execute method, it will reset
the governor limits. (i.e it will bypass the governor limits).

3. Global Void Finish(Database.BatchableContext <RefName>):


- This method will execute after executing all the batches.
- This method is used to perform the Post Execution operations, like
Sending Email, etc.

Executing the Batch Apex Class: (Manual Execution)

We can execute the Batch Apex class with below methods.


1. Manual Execution (Using Execute Anonymous Window)
2. Scheduling Process (Using Schedule Apex).

- To execute the Batch Apex Class, we have to use the Database.ExecuteBatch()


method as follows.

Syntax:
1. Database.ExecuteBatch(<BatchClassObjectName>)
2. Database.ExecuteBatch(<BatchClassObjectName>, integer batchsize)

// Create the Object of the Batch Class in Anonymous Window and Execute the
Below code:

DeleteAccountObjectRecords objBatch = new DeleteAccountObjectRecords ();


Database.executeBatch(objBatch, 50);

/* Apex Batch Job to Update All Account Records, whose name is starting with
'Database'.
Update Website = 'www.Reliance.com'
NumberOfEmployees = 100;

*/

Global class UpdateAccountsWebsiteBatch implements


Database.Batchable<SObject>
{
Global Database.QueryLocator Start(Database.BatchableContext BC)
{
string accNameStartsWith = 'Database%';
string soqlQuery = 'Select Id, name, rating, website from account where
name like : accNameStartsWith and website != null ';

return Database.getQueryLocator(soqlQuery);
}

Global void Execute(Database.BatchableContext BC, List<SObject> lstSObject)


{
List<Account> lstAccounts = new List<Account>();

for(SObject s : lstSObject)
{
Account accRec = (Account)s;
accRec.Website = 'www.Reliance.com';
accRec.NumberOfEmployees = 100;

lstAccounts.add(accRec);
}

if(! lstAccounts.isEmpty())
{
update lstAccounts;
}
}
Global void Finish(Database.BatchableContext BC)
{
system.debug('Current Batch ID is....: ' + BC.GetJobID());

AsyncApexJob jobDetails = [select id, status, totalJobItems,


jobitemsprocessed, numberoferrors, createdby.email
from asyncapexjob where id =: BC.GetJobID()];

string emailSubject = 'Batch Job UpdateAccountsWebsiteBatch : ' +


jobDetails.Id + ' Execution Status';

string[] toAddresses = new string[]{jobDetails.CreatedBy.Email,


'[email protected]'};

Messaging.SingleEmailMessage email = new


Messaging.SingleEmailMessage();

email.setToAddresses(toAddresses);
email.setReplyTo('[email protected]');
email.setSenderDisplayName('QEdge Account Website Update Batch');
email.setSubject(emailSubject);

string emailContent = ' Your Batch UpdateAccountsWebsiteBatch Id : ' +


jobDetails.Id + ' <br><br>'+
'Batch Job Status is....: ' + jobDetails.Status +
'<br><br>' +
'Total Number Of Batches ....: ' +
jobDetails.TotalJobItems + '<br><br>' +
'Total Number Errors Occured...: ' +
jobdetails.NumberOfErrors + '<br><br>' +
'Total Job Items Processed.....: ' +
jobDetails.JobItemsProcessed ;

email.setHtmlBody(emailContent);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Execution:
---------
// Creating Object for BatchApex class...
UpdateAccountsWebsiteBatch acc = new UpdateAccountsWebsiteBatch();
Database.executeBatch(acc, 50); // Batch size is : 50
//Database.executeBatch(acc); --> Default Batch size : 200

/ Create a Batch Apex class to Delete the Account Records, Which are having the
"Delete" (Check Box)field status as "TRUE"
*/

global class DeleteAccountObjectRecords implements


Database.Batchable<sObject>

{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String Query = 'select id from Account where Delete__c = true';
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<sObject> scope)


{
List <Account> lstAccount = new list<Account>();

for(Sobject s : scope)
{
Account a = (Account)s;
lstAccount.add(a);
}

Delete lstAccount;
}

global void finish(Database.BatchableContext BC)

{
// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.

AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,


TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id =: BC.getJobId
()];

// Send an email to the Apex job's submitter notifying of job completion.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();


String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation ' + a.Status);
mail.setPlainTextBody
('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+
a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Test Classes:

Test Class:
===========
@isTest
Public class ArithmeticOperationsClassTest
{
testmethod static void TestOperations()
{
ArithmeticOperationsClass a = new ArithmeticOperationsClass();
a.Addition(200,456);
a.Subtraction(400,200);
a.Multiplication(45,34,45);
a.Division(45,5);

}
}

===============================================
Apex Class:
===========
/**
@Author: Feroz Beg
@name: LeadHandler
@CreateDate:
@Description: This class provides the ability to Handle the Lead to Prospect
Synchronization.
@Version: 1.0
@reference:
*/

public class LeadHandler


{
// This Method is used to Convert the Lead Automatically, upon updating Lead
Status as "Closed - Converted"
Public static Void AutoLeadConversion(Map<Id,Lead> mapLeads)
{
LeadStatus status = [select id, masterlabel from leadstatus where isconverted
= true limit 1 ];
List<Database.LeadConvert> lstConverts = new
List<Database.LeadConvert>();

if(!mapLeads.isEmpty())
{
for(Lead l : mapLeads.values())
{
if(l.Status == 'Closed - Converted')
{
Database.LeadConvert lc = new Database.LeadConvert();
lc.SetLeadId(l.Id);
lc.SetConvertedStatus(Status.MasterLabel);
lc.setSendNotificationEmail(false);

if(l.Do_Not_Create_Opportunity__c == true)
{
lc.SetDoNotCreateOpportunity(true);
}

lstConverts.add(lc);
}
}

List<Database.LeadConvertResult> lcResults= new


List<Database.LeadConvertResult>();

if(!lstConverts.isEmpty())
{
try
{
lcResults = Database.convertLead(lstConverts);
}
Catch(DMLException d)
{
system.debug('DML Exception Occured during Lead Conversion.' +
d.getMessage() + '-- StackTrace string :'+ d.getStackTraceString());
}
Catch(Exception e)
{
system.debug('Exception Occured during Lead Conversion.' +
e.getMessage() + '-- StackTrace string :'+ e.getStackTraceString());
}

}
}

// This method will create an associated Prospect Record, upon creating a


new Lead.
Public static void AfterInsert(List<Lead> lstLeads)
{
List<Prospect__c> lstProspects = new List<Prospect__c>();

for(Lead ld : lstLeads)
{
Prospect__c p = new Prospect__c();

p.FirstName__c = ld.FirstName;
p.Name = ld.LastName;
p.Phone__C = ld.Phone;
p.Email__c = ld.Email;
p.Fax__c = ld.Fax;
p.Rating__c = ld.rating;
p.Industry__C = ld.Industry;
p.Lead_Source__C = ld.LeadSource;
p.Passport_Number__c = ld.Passport_Number__c;
p.ssn_Number__c = ld.ssn_Number__c;
p.Product_interest__c = ld.ProductInterest__c;
p.Primary__c = ld.Primary__c;
p.Company__c = ld.Company;
p.Website__C = ld.Website;
p.Lead_Status__c = ld.Status;
p.Annual_Revenue__c = ld.annualrevenue;
p.Lead__C = ld.id;

lstProspects.Add(p);
}

try
{
if(!lstProspects.isEmpty())
insert lstProspects;
}
catch(DMLException dex)
{
system.debug('DML Exception Occured during Prospect Creation.' +
dex.getMessage() + '-- StackTrace string :'+ dex.getStackTraceString());
}

// This method will update the associated Prospect Record, upon updating the
Lead record.
Public static void AfterUpdate(Map<Id,Lead> mapLeads, Map<Id,Lead>
oldLeads)
{
List<Prospect__c> prospectsToUpdate =new List<Prospect__C>();

Map<Id,User> mapActiveStaff = StaffMethods.GetActiveStaffUsers();


List<Prospect__c> lstProspects = [select id,FirstName__c
,Name ,Email__c,Fax__c,Rating__c,
Industry__C,Passport_Number__c
,ssn_Number__c,Product_interest__c,Primary__c
,Company__c ,Website__C, ownerid
,Annual_Revenue__c, lead__C from Prospect__C where
lead__c IN : mapLeads.keySet()];

if(!lstProspects.isEmpty())
{
for(Prospect__C p : lstProspects)
{
for(Lead l : mapLeads.values())
{
if(p.Lead__c == l.id)
{
p.FirstName__c = l.FirstName;
p.Name = l.LastName;
p.Phone__C = l.Phone;
p.Email__c = l.Email;
p.Fax__c = l.Fax;
p.Rating__c = l.rating;
p.Industry__C = l.Industry;
p.Lead_Source__C = l.LeadSource;
p.Passport_Number__c = l.Passport_Number__c;
p.ssn_Number__c = l.ssn_Number__c;
p.Product_interest__c = l.ProductInterest__c;
p.Primary__c = l.Primary__c;
p.Company__c = l.Company;
p.Website__C = l.Website;
p.Annual_Revenue__c = l.annualrevenue;
p.Lead_Status__c = l.status;
// Trasfering Prospect to another user...
if((oldLeads.get(l.Id).Prospect_owner__C !=
mapLeads.get(l.Id).Prospect_owner__c) &&
mapActiveStaff.containsKey(l.Prospect_owner__C))
{
p.OwnerId = mapLeads.get(l.Id).Prospect_owner__c;
}

prospectsToUpdate.Add(p);
}
}
}

try
{
if(!prospectsToUpdate.isEmpty())
update prospectsToUpdate;
}
catch(DMLException e)
{
system.debug('DML Exception Occured during Prospect Creation.' +
e.getMessage() + '-- StackTrace string :'+ e.getStackTraceString());
}
}
}
}

Test Class:
===========

@isTest
Public class LeadHandlerTest
{
testmethod static void TestAfterInsert()
{
List<Lead> lstLeads = new List<Lead>();

Lead l1 = new Lead(firstname='firstname1', lastname='lastname1',


industry='Banking',annualrevenue=400000,rating='Warm',LeadSource='Web',stat
us='Open - Not Contacted',ssn_number__c='12312',passport_number__c
='45456', company ='Wipro');

Lead l2 = new Lead(firstname='firstname2', lastname='lastname2',


industry='Banking',annualrevenue=400000,rating='Warm',LeadSource='Web',stat
us='Open - Not Contacted',ssn_number__c='12312',passport_number__c
='45456', company ='Wipro');

Lead l3= new Lead(firstname='firstname3', lastname='lastname3',


industry='Banking',annualrevenue=400000,rating='Warm',LeadSource='Web',stat
us='Open - Not Contacted',ssn_number__c='12312',passport_number__c
='45456', company ='Wipro');

lstLeads.Add(l1);
lstLeads.Add(l2);

Test.StartTest();

insert lstLeads;

List<Lead> leadsToUpdate = [select id, firstname, lastname, industry,


annualrevenue from lead where industry ='Banking'];
if(! leadsToUpdate.isEmpty())
{
for(Lead l : leadsToUpdate)
{
l.firstname= l.firstname + '-Updated';
}

Update leadsToUpdate;

insert l3;

Lead l = [select id, firstname, lastname, status from lead where id=: l3.id
limit 1];

if(l != null)
{
l.Status ='Closed - Converted';

update l;
}
}

Test.StopTest();

}
}

============================================
Apex Class:
-----------
// Apex Class to send Email Notifications...

Public Class MessagingUtility


{
Public static void SendEmailTocandidate(Candidate__C cndRec, string
emailSubject)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();
if(cndRec != null)
{
Candidate__C cnd = [select id, name, email_id__C, Location__c,
PositionName__c from Candidate__C where id =: cndRec.id limit 1];

Position__c pos= [select id, name from position__c where id =:


cnd.PositionName__c];

string[] toAddress = new string[]{cnd.email_id__C, '[email protected]'};

email.SetToaddresses(toAddress);

email.SetSubject(emailSubject);
email.SetReplyTo(cnd.email_id__C);
email.SetSenderDisplayName('QEdge Support Center');

/*
// To Send the Plain Text Information..

string emailContent = 'Hi '+ cnd.Name + 'Thanks for apllying for the position
' + pos.Name + '. We will have a look into your profile and out HR Team will get
back to you shortly. Thanks & Regards, ABC Technologies ';

email.SetPlainTextBody(emailContent);

// This is having Hard Coded value for BaseURL..


string emailHTMLContent = 'Dear ' + cnd.Name + '<br><br>' + 'Thanks for
Appying the Position for <b>' + pos.Name + '</b>. <br> <br>' + 'We will review
your profile and come back to you if any suitable matching requirement. <b> Here
is your Candidature Record. <a href=https://ap2.salesforce.com/'+ cnd.Id +'> Click
Here </a> . <br> Thanks and Regards,<br> <b> ABC Technologies</b>';
*/

string emailHTMLContent = 'Dear ' + cnd.Name + '<br><br>' + 'Thanks for


Appying the Position for <b>' + pos.Name + '</b>. <br> <br>' + 'We will review
your profile and come back to you if any suitable matching requirement. <b> Here
is your Candidature Record. <a href='+
System.Url.getSalesforceBaseUrl().ToExternalForm() + '/'+ cnd.Id +'> Click Here
</a> . <br> Thanks and Regards,<br> <b> ABC Technologies</b>';
email.SetHTMLBody(emailHTMLContent);

Messaging.SendEmail(new Messaging.SingleEmailMessage[]{email});

}
}

Test Class:
-----------
@isTest
Public class MessagingUtilityTest
{
testmethod static void TestEmailToCandidate()
{

Position__c p = new Position__c();


p.name = 'SAS Developer';
p.Location__c = 'Hyderabad';
p.Open_date__c = system.today();
p.Number_Of_Positions__c = 2;
p.Close_Date__C = system.today().AddDays(30);
p.minimum_pay__C = 3400000;
p.maximum_pay__C = 4500000;
p.position_description__c = 'SAS Developer, Medical Coding, Clinical
Programming.';

insert p;

Candidate__C c = new Candidate__C();


c.Name = 'Kiran Kumar';
c.Location__c = 'Bangalore';
c.pan_Number__c = '121232';
c.Qualification__C = 'MCA';
c.Notice_period__C = '1 Month';
c.PositionName__c = p.id;
c.email_id__C = '[email protected]';
c.contact_number__c = '9966554411';
c.expected_ctc__c = 450000;

Test.StartTest();

insert c;

MessagingUtility.SendEmailTocandidate(c, 'Congratulations...!!
Your Candidature has been submitted successfully.');

Test.StopTest();

}
}

==================================
Batch Apex Class:
-----------------

Global class UpdateAccountsWebsiteBatch implements


Database.Batchable<SObject>
{
Global Database.QueryLocator Start(Database.BatchableContext BC)
{
string accNameStartsWith = 'Database%';
string soqlQuery = 'Select Id, name, rating, website from account where
name like : accNameStartsWith and website != null ';

return Database.getQueryLocator(soqlQuery);
}

Global void Execute(Database.BatchableContext BC, List<SObject> lstSObject)


{
List<Account> lstAccounts = new List<Account>();

for(SObject s : lstSObject)
{
Account accRec = (Account)s;
accRec.Website = 'www.Reliance.com';
accRec.NumberOfEmployees = 100;

lstAccounts.add(accRec);
}

if(! lstAccounts.isEmpty())
{
update lstAccounts;
}
}

Global void Finish(Database.BatchableContext BC)


{
system.debug('Current Batch ID is....: ' + BC.GetJobID());

AsyncApexJob jobDetails = [select id, status, totalJobItems,


jobitemsprocessed, numberoferrors, createdby.email
from asyncapexjob where id =: BC.GetJobID()];

string emailSubject = 'Batch Job UpdateAccountsWebsiteBatch : ' +


jobDetails.Id + ' Execution Status';

string[] toAddresses = new string[]{jobDetails.CreatedBy.Email,


'[email protected]'};
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();

email.setToAddresses(toAddresses);
email.setReplyTo('[email protected]');
email.setSenderDisplayName('QEdge Account Website Update Batch');
email.setSubject(emailSubject);

string emailContent = ' Your Batch UpdateAccountsWebsiteBatch Id : ' +


jobDetails.Id + ' <br><br>'+
'Batch Job Status is....: ' + jobDetails.Status + '<br><br>' +
'Total Number Of Batches ....: ' + jobDetails.TotalJobItems + '<br><br>'
+
'Total Number Errors Occured...: ' + jobdetails.NumberOfErrors +
'<br><br>' +
'Total Job Items Processed.....: ' + jobDetails.JobItemsProcessed ;

email.setHtmlBody(emailContent);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Test Class:
-----------
@isTest
Public class UpdateAccountsWebsiteBatchTest
{
testmethod static void TestAccountBatch()
{

List<Account> lstAccounts = new List<Account>();


for(integer counter = 1; counter<=100; counter++)
{
Account a = new Account();
a.name = 'Database Test-' + counter;
a.rating = 'Hot';
a.annualrevenue = 34000;
a.industry = 'Insurance';
a.Type = 'Prospect';
a.phone = '9966554400';
a.active__c = 'Yes';
a.fax = '8899552200';
a.website = 'www.gmail.com';
a.pan_Number__c = 'alppb-4334-e';

lstAccounts.Add(a);

UpdateAccountsWebsiteBatch bat = new


UpdateAccountsWebsiteBatch();

Test.StartTest();

insert lstAccounts;
Database.ExecuteBatch(bat);

Test.StopTest();
}
}

=====================================
Apex Class:
-----------
public class MassEmailClass
{
Public static void SendMassEmailsToContacts()
{
string lastNameStartsWith = 'b%';

Map<Id, Contact> mapContacts = new Map<Id, Contact>(


[select id, firstname, lastname, email from contact
where lastname like : lastNameStartsWith]);

List<ID> contactIds = new List<ID>();

if(! mapContacts.isEmpty())
{
contactIDs.addAll(mapContacts.keyset());

system.debug('Contact Record Ids ....: ' + contactIDs);

Messaging.reserveMassEmailCapacity(4);
Messaging.MassEmailMessage email = new
Messaging.MassEmailMessage();

email.setSenderDisplayName('QEdge Support Center Mass Email.');


email.setReplyTo('[email protected]');
email.setTargetObjectIds(contactIDs);
List<EmailTemplate> templateId = [select id, name from emailtemplate
where name =: 'New Year Wishes' ];
email.setTemplateId(templateId[0].id);

Messaging.SendEmail(new Messaging.MassEmailMessage[] {email});

}
}
Test Class?
-----------

================================================
Apex Class:
===========
Public class ProspectHandler
{
/*
* This method is used to Update the Associated Lead Record upon updating
Prospect record.
*/

Public static void AfterUpdate(Map<ID, Prospect__C> mapPros)


{
Set<ID> leadIds = new Set<Id>();
List<Lead> leadsToUpdate = new List<Lead>();

if(!mapPros.isEmpty())
{
for(Prospect__c p : mapPros.values())
{
if(p.lead__C != null)
{
leadIDs.Add(p.lead__C);
}
}

Map<ID, Lead> mapLeads = new Map<ID, Lead>([select id,


firstname,lastname, email,company, title, website, phone, fax, rating, industry,
status, leadsource, productinterest__C,primary__c,
ssn_Number__C,passport_Number__C, AnnualRevenue from lead where id IN :
leadIDs]);
if(!mapLeads.isEmpty())
{
for(Prospect__c p : mapPros.values())
{
if(mapLeads.ContainsKey(p.Lead__C))
{
Lead l = mapLeads.get(p.Lead__C);
l.firstname = p.FirstName__C;
l.lastname = p.Name;
l.email = p.Email__C;
l.company= p.Company__c;
l.website= p.Website__C;
l.phone= p.Phone__c;
l.fax= p.Fax__C;
l.rating= p.Rating__C;
l.industry= p.Industry__c;
l.status= p.Lead_status__c;
l.leadsource= p.Lead_source__C;
l.productinterest__C= p.Product_Interest__C;
l.primary__c = p.Primary__c;
l.ssn_Number__C= p.ssn_Number__C;
l.passport_Number__C= p.passport_Number__C;
l.AnnualRevenue= p.Annual_Revenue__c;

leadsToUpdate.Add(l);
}
}
if(!leadsToUpdate.isEmpty())
update leadsToUpdate;
/*
try
{
if(!leadsToUpdate.isEmpty())
update leadsToUpdate;
}
Catch(DMLException d)
{
system.debug('DML Exception Occured.' + d.getMessage() + ' Stack
Trace : '+ d.getStackTraceString());
}
Catch(Exception e)
{
system.debug('Exception Occured.' + e.getMessage() + ' Stack Trace :
'+ e.getStackTraceString());
}
*/
}
}
}
}

Test Class?
-----------

FUTURE ANNOTATION IN Salesforce


===============================

There are two types of objects that you can interact with on the platform.

Setup Objects:
==============
- A "setup" object is one that must be edited from the setup or builder area of the
platform.

- Use setup objects to interact with metadata for declarative development.


For example, you may wish to create your own version of Setup, or restrict the
amount of data you need to push to an app on a mobile phone.

Ex: User, UserRole, UserTerritory,Territory, GroupMember, RecordType, Profile,


QueueObject, CustomField, CustomObject, CustomTab, EmailTemplate, FieldSet,
RecentlyViewed,...etc.

Non-Setup Objects:
==================
Non-Setup objects can be any one of standard objects like Account / Contact /
Lead / Opportunity...etc or any custom object created by user / developer.

Ex: Position__C, Customer__C, Account, Contact, Opportunity , Product,


PriceBook, etc...

UseCase:
========
When we try to perform the DML operations on both Setup Object and Non-
Setup object in a Single Transaction, Salesforce will throws the
"MIXED_DML_OPERATION Exception".

i.e. I am updating a User Record and Updating an Account record in the same
context as below.

Example:
========
Public class MixedDMLExceptionTestClass
{
Public static void DoDMLOperations()
{
// Making User Record DeActive (Updating - DML)..

User u = [select id, username, isActive from user where username =


'[email protected]' limit 1];
if(u != null )
{
system.debug('User Record is...: '+ u);

u.isActive = false;
update u;

System.debug('User Record Updated Successfully. : ' + u);


}

// Udating Account Record's Annual Revenue value (DML)..

Account acc = [select id, name, rating, annualrevenue from account where
name ='Query String Test' limit 1];
system.debug('Account Record is....: '+ acc);

if(acc != null)
{
acc.annualrevenue = 60000;
update acc;

System.debug('Account Record Updated Successfully. : '+ acc);


}

}
}

Testing:
---------
MixedDMLExceptionTestClass.DoDMLOperations();

Result:
-------
You will be receiving the "MIXED_DML_OPERATION" Exception. As we can't
perform DML operations on both Setup and Non-Setup objects in a single
transaction (and vice versa).

Solution:
=========
To avoid these issues, we need to use "Future Annotated Methods", defined with
the help of "@Future()" annotation.

FUTURE METHODS:
===============
The future annotation is a great feature on the Salesforce Platform to allow you to
execute custom logic asynchronously.

Use the future annotation to identify methods that are executed asynchronously.
When you specify future, the method executes when Salesforce has available
resources.

For example, you can use the future annotation when making an asynchronous
Web service callout to an external service.

A future method runs in the background, asynchronously.

You can call a future method for executing long-running operations, such as
callouts to external Web services or any operation you’d like to run in its own
thread, on its own time.

Note: You can also make use of future methods to isolate DML operations on
different sObject types to prevent the "Mixed DML Error".

Each future method is queued and executes when system resources become
available.
That way, the execution of your code doesn’t have to wait for the completion of a
long-running operation. A benefit of using future methods is that some governor
limits are higher, such as SOQL query limits and heap size limits

- We need to use the "@Future" annotation to define Future Methods.


Syntax:

Global Class <ClassName>


{
@future
Public static void <FutureMethodName>(<Parameters List>)
{
// Todo..
}
}

Rules / Considerations:

1. Future Annotated method should be always "Static".


2. Future methods return type should be "Void" always.
3. The specified parameters must be primitive data types, arrays of primitive data
types, or collections of primitive data types.

Note: We can't pass SObjectTypes / Object Types as parameters to Future


methods.
4. We can't call One Future method from another Future annotated method.
5. The maximum number of future method invocations per a 24-hour period is
250,000 or the number of user licenses in your organization multiplied by 200,
whichever is greater
6. Methods with the future annotation cannot be used in Visualforce controllers
in either getMethodName or setMethodName methods, nor in the constructor.
7. Asynchronous calls, such as @Future or ExecuteBatch, called in a startTest,
stopTest block, do not count against your limits for the number of queued jobs
Solution:

Public class MixedDMLExceptionTestClass


{
Public static void DoDMLOperations()
{
User u = [select id, username, isActive from user where username =
'[email protected]' limit 1];

if(u != null )
{
system.debug('User Record is...: '+ u);

u.isActive = false;
update u;

System.debug('User Record Updated Successfully. : ' + u);


}

UpdateAccount();

@future()
Public static void UpdateAccount()
{
Account acc = [select id, name, rating, annualrevenue from account where
name ='Query String Test' limit 1];
system.debug('Account Record is....: '+ acc);

if(acc != null)
{
acc.annualrevenue = 60000;
update acc;
System.debug('Account Record Updated Successfully. : '+ acc);
}

}
}

Testing:
========
MixedDMLExceptionTestClass.DoDMLOperations();

Test Class for Future Methods:


=============================
@isTest
Public class MixedDMLExceptionTestClassTest
{
testmethod static void TestDMLOperation()
{
Profile p = [select id, name from profile where name = 'Standard User'];
User u = new User(firstname='test',lastname='userrec', username =
'[email protected]', isActive=true, email='[email protected]',
alias='testuser',EmailEncodingKey='UTF-8', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles');

Account a = new Account(name='Query String


Test',rating='Hot',Industry='Banking',active__C='Yes',annualrevenue=400000,type
='prospect',pan_number__C='alppb9219e', website='www.test.com');

Test.startTest();
insert u;
insert a;

MixedDMLExceptionTestClass.DoDMLOperations();
Test.StopTest();
}
}

// Write an Apex Program to Update Rating Value as "Warm" for the Accounts
Associated with the Industry "Finance / Chemical / HealthCare"
list<account> lstacc = [select id, name, industry, rating from account where
industry IN('chemical', 'Finance','Healthcare')];
for(account acc: lstacc)
{
acc.rating=’warm';
}
update lstacc;
system.debug(lstacc);

// write an apex program to update all associated contacts owner with the
same as parent account owner up on changing the account owner value.
Account acc =[select id, name, ownerId from account where name =:'harsh
technologies' ];
system.debug(acc);
acc.ownerId = '00561000000rOPpAAM';
update acc;
id accid =acc.id;
List<contact> lstcon =[select id, ownerid from contact where accountid=:accid ];
for(contact con:lstcon)
{
con.ownerId = acc.ownerId;
system.debug(con);
}
update lstcon;
// Write an Apex Program to fetch all converted lead records and their
associated Account , Contact and Opportunities.
Here two ways to execute the programe:
list<lead> lstlea =([select id,name, convertedaccountid, convertedcontactid,
convertedopportunityid from lead where isconverted=:true]);
system.debug(lstlea.size());
for(lead le:lstlea)
system.debug(le);

// Added by Feroz : 25/12/2015:


1. Best Practices of a trigger
2. Is it advisable to call batch class from trigger? If Yes, Why? If No, Why?
3. What are actionSupport and actionFunction? Differences ?
4. What is viewstate error? Best Practices to avoid the same ?
5. OWD on an object is Private. On Profiles, Only READ access has been provided and there
are no permission sets assigned, but still user is able to view and edit records. what might be
the reason?
6. What happens if you delete one of the master records in many to many relationship ?
7. What are the tough situations which you faced in project technically?
8. Data from popup window needs to be passed back to calling parent window. How to
achieve this ?
9. What are custom settings ?
10. Can we deploy a class without test class/ code coverage? Is it advisable? If Not, Why?
11. Difference between Enterprise and partner WSDL
12. Which one you prefer, SOAP or REST for mobile applications ?
13. Workflow rule limitations ?
14. How do you control the insertion or deletion of detail records ?
15. Validation rule to allow only a particular user to edit a field. For others, error message
should thrown?
16. What is database.stateful ?

One Top MNC Asked These Questions In Interview.Please Try To Answer These
Questions. All The Best Friends.

1.what are visualforce tabs in salesforce?


2.how to create a custom tab in sfdc?
3.what is the support process in sfdc?
4.have you done any certification?
5.how much rating you will give out of 10 in sfdc?
6.have you create any custom list view in sfdc?
7.have you used any app in sfdc mobile platform?
8.have you worked on case object in your project?
9.difference b/w validation and workflows?
10.scenario: we have two custom objects i want to create master detail
relationship b/w then as laptop is master and mobile is detail.
11.we have laptop is custom object,can we create masterdetail relationship
with opprtunity in such a way that laptop is master and oppertunity is detail?
12.can we create a masterdetail relation with account by any custom object in a
way that account is detail &any custom object is master side?
13. what is junction object and how we use?
14.what are the required fields to we use?
15.how can we remove user accounts from sfdc?
16.when we deactivate a user what will happen any record which are assosiated
with that user
suppose an oppertunities in progress then what will happen to that
oppertunity?
17.when we deactivate user is these any pre defined peocess to deactivate
user?
18.difference b/w deactivate & freeze or queues?
19.which tool you used for deployed?
20.do you need certain code coverage?
21.suppose i did not test and code coverage is also zero then how can we
deployed?
22.what is report & types of reports?
23.i create one custom field an apportunity object without any coading,when i
am trying to create a report for opportunity
i can't drag and drop that custom field then how can we do?
24.Reports will generated by system(or) we have to create ?
25.what are the dml operations we have in dataloader?
26.difference b/w export and exportall?
27.whatis the url to accsess the sandbox?
28.difference b/w renderd and rerendered?
29.how to you ovrride button in vfpage?
30.what are vf component and whendo we use them?
31.diff b/n data table and pageblock table?
32.what is a wrapper class?
34.what are the changes on collection in winter 16 ?
35.what are the governor limits in SFDC ?
36.I have to display 400 records on ascreen how can we display?
37.what are the collections in SFDC ?
which is ordered?
which allows duplcates and which does not?
38. I have to perform sum validations which triggers , I have to use ?
39. what is batch apex, how can wu use?
40. how do we use scheduled apex?
41. diff b/n normal class and test class?

Please Try To Answer These Questions.


1)What Is current Project?
2)Have you Worked On Configuration?
3)Diff Between Role & Profile?
4)Diff Between OWD & Shareing Rules?
5)What Is Manual Sahring?
6)Types Of Relationships SFDC Supports?
7) Diff Between Lookup & Master Detail?
8)What is Junction Object? What is User?
Can you give any scenario where we have created Junction Object?
9) Can I Make A PICK List field Mandatory? How can we do it Mandatory?
10) what is workflow Process?
11)Have You worked On Cross Object Formule?
12) what are Governor Limits & why sfdc Introduced Governor Limits?
13)How can we Overcome Governer Limites?
14) What is the purpose of batch Appex?
15)Give me One scenario where we can use Batch Appex?
16) Diff Between Trigger.New & Trigger. Old?
17) Give Me Scenario Where we have to use Trigger?
18) Order of ExecutionS Validations AND Before Trigger And Assignment Rules?
19)What is Record Types?
20)Diff Between Page Block Table AND Data Table?
21)What is the purpose of rendered and rerendered?
22)What IS Major Issues You Faced When Deployment?

You might also like