Saleforce Coding
Saleforce Coding
Programming Language:
Data Types
Operators
Constructors
Collections
Debugging
Opp’s fitment
Data Retrieval Query
Data Manipulations
User interface capabilities
Integration Capability
Security
What is Apex?
Apex is strongly types object-oriented programming language that allows developers to
execute the flow & Transaction control statements on salesforce servers in conjunctions call
to the API.
System.debug('Date'+date.newInstance(2022,1,10));
System.debug(Datetime.now());
datetime Dt = datetime.now();
System.debug(Dt);
Operators:
Collections:
Collection are capable to store multiple values.
Map: In Map using key value we can find the exact element.
Map is a collection of Key -Value pairs.
Key is always a unique having a value associated.
Values Can be duplicate.
Apex uses a Hash structure to all maps.
Adding a map with an existing key overrides the Existing entry with new.
Map Key & values can contains any collection & can contain nested collections.
Key & Values can be of any data type:
(Primitive type, Collections, sObjects
User defined types & Built in types).
Ex: Map<String, String > Myst = new Map <String, String >();
Map<Integer, String > Myst = new Map < Integer, String >();
Map<Id, Account > Myst = new Map < Id, Account >();
Constructor:
1. Constructor name is same like class name.
2. To assign default value for the class members/Variable.
3. Constructor will not contain any return type.
4. Constructor I’ll execute whenever object call.
Access Modifiers:
Public: Inside the org
Private: Inside the apex class
Protected: Inside the apex class & its Child class.
Global: One org to another org {Integration}.
methods & classes all should be global
Test Class:
1. Testing the class with sample test data.
2. @isTest annotation to create test class.
3. If you want to deploy the code from sandbox to production 75% code is coverage
required.
4. Sandbox to sandbox to code coverage is not required.
5. By default, test class id synchronous, we have to wait until code execution completed in
synchronous.
6. By Using Asynchronous we don’t need to wait until code run, it will run the backend &
show the output.
Syntax: @isTest
Batch Apex(Interface):
1. If you want execute some actions asynchronously in feature method with large number of
records, we can go for batch apex.
2. Batch Apex is an Interface (Database.Batchable<Sobject>). Start, Execute & Finish
Methods. In interface we should use all 3 methods. In interface we have only method
signature, no development implements.
Database.BatchableContext: It’s a Object, We can get batch job ID or we can tract the
status.
3. If you want to work on larger number of records, we can use batch apex. (50 million)
By using DML we can insert 10000,
Import Wizard 50,000 records we can insert.
Data loader 5 million record we can insert
4. Start Method: By using start method we can fetch record using two return types.
Database.querylocator : 50M
Iterable: 50k records (Complex logics)
5. Execute Method: It will divide the records into small chants.
Each chants have their own governor limits.
Return type of execute method is void.
6. Finish Method: To send the Notification whether job succussed or not.
If we want one more batch apex, we use finish method.
By default Batch apex is a ‘Stateless’ (No connection between one to one method).
To get connection we have to make ‘State full’ Database.Statefull
Asynchronous Apex:
Asynchronous processing executes a task in the background, and only when sufficient resources
become available.
Asynchronous Apex:
Feature
Batch apex
Schedule apex
Queueable apex
If you want to call any apex methods in process builders or flows we should use invocable
methods.
*********
What is feature method:
Any asynchronous operation that we are going to run it I’ll add to ‘Queue’. From queue it I’ll
execute.
Once you execute any asynchronous job That is executed it will registered with
“AsyncApexJob” Object Job id is created, Here we can check Status of Job, Pending Wating,
How many batches.
Once this “AsyncApexJob” Job is registered this Job will be added to queue.
Due to Inconsistency for apex Jobs, we don’t Pass the ‘Sobject’ as parameter.
Any long running operation are there in Transaction They will taking more time, Due to
which the transaction may delay. To avoid this delay in transaction people are going to
@feature method. Whichever the statements are taking longer time run those statements
independently from rest of transaction.
DrawBack of feature method:
1. It I’ll not take Sobject as parameter.
2. It I’ll registered in Async Apex Job, It I’ll Create a Job Id, but it won’t return JobId.
@Feature
Public Static Void MethodName(){
}
3. With in the feature method we cannot call another feature method.
feature method:
4. A benefit of using future methods is that some governor limits are higher, such
as SOQL query limits and heap size limits.
5. Feature methods must be static & return type void.
6. Feature method I’ll not take Sobject as parameter, only primitives datatypes it
I’ll accept.
6. Feature methods I’ll not accept Sobjects as parameters (Instead of that we use
ID’s).
7. We cannot call feature method into a feature method.
8. You can also use future methods to isolate DML operations on different
sObject types to prevent the mixed DML error.
9. Long time running operations Bulk DML Operations, & Web services calls.
10. Feature I’ll not return Id of the Job.
11. With In a transaction 50 feature methods Run.
12 We call a feature method with Classname.Methodname();
Mixed DML:
Here also we are going to use @feature Method.
In a single method performing DMLs on setup & non setup together I’ll get mixed
DML Error. We resolve this issue running separately By @feature.
If we run separately using @feature I’ll not get Error, Run Successfully.
Setup Objects: Object are which if you make a DML they I’ll impact on permission
of the users on Database they are call setup object.(User, User Role, Profiles,
Permission set, Page layout, work flow, Record types, Group, Group Member,
Object permission, field permission, territory)
Any DMLs Operations performed on these objects will impact permission of other
people on data base which is called setup objects.
Non setup objects: Normal standard+ Custom objects (Account, Case, contacts).
Feature cannot be called into a feature.
Syntax:
Public class Queaclass Implements Queueable(){
public Void Execute(QueueableContext BC){
ClassName cs = new ClassName();
Id JobId = System.enqueueJob(cs);
}
}
Scheduled Apex:
If you want to schedule a apex class you should to implements the ‘schedulable’
interface.
Any class implements a schedulable then we have to go for execute method.
why because Login we define in execute method.
Once Job is scheduled, Async apex Job create a job details. It won’t show any
scheduled timings in that.
& CronTrigger also create, it I’ll show the scheduled timings.
String CronExp = ‘0, 10, 7, 3 ,?’
Id JobId=System.Schedule(‘Nameof the job’,’Cron expression’,’Object of class’)
Id JobId=System.Schedule(‘Myjob’, CronExp, Account)
100 Schedule apex we can call in a transaction.
We can call Feature method in schedule apex Yes.
We can call web services in schedule apex Yes(But we don’t call it directly, we
have call by feature method)
CronExpresion Gives the information When was the Last Scheduled, Next
Scheduled.
Scheduled success or Failed we can get from Async apex Job.
‘ * ’ : every Month
‘ ? ‘ : not sure
‘ w ’ : Working Day
‘ L ’ : Last Working day
‘ # ’ : 2#6 -- Second Friday
Batch Apex:
why we go for batch apex:
When we working on large set of data, there is a possibility of governing limits
issue to resolve this issue we go for Bath apex.
Breaking the large transaction into number of child Batches running them
independently, without effecting to governing limits.
In Batch apex every child Batches separate by set of Governing limits.
If you want to run any apex class as batch apex, class as to implements
Database.Batchable<sObject> it’s a interface global interface. If you implements
Database.Batchable interface It has to implements ‘Start’, ‘Execute’, ’Finish’.
It has only two methods, get current job running ‘getJobId()’, getChildJobId()
Start Method:
Start method I’ll fetch the data break them in number of batches.
return type DataBase.queryLocator I’ll gives you 50M records.
This “QueryLocator” Gives you cursor to move. Because this cursor able to move
forward & backword.
Execute Method:
When a batch apex wants to implements the web service calls. Then we have to
implements the ‘database.AllowCallouts’
Methods:
MoveAfterJob(JobId)
MoveBeforeJob(JobId)
MoveJobToEnd(JobId)
MoveJobTo Front(JobId)
DMLs:
DMLs are two type 1. Atomic 2. Non-Atomic
Atomic Means perform all, Perform None,(If any record is fail whole execution will
fail).
Non Atomic : Non Atomic Means One record fail in execution only that records
will fail, remaining records execute successfully.
Database.SaveResult result = Database.Insert(sObject[], False);
Database.SaveResult sr = Database.Insert(accLst,False);
List<Database.SaveResult> sr = Database.Insert(accLst,False);
For(SaveResult fSr : sr){
if(fSr.itSuccess()){
System.debug(‘Id:’+fSr.getId);
}
else{
Database.error[] errors = sr.getErrors();
for(Database.Error er : errors ){
System.debug(er.getFields);
System.debug(er.getMessage);
}
}
SOQL Queries:
Static query:
Dynamic query:
Cursor:
map:
setHtmlBody(htmlBody)
setSubject(setSubject)
setToAddress(toAddress)
setBccAddress(BccAddress)
setccAddress(ccAddress)
setTemplateId(templateId)
setPlainTextBody(“Hi”)
messaging.sendEmail();
Recursive Trigger:
Calling same Trigger again & again.
Use case: Whenever account is inserted Child account also inserted.
Static method:
Static Variable will maintains the state across the transaction.
We can call the static methods & variable in other class with
‘ClassName.method’
We can give static Keyword to Methods & variables.
aggregate Functions:
SELECT Count(Id) FROM Opportunity
SELECT Count(Id), Sum(Amount) FROM Opportunity
SELECT Count(Id), Sum(Amount), Max(Amount) FROM Opportunity
SELECT Count(Id), Sum(Amount), Max(Amount),Avg(Amount),Min(Amount) FROM
Opportunity
Alias Name we use to call
AggregateResult agr = [SELECT Count(Id)cnt, Sum(Amount)sm,
Max(Amount)mx,Avg(Amount)ag,Min(Amount)mn FROM Opportunity]
System.debug(‘----Count----'+agr.get(‘cnt’));
Test Class:
Any apex code you want to deploy from one environment to another
environment need to be tested & they should have a test coverage 75% then
only they can be deployed.
Test Classes is defined with @isTest annotation.
Test Classes will have test Methods with @isTest Annotation or Testmethod.
Making Private is good practice of writing test classes.
Test Class will run synchronously.
‘TestMethod’
Method Should be ’static’.
Return Type Always ‘Void’
Methods should not contain any ‘Parameters’
Static Void Callmetest(){
}
If You require a sample data for testing multiple functionality instead of
recreating multiple times again & again I can create a sample data as test
Factory I can use it where ever I use.
@testSetUp Annotation is used to Create a sample test data For Testing the
Update,Delete,Undelete DML.
Report:
Tabular Report: Simple report with grand Total.
Matrix Report: Group By with rows & Columns
Summary Report: Group By With rows
Joined report: You can display multiple object report types in single report. We
can add block in Joined report which refers to another object.
Page reference:
Page reference is class.
Using page reference we can navigate to another url or VF page.
Data Loader:
Import Wizard:
1. Import Wizard Salesforce Internal UI Tool.
2. Using This Tool, we can upload up to 50k Records.
3. It will Support Few Standard Objects & all Custom Objects
Standard Objects: Account, Contact, Lead, Solution, Campaign Members
4. Using Import Wizard Insert, Update, Upsert.
5. We have to Upload in CSV Format.
6. If any Mandatory field missing that record will fail. Remaining execute.
Data Loader:
1. It’s also Salesforce tool we can import & Export data.
2. We need to install data Loader & JDK 11…
3. Data Loader support 5M Records to load.
4. It will support all Standard & all Custom Object.
5. Using Data Loader Insert, Update, Upsert, Delete, Hard Delete.
6. We have to Upload in CSV Format.
7. If any uploads on daily so we can save the .sdl file.
Custom MetaData :
Custom Metadata same like a custom settings, Only one change that we can
fetch data using SOQL Query.
advantage:
When we deploy the Custom Metadata including Template & fields Data also
deploy.