Beruflich Dokumente
Kultur Dokumente
Salesforce Company.
Feature of Apex:
1. STRONGLY TYPED LANGUAGE: It is Strongly Typed Language, so every variable in Apex will be declared with the specific data
type. All apex variables are initialized to null initially. It is always recommended for a developer to make sure that proper
values are assigned to the variables.
2. Similar to Java Syntax: Apex syntax is just like Java Syntax such as variable declaration, Loop Sytnax, Conditional Statement
syntax ,Class syntax etc.,
3. Integrated with Data: Apex can integrate with all types of DML statements such as INSERT, UPDATE, DELETE. We can easily
embed with SOSL and SOQL Statements with Apex coding.
4. It Supports Multitenant Architecture.
5. Apex automatically upgraded whenever the new version releases, we no need to upgrade Manually.
6. It is a case insensitive language.
7. It upgrades automatically, it means we no need to upgrade our development kit or compiler or interpreter.
8. It is very easy to test, it provides built in support or functionality to write and execute the test cases.
9. It runs on Multitenant Environment.
1. When we want to do some automation that cannot be implemented using workflows and process builder in that case we have
to write the code in Apex Trigger.
2. When we need to write complex validation rules. For Ex we want to validate that the account we are creating do not have
phone number or email id similar to any of the other account that you have available. So, those kind of validations are not
possible through point and click (configuration) for that we need to write a code in Apex.
3. If we want to interact with external application we need to use web services (integration) and creating email services for that
we need to use Apex.
4. Whenever we want to do certain transactions and we need to control those transactions using some savepoints and rollbacks
we can use Apex.
Limitations of Apex:
1. Apex is not available in Professional Edition, Governor Limits, Code is not maintnable as compared to the point and click tools
and declarative approaches.
2. We cannot show anything on UI(user Inteface) using Apex, except Error Messages.
3. Using Apex we cannot change any salesforce functionality. We can only add new functionality and stop the execution of the
existing functionality to do particular action.
4. Apex cannot create any temporary files. So there is no file handling concept in Apex.
5. We cannot create multiple threads in Apex.
Data Types in APEX:
1.Integer : This data type allows us to enter Integer values such as either positive or negative numbers. The range of this
datatype is -2117483648 to +2117483647.
Ex: Integer roll_number=1001;
2. Long: This data type allows us to enter Integer values such as either positive or negative numbers. The range of this data
type is 2^63 to 2^63-1. It allows us to enter the value like mobile numbers, Account Number etc.,
3. Decimal: This data type allows us to enter decimal values such as employee salary, student fees which are particularly currency
field values.
Ex: Decimal salary=9875.97;
4. Double: This data type allows us to enter decimal values. Ex: Double total_balance=98535252.9525;
5. Boolean: This data type allows us to enter true or false values. Ex: Boolean status=true;
6. String: This data type allows us to enter String values such as names etc., Ex: String iname=’oscar it’;
7. Date: This data type allows us to enter date values such as joining date etc.,
Ex: date variable name= date.newInstance(yyyy,mm,dd); Date hiredate =date.newInstance(2019,08,15);
8. Time: This data type allows us to enter time values such as login time etc.,
time variable name= time.newInstance(hh,mi,ss,ms); ex: Time login_time = time.newInstance(10,15,40,49);
9. DateTime: This datatype allows us to enter Datetime both. DateTime Variable name =
datetime.newInstance(yyyy,mm,dd,hh,mi,ss); DateTime dt= datetime.newInstance(2019,10,06,09,08,45);
10. Void: This data type does not return any value, Especially we use this operator while using functions.
1. ID: It allows us to enter Alphanumeric values. The maximum length of this data type is 15 digits.
These ID’s are not entered by user, it is automatically generated by SF. It is always unique value.
Ex: Car number, Student Id etc.,
2. Binary Large Object(BLOB): It allows us to enter any kind of Image, MMS, Text files, Audio, Video files etc.,
3. Sobject: It is a storage space, it stores the data in the form of rows and cols. Matrix format.
Operators In Apex:
1. Variable name must starts with an alphabet and it contains minimum 1 character and maximum 256 characters.
2. It does not allowed any kind of special characters except _ and 0 to 9 numbers.
3. Variables names should not use any keywords.
4. It is not case sensitive a and A both are same.
Ex: student valid
Student123 valid
123student invalid
_123student invalid
Student#123 invalid
Syntax to declare a variable:
Datatype identifier/variable; or Datatype Identifier/Variable = Value;
Ex: integer sno; or Integer sno=1001
Programs:
Control Statements: These statements are used to control the flow of execution of the program.
By default, execution begins from top of the program and ends with bottom of the program and every statement gets executed only once.
Sometimes this flow might not be accepted, depending up on some values, depending upon certain conditions,
Some statements should get executed, some statements should not executed, some statements should skipped, and some statements
should executed repeatedly.
For this, we have 3 types of Control Statements.
1. Simple condition control Statements: Statements are executed once based on some condition or Skips the statements. Ex: if - else
2. Iterative Control Statements: Statements are executed repeatedly based on some condition.
Ex: for loop, for each, while and do – while loop
3. Jump Statements: moves the control from one block of statements to another block of statements.
Goto , break, function call, return .
IF-Condition:
1. simple If ,2. if – else ,3. if- else if (series of If else ), 4. nested if, 5. series of if(collection of simple if, no else).
If(condition)
{
Statement 1;
Statement n;
}
Syntax of If-Else:
If(condition)
{
Statement 1;
Statement n;
}
Else
{
Statement 1;
Statement n;
}
Sytnax of If-Else-If
If(condition)
{
Statement 1;
Statement n;
Else
if
Statement 1;
Statement n;
if(condition)
{
Statement 1;
Statement n;
}
If(condition)
{
Statement 1;
Statement n;
}
Syntax of Nested If:
If(condition)
If(condition)
{
Statement 1;
Statement n;
}
Else
{
Statement 1;
Statement n;
}
Else
If(condition)
If(condition)
{
Statement 1;
Statement n;
}
Else
{
Statement 1;
Statement n;
}
}
Programs:
2.Iterative Statements (Loops): Whenever we need to execute a single statement or set of statements repeatedly, then we need to use
Loops. Loops are divide into 2 types.
Range Based Loops: A Range based loop is a loop statement which executes the statements as long as the initial value reaches the final
value. Once control Crossed the final value then control automatically comes of the loop.
For(initialization;condition;incrementation/decrementation)
{
Statement 1;
Statement n;
}
Ex:
Integer I;
For(i=1;i<=10;i++)
{
System.debug(i);
}
Note: For Each loop we will discuss in Collections Topic.
Conditional Based Loops: A condition based loop is a loop statement which executes the statements as long as the given condition is
satisfied. Once condition is false then control automatically comes of the loop.
While(condition)
{
Statement 1;
Statement n;
}
Ex:
Integer I=1;
While(i<=10)
{
System.debug(i);
I++;
}
Syntax of Do-While:
Do
{
Statement 1;
Statement n;
} while(condition);
Ex:
Integer i=1;
Do
{
System.debug(i);
I++;
}while(i<=10);
3.Jump Statements: In these statements Control will move from one block of the program to another block of program.
Ex: Return, Go to, Exit, continue etc.,
Functions:
Programs:
1st program: Addition of two number
Integer a,b,c;
A=10;
B=20;
C=add(a,b);
System.debug(‘the sum is ‘+ c);
//function definition
Integer wd(Integer x, Integer y) // function header
{
Integer z;
z=x-y;
return z;
} // function body
Integer dep(Integer x, Integer y)
{
Integer z;
z=x+y;
return z;
}
What is this?
It is a concept or It is Collection of Principles or it is one kind of Approach or it is a paradigm, These principles or concept was developed
by Mr. Grady Booch. So we can call him as Father of OOPs.
1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance
Whichever programming language incorporate these 4 principles, then those languages can be called as Object Oriented Programming
Languages(OOPL)
Languages
1.Encapsulation:
Binding of Programming Elements(PE) i.e Data and Instruction in a single unit. (OR)
Binding of STATE(DATA/PROPERTY) AND BEHAVIOR(FUNCTIONALITY) as single unit is known as
ENCAPSULATION. (DATA+FUNCTIONALITY).
Ex: Our Hands are helps us to Eat and Write, so hear Hand is a data and eat and write are the functionalities.
Syntax of Class:
Class <Class name>
{
Data Members; -- Features
Member Methods; -- Behaviors
}
Ex:
Class Student
{
Integer sno,tm;
String sname;
Decimal avg;
Total_Marks();
Avg_Marks();
}
.
Member Methods: It is of 4 types.
1. Create 2.Input 3. Process 4. Output.
Every member method gives some service to data members. If any member method does not give any service to data members, then
there is no point of writing the member method with in the class.
Object: It is a real world entity, means what we can see and what we can touch, feel is known as Object such as, Fan, Chair etc.,
Every object has some STATE and BEHAVIOUR ,State means Properties (data) and Behavior means Functionalities (methods).
For ex Take a Class called HUMAN From Human class we can derive two objects i.e MEN and WOMEN.
MEN properties like Name, Height, Weight, Color etc., Behavior like eat(),walk(),Write(), Read() etc.,
So same kind of properties and behavior for Woman also but there are some different functionalities between MEN and WOMEN i.e like
MEN cannot give the birth to a child but where are WOMEN can.
Another example:
Every MEN and WOMEN have 2 legs, 2 hands, 2 eyes,2 ears,1 nose, 1 mouth this is common parts for both MEN and WOMEN some of the
parts of the will differ from MEN and WOMEN. This is property differences.
Definition of an Object:
1. It is an instance of a Class
2. It is a real world existence of class
3. It is a variable of type class
How to create an object:
Dataype name;
Classname objectname = new classname();
1 2 3 4
Here
It means only showing the required things to the outside world so that we can hide the inner details. Levels of Hiding the Data and
Methods which are Encapsulated.
Syntax:
Abstraction Data member;
Abstraction Member Method();
Example:
Class Student
{
Private Integer sno,tm;
Private String sname;
Private Decimal avg;
Public Total_Marks();
Public Avg_Marks();
}
3) INHERITANCE: Reusing the Data and Functionality in one Encapsulation for another Encapsulation.
Example:
Class Human
{
// Data Members
String Name, Color;
Private Integer Age, ,Height, Weight;
// Member methods
Public Walk();
Public Talk();
Public Sleep();
}
We can derive two sub classes i.e., Male Class and Female Class and every Male and Female Class.
Have same kind of data and method so that we no need to declare once again we can directly inherit from Human Class into
Male and Female class. This is called Inheritance.
For ex: Restaurant, Functions, we can implement Polymorphism using following ways.
1. Method OverLoading.
2. Method Overriding : Generally we are walking in the direction of our face, but if somebody asking to walk backward
direction we can walk, but it is in different direction. So, When we change the mechanism of the function is called
overriding.
3. Operator OverLoading
4. Constructor Overloading
There are 3 places we can write the code, out of which 2 are cloud based and 1 are desktop based
Cloud based—within organization
1st way:
Setup builddevelopAppex Classes new button
2nd way:
Goto user nameDeveloper console filenew->apex class
Desktop
Eclipse it is an IDE (integrated development environment), it is a tool which gives 5 things
i.e Editor, Linker, compiler, library, console(takes input and gives output) , here programmer can
write the program in a single Environment.
So, we can also write our Apex programs in Eclipse tool but we need to add some plug in like
Force.com IDE it is the combination of Eclipse+force.com plug in
Programs:
Business Class:
}
}
Test Class:
@isTest
public class MyclassTest {
public static testMethod void pain() {
MyClass obj= new MyClass();
obj.input(10,20);
obj.output();
}
}
//2. write an apex code input two number and find its sum and print it.
Business Class:
// process
Public void process()
{
Result = num1 + num2;
}
// output
public void output()
{
System.debug('the sum is ' + result);
}
}
3nd program: Input Student details and calculate total marks and average marks
Business Class:
}
}
Test Class:
@isTest
public class studentClassTest {
public static testMethod void main()
{
studentClass obj = new studentClass(); // calling point of constructor
// check the state of the values of the object
obj.setValues(90,90,90); // calling point
obj.getValues(); // calling point
}
}
Program 4: input employee details and calculate gross salary and net salary
Business Class:
}
public void getVal()
{
System.debug('Employee Id ' + empno);
System.debug('Employee Name ' + ename);
System.debug('Employee Gross Salary' + gross);
System.debug('Employee Net Salary' + net_sal);
}
}
Test Class:
@isTest
public class empClassTest {
public static testMethod void main(){
empClass obj = new empClass();
obj.setVal(15000,5000,2000,1000,500);
obj.getVal();
}
}
Business Class:
Test Class:
@isTest
public class ifCalssTest {
public static testMethod void main()
{
ifClass obj = new ifClass();
obj.setVal(10,10);
}
}
Business Class:
}
public void setValues(Integer no, String name, Integer bal) // parameterized constructor
{
ac_no=no;
ach_name=name;
ac_bal=bal;
Test Class
@isTest
public class bankAccountTest {
public static testMethod void main()
{
bankAccount bank1 = new bankAccount();
bank1.getValues();
bank1.setValues(101,'Raj',10000);
bank1.getValues();
bank1.deposit(15000);
bank1.checkBalance();
bank1.withdraw(5000);
bank1.checkBalance();
}
}
Business Class
public class rectangleClass{
// data members
Integer length;
Integer breadth;
//create
public rectangleClass() // default constructor
{
Length=0;
Breadth=0;
}
public rectangleClass(Integer len, Integer bred)
{
length=len;
breadth=bred;
}
// input
Public void setValues(integer len,integer bred)
{
length=len;
breadth=bred;
}
//action or process
Public integer calcArea( )
{
Integer area;
area= length*breadth;
return area;
}
public integer calcPerimeter()
{
Integer perimeter;
perimeter=2*(length+breadth);
return perimeter;
}
}
Test Class
@isTest
public class rectangleClassTest{
public static testMethod void main()
{
// area of board calculation
rectangleClass board = new rectangleClass();
board.setValues(10,20);
integer ar_b=board.calcArea();
System.debug('Area of board ' + ar_b);
}
// input
Public void setValues(integer len,integer bred)
{
length=len;
breadth=bred;
}
//action or process
Public integer calcArea( )
{
Integer area;
area= length*breadth;
return area;
}
public integer calcPerimeter()
{
Integer perimeter;
perimeter=2*(length+breadth);
return perimeter;
}
public void getValues()
{
System.debug('The length is ' + length);
System.debug('The width is ' + breadth);
}
}
Test Class:
@isTest
public class rectangleClassTest{
public static testMethod void main()
{
RectangleClass box = new RectangleClass(12,18);
box.getValues();
}
}
// member method
// create
public EvenorOdd()
{
num1=0;
}
// input
public void setValues( integer x)
{
num1=x;
}
// process
public integer EO()
{
if(math.mod(num1,2)==0)
return 0;
else
return 1;
}
Test Class:
@isTest
public class EvenorOddTest {
public static testmethod void main()
{
integer m1=0;
EvenorOdd obj= new EvenorOdd();
obj.setValues(10001);
m1=obj.eo();
if(m1==0)
system.debug('the given number is even');
else
system.debug('the given number is odd');
}
}
// member method
// create
public POorNEG()
{
num1=0;
}
// input
public void setValues( integer x)
{
num1=x;
}
// process
public integer PN()
{
if(num1>0)
return 1;
else
if(num1==0)
return 0;
else
return -1;
}
Test Class:
@isTest
public class POorNEGTest {
public static testmethod void main()
{
integer m1=0;
POorNEG obj= new POorNEG();
obj.setValues(-10001);
m1=obj.PN();
if(m1==1)
system.debug('the given number is Postive');
else
if(m1==0)
system.debug('the given number is nuetral');
else
system.debug('the given number is negative');
}
}
Program 10: Student Pass or Fail Test
Business Class:
public class StudentPassOrFailClass {
String name;
integer id;
integer []marks;
public void acceptDetails(String name,integer id)
{
this.name=name;
this.id=id;
}
public void acceptMarks(integer []marks)
{
this.marks=marks;
}
public integer calculateTotalMarksAndDisplay()
{
integer total=0;
System.debug('MarksList:');
for(integer i=0;i<5;i++)
{
System.debug('Subject '+(i+1)+'='+marks[i]);
total=total+marks[i];
}
return total;
}
public decimal calculatePercentage()
{
integer total=calculateTotalMarksAndDisplay();
System.debug('Total Marks ='+total);
decimal per=total/5;
return per;
}
return status;
}
public void displaystudentReportCard()
{ System.debug('Id:'+id);
System.debug('Name:'+name);
decimal per=calculatePercentage();
if(checkPassFail()){
System.debug('Percentage:'+per);
if(per>=70)
System.debug('Grade:A+ Destinction');
else if(per>=50 &&per<70)
System.debug('Grade:A First Class');
else if(per>=40 && per<50)
System.debug('Grade:B Second Class');
else
System.debug('Grade:c Third Class');
}
else
System.debug('Result:Fail');
}
Test Class:
@isTest
public class StudentPassOrFailClassTest {
public static testmethod void studentDetails()
{
StudentPassOrFailClass info = new StudentPassOrFailClass();
info.acceptDetails('samreen', 402);
integer []marks=new integer[]{100,90,90,90,100};
info.acceptMarks(marks);
info.displaystudentReportCard();
}
}
Business Class:
// member methods
// 1. create
public bankAccount() // default constructor
{
System.Debug('I am default Constructor');
ac_no=0;
ach_name='no name';
ac_bal=0;
count++;
}
/* public bankAccount(Integer no, String name, Integer bal) // parameterized constructor
{
System.Debug('I am in parameterized constructor');
ac_no=no;
ach_name=name;
ac_bal=bal;
} */
public void setValues(Integer no, String name, Integer bal)
{
ac_no=no;
ach_name=name;
ac_bal=bal;
Test Class:
@isTest
public class bankAccountTest {
public static testMethod void main()
{
BankAccount bank1 = new BankAccount();
bank1.getValues();
bank1.setValues(101,'Raj',10000);
bank1.getValues();
bank1.deposit(15000);
bank1.checkBalance();
bank1.withdraw(5000);
bank1.checkBalance();
BankAccount.getcount();
bankAccount bank2 = new bankAccount();
bank2.getValues();
bank2.setValues(102,'Ram',20000);
bank2.getValues();
bank2.deposit(5000);
bank2.checkBalance();
bank2.withdraw(10000);
bank2.checkBalance();
BankAccount.getcount();
}
}
Test Class:
@isTest
public class MethodOverLoadingTest {
public static testMethod void main()
{
MethodOverLoading obj = new MethodOverLoading();
Integer first =obj.setValues(10,20);
System.debug('the sum of two numbers is' + first);
integer second=obj.setValues(10,20,30);
System.debug('the sum of three numbers is' + second);
Integer third=obj.setValues(10,20,30,40);
System.debug('the sum of four numbers is' + third);
}
}
Exception Handling:
OBJECTIVES:
In this is Chapter you will learn
Learn what an Exception is.
What is an Error.
Types of Errors.
Learning how to handle Exceptions in a Program.
Learning Exception handling through Try/Catch.
High level language(source code)----Intermediate code---Machine Level Language – run—output
SYNTACTICAL ERRORS—if the programmer do not follow the language rules and regulations then it will display syntactical errors.
These errors will raise at the time converting program from HLL to IC.
If high level language code successfully converted into intermediate code then it fails to convert into Machine level language code then it
will display ‘SEMANTICAL ERRORS’.
num1,num2,result integer;
12+16==82
if the program successfully converts from HLL – IC –MLL – RUN – Output wrong – BUG.
DEFINITION:
“It is a Mechanism of designing the code which enables the processing of the Program to continue inspite of the Occurrence of the Run-
Time Error”
What is an Error?
An Error is a condition where the processing of the program gets terminated automatically.
Types of Errors:
There are 2 types of Error.
1. Translation Error:
Here the Error occurs in the translation phase of the program. Translation Error is of two types.
i. Syntax error
ii. Symatic error.
Syntax Error and symantic error are the Rules to create the statements. The only one way to overcome these errors is to change the
source code.
2. Execution Error.
This Error occurs at the execution phase of the program, these are known as runtime error or Exception.
Exception Handling can be achieved through two keywords.
1. Try
2. Catch.
TYPES:
Built-In Exceptions and Common Methods:
Dml Exception:
Any problem with a DML statement, such as an insert statement missing a required field on a record.
This example makes use of Dml Exception. The insert DML statement in this example causes a Dml Exception because it’s inserting a
merchandise item without setting any of its required fields. This exception is caught in the catch block and the exception message is
written to the debug log using the System. Debug statement.
Exception Handling
Convert system defined error msgs into User Defined error msgs.
We can handle exceptions by using Try and Catch methods.
1. Null Pointer Exception: this exception will raise when the user trying to perform operations o n null values.
@isTest
public class nullpointer {
public static testmethod void main()
{
integer num1,num2,result;
try{
result = num1+num2;
}
catch(exception c)
{
system.debug('Sorry we cannot perform addition operation on null values');
}
num1=10;
num2=20;
result = num1+num2;
system.debug('the result is ' + result);
}
2. Arithmatic Exception: This exception will raise when the user trying to dividing the number by zero.
ARITHMATIC EXCEPTION:
@isTest
Public class arithMatic{
Public static testmethod void main()
{
Integer num1,num2,result;
Num1=10;
Num2=0;
Try{
Result= num1/num2;
}
Catch{
System.debug(‘sorry we cannot divide the number by zero’);
}
}
3. Array out of bound Exception: This exception will raise when the user trying to fetch element out of the array size.
Assertions: There is close relation between Exception and Handling and Assertion, ie.
In exception handling if any problem occurs then control takes another path and executes the rest of the statements but where as in
assertion if any problem get occurs then the control completely comes of the program.
1. System.assert()
2. System.assertEquals()
3. System.assertNotEquals()
@isTest
integer num1,num2,result;
num1=10;
num2=10;
/* if condition is true, then it will executes the statements,if it is false then error
result=num1/num2;
}
}
Annotation:
1. Annotations are special words in a language and always begins with “@” symbol.
2. These words convey a special meaning to the server in order to treat a resource differently.
3. Apex provided many annotations such as @isTes,@future,@depricated etc,
3 @readOnly Defines methods that can perform queries unrestricted by the number of returned rows limit for a
request.
6 @restResource Identifies a class that is available as a REST resource. The class must be global. The urlMapping
parameter is your
resource’s name and is relative to https://instance.salesforce.com/services/apexrest/
Syntax:
@restResource(urlMapping= ‘/Widget/*’)
global with sharing class MyResource() {
}
Main()
------
--------
----
Abc();
Abc()
--
--
Pqr();
--
--
Pqr()
--
--
SecondMethod();
@future
Test class:
@isTest
public class AnnotationTest {
obj.FirstMethod();
SOQL: It stands for Salesforce Object Query Langauge, which Is used to communicate with the database.
Select : Using this command we can fetch the data from sobject.
Using this command we can fetch all the records in the subject and also we can fetch specific records in the sobject.(using Where
Clause).
Syntax:
Ex:
Syntax:
2. Selection: Retrieve the data based on some condition using where clause.
Ex:
Queries:
Order by Clause:
This clause is used to arrange the records in a proper order i.e either ascending or descending order
By default order by clause will arrange the records in ascending order , if we want to arrange the records
If we apply the order by clause on character column then it will arrange the records in alphabetical order.
We can apply the order by clause on more than one column in the same sobject.
Syntax:
Ex:
functions
group by
cube
rollup
having
limit