0% found this document useful (0 votes)
16 views15 pages

Saleforce Coding

The document provides an overview of Salesforce coding, focusing on the Apex programming language and its features, including data types, collections, and operators. It explains the use of Apex for custom application development, complex validations, and integration with external systems, along with details on asynchronous and synchronous processing, batch processing, and the use of future methods. Additionally, it covers the structure of classes, constructors, access modifiers, and the importance of testing and deployment in Salesforce development.

Uploaded by

vikramyarnagi222
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)
16 views15 pages

Saleforce Coding

The document provides an overview of Salesforce coding, focusing on the Apex programming language and its features, including data types, collections, and operators. It explains the use of Apex for custom application development, complex validations, and integration with external systems, along with details on asynchronous and synchronous processing, batch processing, and the use of future methods. Additionally, it covers the structure of classes, constructors, access modifiers, and the importance of testing and deployment in Salesforce development.

Uploaded by

vikramyarnagi222
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/ 15

Salesforce coding:

Why Coding in salesforce?


1. Customized applications.
2. Custom logics.
3. To get interact with external systems.
4. Complex Validations.

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.

Primitive data types:


Example
Blob
Boolean
Time
Date
Datetime
Decimal 27.0
Double
ID
Integer 27
Long
Object
String ‘Hello World’

Boolean isActive = True;


System.debug(‘Boolean’+ isActive);

System.debug('Date'+date.newInstance(2022,1,10));
System.debug(Datetime.now());

datetime Dt = datetime.now();
System.debug(Dt);

Blob Bb = ‘Hello world’;


System.debug(‘Blob’+ Blob.ofValue(Bb));

Id RecordId = [Select Id From Account Limit 1] [0].Id;


System.debug(‘RecordID’+ RecordId);

Operators:

Collections:
Collection are capable to store multiple values.

List: Follow the order of the element.


List allows the duplicate values.
Each element list has index for identification imp.
Index position always Zero.
list can be nested & even multidimensional.
Elements can any data type:
(Primitive type, Collections, sObjects
User defined types & Built in types).
Ex: List<String> Myst = new List<String>();
List<Account> Myst = new List<Account>();
List<Integer> Myst = new List<Integer>();
List<Account> Myst= [SELECT id, Name FROM Account];
add(element): addAll(collection): get(index): set(index, element):
remove(element): remove(index): clear(): isEmpty(): size():

Set: Not follow the order of the element.


Set not allows the duplicate values.
Set contain collection that can be nested within one another.
Elements can any data type:
(Primitive type, Collections, sObjects
User defined types & Built in types).
Ex: Set<String> Myst = new Set <String>();
Set <Id> Myst = new Set <Id>();
Set <Integer> Myst = new Set <Integer>();

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 >();

List<Account> acclsit = [SELECT id, Name FROM Account];-


- Map<Id, Account>IdToAccountMap = New Map< Id, Account > (acclsit);

Map<Account,List<Contact>>AccToConMap= new Map<Account,List<Contact>>();


put(key, value): get(key): containsKey(key): ContainsValue(value):
remove(key): keySet(): values(): isEmpty(): size():

When I use apex code:


When should I not use apex code:

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

Schedule apex: We can execute some code in feature.


Interface : Schedulable
Method: Execute
Synchronous Apex:
Synchronous processing executes a task in a single transaction, and doesn't wait for available
resources.

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:

1. A future method runs in the background, asynchronously.


2. You can call a future method for executing long-running operations, such as
callouts to external Web services or any operation run in its own thread, on its
own time.

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();

Feature method Use cases:


1. Handle mixed DML operations.
2. To invoke asynchronous web services from trigger.
3. To invoke asynchronous web services from schedule apex.
4. To Handle bulk DML operation.

Works Around feature method usecase.


1. When we have a requirement to pass sobjec as parameter to feature method.
How you will?
ans: a. Pass recordId instead of record.
b. serialize the subject as string using JSON\XML & pass string as
parameter to feature method.

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.

Queueable apex class(Asynchronous):


I want to run asynchronously but I want to run them like Order. So will go with
Queueable.
If class is implements the ‘’queueable’ interface, it has to define a method called
Execute method(QueueableContext ac)
We can call queueable class in another queueable class with “System.enqueJob”
method.
Id JobId = System.enqueueJob()
queueable will return Id of the Job.
Queueable is support S object.
We can call a feature method in queueable class.

Advantages of Queueable apex:

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

Ex: Job at 5 AM on 15th March


Sec : Min : Hr : day : Month : day week :
00 : 00 : 5 : 15 : 3 : ? :

Job at 5 :30 PM on 10, 15 20 of every month


Sec : Min : Hr : day : Month : day week :
00 : 30 : 5 : 10,15,20 :
* : ? :

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.

Gobal Database.QueryLocator start (Database.BatchableContext BC){


String query = ‘Select Id,Name FROM Opportunity’;
return Database.getQueryLoacator(query);
}

This “QueryLocator” Gives you cursor to move. Because this cursor able to move
forward & backword.
Execute Method:

Global Void Execute(Database.BatchableContext BC, List<Opportunity> Scope){


for(Opportunity Op : Scope){
Op.Stage = ‘Hot’;
}
Update Scope;
}
Finish Method
To get Soql on Job Id
AsyncApexJob job = [SELECT Id, Status, JobType FROM AsyncApexJob WHERE Id
=:bc.getJobId()];
To Execcution of apex we use Database.executeBatch(be)
Database.executeBatch(be) By default it take 200 size batch it will execute.
Database.executeBatch(be,1000);
Max size of the records for one batch is ‘2000’;
Statefull:
It is to maintain state of the data.
When a class implements a database.Stateful interface State of a data
exchanged between execute batch methods for non-static variable.

When a batch apex wants to implements the web service calls. Then we have to
implements the ‘database.AllowCallouts’

If Start method Fail entire Operation fails.


If Any one of Batch Execution fail Only that Batch Execution fail.
If Finish method fail Only finish will fail start & execute method will run
successfully.
Flexqueue:
If I Run a Database.executeBatch(Be). Job is added to flex queue. In Flex queue
Job is holding state.
In Batch apex we have a Flex queue concept: 100 Jobs in Flex queue it will take.
From Flex queue it will move to Queue when require resource is available.
Only 5 Jobs can run at a time in queue.
It will It I’ll control the Order of execution before going to Queue execution.
Here we can decised order of execution.

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 result = Database.Insert(sObject[], True);


If you use true the it will behave like a normal DML
Ex: Non Atomic:

Account a1 = new Account();


a1.Name = ‘Vikram’;
a1.Phone = ‘98765’;

Account a2 = new Account( Phone = ‘5678’);


List<Account> accLst = new List<Account>{a1, a2};

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);
}
}

Difference between DML & database DML


In DML Partial success rate will not allow.
Database DML Will allow the partial success rate.
Save Point:
After The save point what are the changes you made cancel all of them, show
me the data which is available data at time of save point.
Savepoint sp = Database.setSavcepoint();
Database.rollback(sp);

SOQL Queries:
Static query:
Dynamic query:
Cursor:
map:

Outbound & Inbound email


To :100
CC:25
Bcc:25
messaging.singleEmailMessage meg = new messaging.singleEmailMessage();

setHtmlBody(htmlBody)
setSubject(setSubject)
setToAddress(toAddress)
setBccAddress(BccAddress)
setccAddress(ccAddress)
setTemplateId(templateId)
setPlainTextBody(“Hi”)

messaging.sendEmail();

Salesforce Implementing a concept called multitenant Architecture. To avoid


Dominant in particular application in the cloud they are implementing
Multitenant architecture. To Implements this architecture Given some Governor
limits.
Total DML are 150
Total DML retuned are 10000
Total SOQL are 100
Total SOQL retuned are 50000
Total Number of webservice are100
Total Number of flex queue are 100
Roll Up Summary :
In Roll Up summary we should go for ‘After Events’. Why because record saved
then only count will change.

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’));

Group By This will get the records Based on picklist values.

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.

If Your testing any asynchronous(batch apex schedule, Feature, Quable) we have


to define test.startTest() method test.stopTest();
When I am testing any asynchronous operation there is a possibility of
encountering governor limits problem comes automaticaaly test.startTest()
method test.stopTest(); this will add extra set of governing limit & solve the
problem.

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.

Export: We can export only object record.


Export All: We can export only object record + Recyclin bin records also.

IQ: How to insert null values in data loader?


In Data Loader settings we should enable ‘insert null Values’.

IQ: Max batch size in Data loader?


10000.

IQ: If we enable Bulk API

What is Custom Setting ?


Custom settings are used to store frequently accessed data in the application cache, which avoids
repeated query execution to the database. Validation rules, flows, formula fields, Apex, and SOAP
API can use this data for further processing. So custom settings are like custom objects on which we
can create custom sets of data for any business use case. We can use the data without writing any
SOQL query.
OR
Custom setting is like a custom object, where we can store the data, perform the manipulation & we
can use it without writing any SOQL querys.

Types of Custom Setting:


1. Hierarchy Custom Settings
In Hierarchical custom setting data will be stored as per the user & as per the
profile.
If You want control execution of triggers & Validation then we go for hierarchical
custom setting.
2. List Custom Settings
Group Of records
Mostly custom setting we use in mapping purpose or control the bulk triggers.
Disadvantage:
When we deploy the Custom setting only Template, Fields will deploy, But data
will not deploy.
We have to recreate the same data again in deployed org.

getall() getInstance() getValues()

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.

You might also like