0% found this document useful (0 votes)
66 views42 pages

SHARE - Salesforce My Notes

Uploaded by

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

SHARE - Salesforce My Notes

Uploaded by

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

TOPIC Code

<template for:each ={carList} for:item="car">


FOR EACH <h1 key={car}> {car} </h1>
</template>

studentList=[
{id:123, name:"shubham", Age:15},
<template iterator:stu={studentList}> {id:124, name:"abhay", Age:16},
ITERATOR LOOP <div key={stu.value.id}> {id:125, name:"Adesh", Age:18},
<h3>{stu.value.name}</h3> <h4>{stu.value.Age}</h4> {id:126, name:"vaibhav", Age:25}
</div>
</template> ]

currentTarget event.currentarget.value (to get from where the event is fired if both event has same event Handler)

EVENT- BUBBLE Child TO Parent by Default behavior

Remains on the same Element


TARGET EVENT
event.stopPropogation();

CAPTURE EVENT targetElement.addEventlistner("click", e=>console.log(), true)

To create an event, use the CustomEvent() constructor.

The CustomEvent() constructor has one required parameter, which is a string indicating the event type.

CUSTOM EVENT new CustomEvent("eventName", }bubble:false,compose:false, details:NULL})

eventTarget.disptachEvent();

In LWC EventTarget is this

event.preventDefault();
const selectEvent = new CustomEvent('selection', {
CHILD TO PARENT
detail: event.target.name
});

showNotifyParentHandler(event) {
event.preventDefault();
const selectEvent = new CustomEvent('show', {
CHILD TO PARENT
bubbles: true
WITH BUBBLING
});
this.dispatchEvent(selectEvent);
}

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:


preventDefault
Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL

recordId @api recordId @api objectApiName

get userId import USER_ID from '@salesforce/user/ID;

get Object import ACCOUNT from '@salesforce/Schema/Account;

get Field import NAME from '@salesforce/Schema/Account.name;

import { getListInfosByName } from "lightning/uiListsApi";

@wire(getListui, {
uiListsApi
objectApiName:ACCOUNT,
listviewApiName:AllAccounts
}) wiredListView

import { getObjectInfo } from 'lightning/uiObjectInfoApi';


uiObjectInfoApi @wire(getObjectInfo, { objectApiName: '$objectApiName' })
objectInfo;

import { createRecord } from 'lightning/uiRecordApi';

const fields={};
fields[NAME_FIELD.fieldApiName]=this.accName;
fields[ANNUAL_REVENUE.fieldApiName]=this.accRev;
console.log(fields);
Create Record
let recordInput={apiName:ACCOUNT_OBJECT.objectApiName, fields}
createRecord(recordInput).then(result=>{
this.accName=''
console.log('Account created ID', JSON.stringify(result.id))
}).catch(error=>{
console.error(error)
})
TOPIC Code

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

this.dispatchEvent(new ShowToastEvent({
TOAST EVENT title 'Contact',
message 'Updated Successfully',
variant 'success'
}));

import { refreshApex } from '@salesforce/apex';

REFRESH APEX
refreshApex(this.wiredData);

import getApexData from '@salesforce/apex/apexControllerName.methodName';

apexMethodName({ paramName : this.paramValue })


.then(result => {
console.log('Result', result);
IMPERATIVE APEX })
.catch(error => {
console.error('Error', error);
});

@wire(apexMethodName, { paramName : '$paramName' })


wiredData({ error, data }) {
if (data) {
console.log('Data', data);
WIRE CALL
} else if (error) {
console.error('Error', error);
}
}

IMPORT COMMUNITY import communityId from '@salesforce/community/Id';


import communityPath from '@salesforce/community/basePath'

MPORT CUSTOM LABELimport labelName from '@salesforce/label/labelReference';

MESSAGE CHANNEL import channelName from '@salesforce/messageChannel/channelReference';

import { NavigationMixin } from 'lightning/navigation';

this[NavigationMixin.Navigate]({
type 'standard__navItemPage',
attributes {
apiName "The unique name of the CustomTab."
}
});

this[NavigationMixin.Navigate]({
type 'standard__component',
attributes {
componentName "c__component name"
}
});

NAVIGATION this[NavigationMixin.Navigate]({
type 'standard__objectPage',
attributes {
actionName "home, list, or new",
objectApiName "The API name of the standard or custom object. "
}
});

this[NavigationMixin.Navigate]({
type 'standard__recordPage',
attributes {
actionName "clone, edit, or view",
recordId "recordId",
objectApiName "The API name of the record’s object. Optional for lookups."
}
});

STATIC RESOURCES import resourceName from '@salesforce/resourceUrl/resourceReference';

SCHEMA import objectName from '@salesforce/schema/objectApiName';


import FIELD_NAME from '@salesforce/schema/object.fieldApiName';

USER import userId from '@salesforce/user/Id';


USER PERMISSION import hasViewSetup from '@salesforce/userPermission/ViewSetup';

<lightning-combobox name="Status" label="Status" value={selectedValue} placeholder="Select Progress"


COMBOBOX options={options} onchange={handleChange}></lightning-combobox>

import { LightningElement, track } from 'lwc';

export default class NameValidationLWC extends LightningElement {


@track name = '';
@track nameError = '';

handleNameChange(event) {
this.name = event.target.value;
} <template>
<lightning-input label="Name" value={name} onchange={handleNameChange}></lightning-input>
LWC VALIDATION validateName() { <lightning-button label="Validate" onclick={validateName}></lightning-button>
const namePattern = /^[A-Za-z ]+$/; // Allow only letters and spaces <div iftrue={nameError} class="error">{nameError}</div>
if (!namePattern.test(this.name)) { </template>
this.nameError = 'Name can only contain letters and spaces.';
} else {
this.nameError = '';
// Name is valid, you can perform further actions here
}
}
}

<template>
<lightning-input
label="Name"
type="text"
name="name"
value={name}
LWC VALIDATION required
pattern="[A-Za-z ]+"
message-when-pattern-mismatch="Name can only contain letters and spaces."
oninput={handleNameChange}>
</lightning-input>
</template>
TOPIC CODE

List<String> listname=new list<String>();


List<integer> listname=new list<integer>();
List<Account> listname=new list<account>();
List<Account> listname=[Select id , name from account];
List<String> my_list2= new List<String>{'Anjali','abhishek'};
String[] name= [];

Method in list
add(element);
add(index, listElement);
addall(fromlist);
LIST addall(from set);
equals(listsecond);
contains(listelements);
clone();
clear();
get(index);
indexof();
isEmpty();
remove();
sort();
size();
set(index,listelement);

Declaration-

Set<string> setname=new Set<String>();


Set<Integer> setname=new Set<Integer>();
Set<Account> setname=new Set<Account>();

Methods In set
add(setelements);
addall(list);
SET addall(set);
clear();
clone();
equals();
contains(single element);
containsall(compair with list);
size();
isempty();
remove(single set elment);
removeall();

map<key, value> mapname=new map<key, value>();


map<string, string> mapname=new map<string, string>();
map<string, integer> mapname=new map<string, integer>();
map<id, Account> mapname=new map<id, account>();
map<id, list<Account>> mapname=new map<id, list<account>>();
list <Account> acc=[select id, name from account ];
map<id, Account> mapname=new map<id, account>(acc);

Methods-

put(key,value);
MAP
putall(secondmap);
remove(key);
value();
size();
clear();
equals(second map);
clone();
get(key);
containskey(key);
isempty()
keyset()

DATE date.newInstance(2023, 4, 21);

global class BatchClass implements Database.Batchable<sObject> {

global Database.QueryLocator start(Database.BatchableContext bc){


return Database.getQueryLocator([select name,id from Student__c]);
}

global void execute(Database.BatchableContext bc, List<Student__c> stud){


}

global void finish(Database.batchableContext bc){}


BATCH CLASS

/*Invoking Btach Class


BatchClass bc= new BatchClass();
Id batchId= Database.executeBatch(bc, 10);
List<AsyncApexJob> job= [Select Id, Status, JobItemsProcessed,
TotalJobItems, NumberOfErrors
From AsyncApexJob where Id= batchId
LIMIT 1]
System.debug('from Window Batch id is '+ batchId + ' Job is' + job);;
*/

global with sharing class ScheduleBatchApex1 implements Schedulable {


global void execute( SchedulableContext sc){
BatchApex1 b= new BatchApex1();
SCHEDULE BATCH Database.executeBatch(b);
}

CUSTOM LABEL System.Label.Account_Test;

//Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll();


//List<Contact__C> sc= Contact__C.getall().values();

Contact__C mhc = Contact__C.getInstance('00e5g000005337c');


System.debug(mhc);
CUSTOM SETTINGS System.debug(mhc.name__c);

//get org defaults


Contact__C CS = Contact__C.getOrgDefaults();
system.debug(CS.name__c);

// Custom Metadata
List<Account_Metadata__mdt> cn= Account_Metadata__mdt.getAll().values();
CUSTOM System.debug(cn[0].masterlabel);
METADTA Map<String, Account_Metadata__mdt> mcs = Account_Metadata__mdt.getAll();
system.debug('keys are'+mcs.keyset());
system.debug('values are' +mcs.values());
public class Metadata {

public static void m(){


Map<String, TriggerSwtich__mdt> mdt = TriggerSwtich__mdt.getAll();
List<TriggerSwtich__mdt> mdt1= TriggerSwtich__mdt.getAll().values();
for(TriggerSwtich__mdt mmdt1){
if(m.DeveloperName=='Account_Switch'){
System.debug(m);
}
}
CUSTOM System.debug(mdt);
METADTA System.debug(mdt1);

Boolean triggerActive=mdt.get('Contact_Switch').Active__c;
System.debug(mdt.get('Contact_Switch'));

TriggerSwtich__mdt mc = TriggerSwtich__mdt.getInstance('Account_Switch');
System.debug('mc is '+mc);

}
}

for(String kmcs.keySet()){
PRINT MAP System.debug('keys are '+ k +' and values are '+ mcs.get(k));
}

Integer ag= [Select count() from Account];


System.debug('Account Count is '+ ag);

AggregateResult agc= [Select count(id) from Account];


System.debug('Account Count is '+ agc);

AggregateResult agc1= [Select count(id), sum(AnnualRevenue),count(Industry) from Account ];


System.debug('Account Count is '+ agc1);
AGGREGRATE
QUERY AggregateResult[] groupedResults= [SELECT AVG(Amount)aver, Count(Id)idd FROM Opportunity];
ORDER BY Object avgAmount = groupedResults[0].get('aver');
GROUP BY Object idOpp= groupedResults[0].get('idd');
System.debug('avg is '+ avgAmount + ' Count is '+ idOpp);

AggregateResult[] l=[Select count(Name), LeadSource from lead group by leadsource];


for(AggregateResult sl){
system.debug('values'+s);
}

Lead[] l1= [Select Name, leadSource from Lead ORDER BY Name ASC];
system.debug(l1);

Messaging.SingleEmailMessage mail= new Messaging.SingleEmailMessage();


String[] toAddress= new String[]{ '[email protected]'};
List<String> ccAddress= new List<String>();
ccAddress.add('[email protected]');

System.debug('toAddress'+ toAddress +'ccAddress ' + ccAddress);


mail.setToAddresses(toAddress);
APEX EMAIL mail.setCcAddresses(ccAddress);

mail.setReplyTo('[email protected]');
mail.setSenderDisplayName('Salesforce Support');
mail.setSubject('New Case Created' );
mail.setPlainTextBody('Your Case has been created.');

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Map<String,Object> gd= Schema.getGlobalDescribe();


system.debug(gd.get('Account'));
system.debug(gd.keyset());

Map<String,Schema.SobjectType> gd1= Schema.getGlobalDescribe();

Schema.SObjectType obj= Account.SobjectType;


system.debug(obj);

SCHEMA
Map<string, Schema.SObjectField> flMap= r.fields.getMap();
Set<string> keys= flMap.keyset();
system.debug('flmap '+flMap);

Id devRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Service Provider Contact').getRecordTypeId();


GET RECORDTYPE
system.debug(devRecordTypeId);
ID
system.debug('keys are' + keys);

Schema.DescribeSobjectResult r= Account.sobjectType.getDescribe();
ISCREATBLE
system.debug('r is creatable '+r.isCreateable());

User[] u= [Select id, name, alias, AccountId, ContactId from USER];


Profile[] p= [Select id, name, UserType from Profile];
PermissionSet[] ps= [Select id, name from PermissionSet];
USER PermissionSet[] ps1=[SELECT Name, PermissionsModifyAllData FROM PermissionSet
PROFILE WHERE PermissionsModifyAllData=true];
PermissionSet[] ps2= [SELECT Name, (SELECT AssigneeId FROM Assignments) FROM PermissionSet
WHERE PermissionsModifyAllData=true];
Group[] g= [Select id, DeveloperName, Type from Group Where Name='Enquiry' OR NAME='Noida'];

ORG DOMAIN System.debug(System.Url.getOrgDomainUrl());

USER INFO System.debug(UserInfo.getLastName()+' ' + UserInfo.getUserName());

In an after insert trigger and the records are read-only in that context as they have been written, but not committed, to the database.

FINAL EXCEPTION This kind of error occurs if you try to update lists/record which are/is read-only in the trigger execution. For example, trigger.new and trigger.old are both read-only lists and cannot be applied with a DML operation.

A field value of the object can be changed using trigger.new but only in case of before triggers. But in case of after triggers changing the values of the records in trigger.new context will throw an exception as "Record is read-only"
Integration
Headers
Authorization header Authorization header is used to send the client’s credentials to the server when the client is attempting to access a protected resource.
The User-Agent header identifies the web browser or client application that is making the request, which enables the server to tailor its response
to the client. For instance, if the User-Agent header indicates that the request is coming from the Chrome browser, the server may include CSS
User-Agent prefixes for CSS properties that are compatible with Chrome.
The Content-Type header identifies the media type of the content in the request body. For instance, Content-Type: application/json indicates that
Content-Type the request body contains JSON data. This information helps the server successfully interpret and process the payload.

Authentication

// Set the authorization header using basic authentication


String authHeader = 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password));
req.setHeader('Authorization', authHeader);

// Add other headers if necessary


Basic username + password req.setHeader('Content-Type', 'application/json');
// Set the API key in the header (the header name may vary depending on the API)
API KEY req.setHeader('Authorization', 'ApiKey ' + apiKey);

// Set the authorization header with the access token


AccessToken req.setHeader('Authorization', 'Bearer ' + accessToken);

POSTMAN
@RestResource(urlMapping='/ContactAPI/*')
YOUR OWN APEX REST API /services/apexrest/ContactAPI
OAUTH BASIC RESOURCE OWNER(USERNAME & PASSWORD)
Body of POST
username
append (passwordSecuiryToke) or Relax Ip from Connected pp Edit
password Policy
grant_type password
client_id
client_secret

Body of GET
header of the request, input the access token and token type. Key- Authorization | Value Bearer + access-token FOR JSON FOR XML
Content- Type application/json application/xml; charset= UTF-8
Accept application/json application/xml

OAuth Endpoints in Salesforce (getting access token)


Authorization https//login.salesforce.com/services/oauth2/authorize
Token Request https//login.salesforce.com/services/oauth2/token

Roles in OAuth 2.0:

Resource Owner: The user who owns the data and can grant access to it. For example, you are the resource
owner if you allow an app to access your Google Drive files.
Client: The third-party application (like a mobile app or website) that requests access to the resource owner's
data.
Resource Server: The server that hosts the resource owner's data (e.g., Google's servers for Google Drive).
Authorization Server: The server that issues access tokens after authenticating the resource owner and
authorizing the client (e.g., Google’s OAuth server).

Tokens:

Access Token: A credential the client uses to access the resource owner's data. This token is typically short-lived.
Refresh Token: A long-lived token that allows the client to obtain a new access token when the current one expires. This avoids needing to ask the user to log in again.

Named Credentials External credentials


A named credential is a secure reference to an external system's authentication details, such as a username, External credentials refer to any credentials (like API keys, OAuth tokens, or login information) that an application or system needs to authenticate
password, OAuth token, or certificate. Instead of hardcoding credentials directly into code, a named credential to an external service or third-party system. These credentials are typically obtained from the external system and used to authorize access or
allows developers or administrators to define the credentials in a secure and centralized manner. make requests.

// Set the endpoint URL using the Named Credential


req.setEndpoint('callout:' + namedCredentialName + '/api/resource');
principal the principal is the party whose identity is being verified using the credentials.

OAuth 2.0
2 step Process-
1- Hit URL in browser of Resource Owner ( Resource - QuickBooks & owner- I if I have access to Quickbooks A/
C), then it return Authorization code which is valid for 60 MIn
2- send Auth Code to get Access Tokeen
QUICKBOOK
Client Id ABbEN9XosnekoudOUUneDTZQLp6DJG2WzctEZR0rvHxKv6ORiP
Client Secret I4Z8ELclxMUtx47iByzNTXG99vb8cWxZbkGDmjvc
https//appcenter.intuit.com/connect/oauth2?
client_id=ABbEN9XosnekoudOUUneDTZQLp6DJG2WzctEZR0rvHxKv6OR
iP
&response_type=code&scope=com.intuit.quickbooks.accounting
&redirect_uri=https//www.salesforce.com
URL to get Auth Code &state=security_token
POST https//oauth.platform.intuit.com/oauth2/v1/tokens/bearer
HTTP/1.1
Accept application/json
Authorization Basic
UTM0dVBvRDIwanp2OUdxNXE1dmlMemppcTlwM1d2

NzRUdDNReGkwZVNTTDhFRWwxb0g6VEh0WEJlR3dheEtZSlVNaFhzeGx
ma1l
XaFg3ZlFlRzFtN2szTFRwbw==
Content-Type application/x-www-form-urlencoded
Host oauth.platform.intuit.com
Body grant_type=authorization_code&
code=L3114709614564VSU8JSEiPkXx1xhV8D9mv4xbv6sZJycibMUI&
Exchange the authorization code for access tokens redirect_uri=https//www.mydemoapp.com/oauth-redirect

GOOGLE API

631950255594-mncomd3ev7ka1q5oa9fkd9bdgitem5ur.apps.googleuse
ClientId (SF Calender)
rcontent.com
Client Secret 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
https//accounts.google.com/o/oauth2/v2/auth?
scope=https//www.googleapis.com/auth/calendar https//
www.googleapis.com/auth/calendar.events &
access_type=offline&
include_granted_scopes=true&
URL for Auth2.0 step 1 (GET THE AUTH CODE) response_type=code&
state=state_parameter_passthrough_value&
redirect_uri=https//www.salesforce.com&
client_id=http//
631950255594-mncomd3ev7ka1q5oa9fkd9bdgitem5ur.apps.googleuse
rcontent.com
POST /token HTTP/1.1
Host oauth2.googleapis.com
Content-Type application/x-www-form-urlencoded

Step 2 Get Access Token code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&


client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https%3A//oauth2.example.com/code&
grant_type=authorization_code

Resources-
Apex Rest
https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_intro.htm

https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_sample_basic.htm

https//trailhead.salesforce.com/en/content/learn/v/modules/apex_integration_services/
apex_integration_rest_callouts

Apex SOAP
https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_web_services.htm

https//trailhead.salesforce.com/en/content/learn/v/modules/apex_integration_services/
apex_integration_soap_callouts

Basic Authentication
https//en.wikipedia.org/wiki/Basic_access_authentication

Connected Application
https//developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/
intro_oauth_and_connected_apps.htm

OAuth 2.0 Authorization Framework


https//auth0.com/docs/protocols/protocol-oauth2

JWT Authentication
https//blog.logrocket.com/jwt-authentication-best-practices/

https//jwt.io/

OpenCage Geocoding API Documentation


https//opencagedata.com/api

LinkedInd API
https//docs.microsoft.com/en-us/linkedin/

https//docs.microsoft.com/en-us/linkedin/shared/authentication/authentication

QuickBooks API
https//developer.intuit.com/app/developer/qbo/docs/api/accounting/most-commonly-used/account

Authentication - https//developer.intuit.com/app/developer/qbo/docs/develop/
authentication-and-authorization

Google API
Authentication - https//developers.google.com/identity/protocols/oauth2/web-server

Scope List - https//developers.google.com/identity/protocols/oauth2/scopes


Google Calendar - https//developers.google.com/calendar/v3/reference/events/insert

Salesforce API -
Authentication - https//help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm&type=5

Freshdesk API
https//developers.freshdesk.com/api/

Named Credentials Salesforce


https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
apex_callouts_named_credentials.htm

https//help.salesforce.com/articleView?id=named_credentials_about.htm&type=5

Auth. Provider Salesforce


https//help.salesforce.com/articleView?id=sso_authentication_providers.htm&type=5

https//help.salesforce.com/articleView?id=sso_provider_sfdc.htm&type=5

https//help.salesforce.com/articleView?id=sso_authentication_providers.htm&type=5

https//help.salesforce.com/articleView?id=sso_provider_plugin_custom.htm&type=5

Einstein API
Sign Up - https//api.einstein.ai/signup

Authentication - https//metamind.readme.io/docs/generate-an-oauth-token-using-your-key

OCR API - https//metamind.readme.io/docs/what-is-einstein-ocr

Sentiment API - https//einstein.ai/products/community-sentiment

Chatter Rest API


Introduction - https//developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/
intro_what_is_chatter_connect.htm

Exaples - https//developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/quickreference.htm

Streaming API
https//developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/intro_stream.htm

https//trailhead.salesforce.com/en/content/learn/v/modules/api_basics/api_basics_streaming

Platform Event
https//developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/
platform_events_intro.htm

https//trailhead.salesforce.com/en/content/learn/v/projects/workshop-platform-events/platform-event-define

https//trailhead.salesforce.com/content/learn/modules/platform_events_basics

Change Data Capture


https//developer.salesforce.com/blogs/2018/08/what-is-change-data-capture.html

https//developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/
cdc_intro.htm

https//trailhead.salesforce.com/en/content/learn/v/modules/change-data-capture/
understand-change-data-capture

JSForce -
https//jsforce.github.io/document/

http//jsforce.github.io/jsforce/doc/

Outbound Message
https//developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_om_outboundmessaging.htm

https//help.salesforce.com/articleView?id=workflow_managing_outbound_messages.htm&type=5

https//developer.salesforce.com/docs/atlas.en-us.api.meta/api/
sforce_api_om_outboundmessaging_setting_up.htm

Metadata API
GitHub - https//github.com/financialforcedev/apex-mdapi

Introduction - https//developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_intro.htm

https//developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/file_based.htm

https//trailhead.salesforce.com/content/learn/modules/apex_metadata_api

Unit Test
https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_unit_tests.htm

https//trailhead.salesforce.com/en/content/learn/v/modules/apex_testing/apex_testing_intro

https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing.htm

https//help.salesforce.com/articleView?id=code_run_tests.htm&type=5

https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
apex_classes_restful_http_testing_httpcalloutmock.htm

https//developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts.htm

https//developer.salesforce.com/blogs/developer-relations/2013/03/
testing-apex-callouts-using-httpcalloutmock.html

Heroku
https//trailhead.salesforce.com/content/learn/modules/salesforce_heroku_integration

https//www.heroku.com/salesforce

Cross Org Adaptor


https//help.salesforce.com/articleView?id=xorg_adapter_about.htm&type=5

External Object
https//help.salesforce.com/articleView?id=external_object_define.htm&type=5

Project
https//pipedrive.readme.io/docs/core-api-concepts-authentication

https//developers.pipedrive.com/docs/api/v1/#/
GIT
GIT BASICS
version git --version
git help --all press q to exit view and shift + G END
config git config --global user.name "w3schools-test"
Use global to set the username and e-mail for every repository on your computer.
config git config --global user.email "[email protected]"
If you want to set the username/e mail for just the current repo you can remove global
initialize Git git init git dont track Empty Folder
Create new Repo in GitHub
mkdir make new directory
cd current dir
cd.. out of current dir
U untracked
M Modified
A Index Added (After Stating Done)
Adds content from all *.txt files under Documentation directory and its subdirectories:

Stage (Add Files to staging Ares) File ready to be committed git add . ----git add Documentation/\*.txt
unstage I still need to do some changes git rm --cached ...
Commit (only staged changes will be committed in Local Repo) finalizing the changes
Push push to git (local to remote) git push --set-upstream origin master
Local Repo VS code
git push --set-upstream origin master
Git Hub git remote add origin https//github.com/w3schools-test/hello-world.git
git remote add origin https//github.com/shubhaktripathi/oct23.git

git remote add Copado https//github.com/shubhaktripathi/Copado-pwcplayground.git


Add Remote (git hub repo)- git remote add origin githubrepoLink
Remove Remote git remote remove copado
change remote/origin git remote set-url origin https://github.com/OWNER/REPOSITORY.git
check remote git remote -v
check status of files git status
Viewing the Commit History git log
Undoing Things git commit --amend
Skip Staging git commit -am "messgae"
Delete file git rm file.txt
Creating a New Branch git branch testing In Git, a branch is a new/separate version of the main repository.
git checkout -b update-readme(direct creates new branch and switch)
Switching Branches git checkout testing
Switch Branch git checkout -b shubhamDev
All Branch git branch -a
Remote Branch git branch -r git checkout origin/master
merge combines the current branch, with a specified branch

git checkout master we need to change to the master branch


git merge test Merge will be done on branch where code will be added
Merge Test is branch which is to be merged on master
git branch -d test
Delete Branch
PULL

fetch gets all the change history of a tracked branch/repo.

FETCH So, on your local Git, fetch updates to see what has changed on GitHub git fetch origin
git diff origin/master git log origin/master
Difference bw Origin and Local
git merge origin/master
Merge
f you just want to update your local repository, without going through all those steps
fetch then Merge?

pull is a combination of fetch and merge. It is used to pull all changes from a remote
PULL(FETCH + MERGE) git pull origin repository into the branch you are working on.
clone from GitHub Repo Git Clone url
pull from github clone
push to scratch org push source to default scratch org
Pull Source from Scratch Org (If any metadata is created in scratch org)

PUSH

git push origin


PUSH will push changed to Remote Repo

PULL BRANCH FROM GIT HUB


git pull
Step 1
Step 2 git branch -a
Step 3 git checkout remoteBranchOnOrigin
Step 4 git pull

Git Push Branch to GitHub


git checkout localBranch git checkout -b update-readme(direct creates new branch and switch)

git push origin localBranch

GIT HUB FLOW


Create a new Branch
Make changes and add Commits
Open a Pull Request
Review
Deploy
The GitHub flow works like this Merge

GIT CONTRIBUTE

A fork is a copy of a repository. This is useful when you want to contribute to someone fork is not a command in Git, but something offered in GitHub and other repository
Git GitHub Fork else's project or start your own project based on theirs. hosts. Let's start by logging in to GitHub,
we have our own fork, but only on GitHub. We also want a clone on our local Git to keep
working on it.
A clone is a full copy of a repository, including all logging and versions of files.
git clone https//github.com/w3schools-test/w3schools-test.github.io.git Move back to the original repository, and click the green "Code" button to get the URL to
Clone clone
According to Git naming conventions, it is recommended to name your own repository origin,
and the one you forked for upstream
Now we have 2 remotes
origin - our own fork, where we have read and write access
upstream - the original, where we have read-only access

GIT ADVANCE

Examples
log files
temporary files
When sharing your code with others, there are hidden files
often files or parts of your project, you do not personal files
want to share. etc.
touch .gitignore
Create .gitignore
in this file Ignore any files with the .log extension # ignore ALL .log files
*.log

# ignore ALL files in ANY directory named temp


temp/
GIT UNDO
Git Revert revert is the command we use when we want to take a previous commit and add it as a
new commit, keeping the log intact.

GIT REBASE

Rebasing in Git is a process of integrating a series of commits on top of another base


tip. It takes all the commits of a branch and appends them to the commits of a new
branch.

Deployment To Production / SandBox


Convert source to metadata format sfdx forcesourceconvert
-r source directory
-d output directory
-n package name

Command Display Org Details for Default Org


Set Password for Scratch org user sfdx forceuserpasswordgenerate -u username

GIT CodeLab Basics (Real time Practice)

Fork a Repo Creating own copy of other Repo


Clone a Repo
Push souce to Scratch Org
Create Branch to make changes of your code in your branch only shubhamDev
Commit Change git commit -m "initial commit"
push to github git push origin shubhamDev git push origin branchName
Pull requests let you tell
others about changes
you've pushed to a branch
in a repository on GitHub.
Once a pull request is
opened, you can discuss and
Create a Pull Request
review the potential
changes with collaborators
and add follow-up commits
before your changes are
merged into the base
branch
Merge a Pull Request and Live Deployment using GitHub
Actions
Create a Merge Conflict
Because we're having same changes over same lines in a
single file
- Store the original repo URL
git remote add upstream https//github.com/rahulmalhotra/salesforce-git-codelab
- Switch to master branch
git checkout master
- Pull from Original repository
git fetch upstream master
- Merge upstream master with local master Merge a pull request into
git merge upstream/master the upstream branch when
Resolve Merge Conflict work is completed. Anyone
- Merge master branch into rahuldev with push access to the
git merge master --no-ff (no-ff means no fast forward) repository can complete the
- Staged Changes merge.
git add .
- Made a commit
git commit -m "Commit Message"
- PR is updated automatically

echo "# js" >> README.md


git init
git add README.md
…or create a new repository on the command line git commit -m "first commit"
git branch -M main
git remote add origin https//github.com/shubhaktripathi/js.git
git push -u origin main

git remote add origin https//github.com/shubhaktripathi/js.git


…or push an existing repository from the command line git branch -M main
git push -u origin main

You can define a namespace in a Developer Edition org that


isn’t your Dev Hub, and you can enable Dev Hub in a
Developer Edition org that doesn’t contain a namespace.
First Generation Package
You can't enable Dev Hub in
Setup > Package Manager > Edit > Name Space (only works when no package is created) [email protected] a Developer Edition org with
a registered namespace.

Second Generation Package

Scratch Org [email protected]

Enable DevHub > Auth DevHub in VS Code


Create New Scratch Org

sfdx forcesourcedeploy -x "manifest\package.xml" -c


GIT COMMANDS

You can view all of your settings and where they are
coming from using git config --list --show-origin
Open git config in VS code git config --global core.editor "code --wait"
Open git config in VS code git config --global -e
Global User Name git config --global user.name "John Doe"
Global User Email git config --global user.email [email protected]
git config --global core.autocrlf input

To set main as the default branch name to(master) $ git config --global init.defaultBranch main
check your configuration settings git config --list
$ git help <verb>
$ git <verb> --help
Getting Help $ man git-<verb>
cd C/Users/user/my_project
Initializing a Repository in an Existing Directory git init
git clone
Cloning an Existing Repository git clone https//github.com/libgit2/libgit2
git status
On branch master
Your branch is up-to-date with 'origin/master'.
Checking the Status of Your Files nothing to commit, working tree clean
echo 'My Project' > README
git status
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files
(use "git add <file>..." to include in what will be committed)

README
simple README file ( Echo command write content in
file) nothing added to commit but untracked files present (use "git add" to track)
Echo (modifying same file) echo helloAll >> README
Tracking New Files( Add - to add files to staging Area) git add README
add all files git add .
git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed
(use "git reset HEAD <file>..." to unstage)

new file README

Changes not staged for commit


(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

Staging Modified Files modified CONTRIBUTING.md


Committing Your Changes git commit
git log
Viewing the Commit History git clone https//github.com/schacon/simplegit-progit
Undoing Things git commit --amend
Skip Staging git commit -am "messgae"
Delete file git rm file.txt
Files in staging Area git ls-files.txt
Remove file from Repo as well as Staging Area git rm file.txt
rename file git mv file file2.txt
Creating a New Branch git branch testing
Switching Branches git checkout testing
Ignore files echo logs/> .gitignore
System- All Users
Global- All Repo of current users
Levels in Git Local- The Current Repo
short status git status -s
git diff --staged
git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"
Track Changes in VS code git config --global -e (default edititor )
git difftool --staged
Last Commit git show HEAD
Previous Commits git show HEAD~1
git restore --staged file.txt
Without Test.startTest, asynchronous code executes in last and the no account records was found when we queried that records in test class.

Test.startTest() Async? With Test.startTest asynchronous operation executes in series and result also obtained in test class.
Total number of records processed as a result of DML statements, Approval.process, or 10,000 10,000
Mannual Sharing for Queue

Both can be used, but having can be used for aggregate only and for aggregation. SELECT LeadSource, COUNT(Name)
FROM Lead
GROUP BY LeadSource
wHERE VS Having HAVING COUNT(Name) > 1
Service Cloud-

1- Create Service Console App


2- Email -to- Case
3- Web-to-Case ( Generate HTML template)
4- Support Process
5- Page Layouts
6- Record Types
7- Create Queues
8- Assignment Rules
9- Auto Response Rule
10- Case Escalation Rule
11- SLA - service level Agreement & KPI- key performance Indicator
12- Entitlement Management
Enable EntitleMent --> Create MileStone --> Create an EntitleMent Process --> Add your
Milestone to Ent. Process -->
Add workflow Action to the Process MileStone --> Create EntitleMent Templates for Products
13- Knowledge Management
14- Live Web Chat
15- Omni channel
1- Queue Base Routing 2- Skill Based routing 3- External Routing
Queuebased--> Enable omni channel --> Service Channel --> Routing Configuration --> Create
Queue --> Presence configuration --> Assign to Profile
Skillbased --> Enable Omni (Enable Skill based Routing) -->
Service Channel --> Create Skills --> Service Resources -->
Routing Configurations
REGEX
Regular expressions (regex or regexp) are a powerful tool for pattern matching and manipulating strings. They consist of a sequence of characters that define a search pattern. Here's an overview of the basic syntax and some
common components used in regex

1. Literals Characters that match themselves. For example, the regex `a` matches the character "a" in a string.

2. Metacharacters - `.` (dot) Matches any single character except a newline.


- `*` Matches zero or more occurrences of the preceding character or group.
- `+` Matches one or more occurrences of the preceding character or group.
- `?` Matches zero or one occurrence of the preceding character or group.
- `|` (pipe) Acts as an OR operator, allowing you to match one of multiple patterns.
- `^` Matches the start of a string.
- `$` Matches the end of a string.

3. Character Classes - `[abc]` Matches any one of the characters "a," "b," or "c."
- `[^abc]` Matches any character except "a," "b," or "c."
- `[a-z]` Matches any lowercase letter.
- `[A-Z]` Matches any uppercase letter.
- `[0-9]` Matches any digit.
- `[A-Za-z0-9]` Matches any alphanumeric character.

4. Quantifiers - `{n}` Matches exactly n occurrences of the preceding character or group.


- `{n,}` Matches at least n occurrences of the preceding character or group.
- `{n,m}` Matches between n and m occurrences of the preceding character or group.

5. Escape Sequences To match metacharacters as literals, you can escape them with a backslash `\`. For example, `\.`, `\*`, `\\`.

6. Predefined Character Classes - `\d` Matches any digit (equivalent to `[0-9]`).


- `\D` Matches any non-digit.
- `\w` Matches any word character (letters, digits, or underscores).
- `\W` Matches any non-word character.
- `\s` Matches any whitespace character (space, tab, newline).
- `\S` Matches any non-whitespace character.

7. Grouping - `()` Groups characters or patterns together, allowing you to apply quantifiers or other operations to a group.

8. Anchors - `\b` Matches a word boundary.


- `\B` Matches a non-word boundary.

9. Modifiers - `i` Case-insensitive matching.


- `g` Global matching (find all matches, not just the first).
- `m` Multiline mode (treats `^` and `$` as start/end of lines).

10. Escaping Special Characters To match characters that are regex metacharacters as literals (e.g., `[`, `]`, `(`, `)`, `?`), you need to escape them with a backslash `\`.

Matching a Pattern String text = 'The quick brown fox jumps over the lazy dog.';
String pattern = 'fox';
Boolean isMatch = Pattern.compile(pattern).matcher(text).find();
System.debug('Is there a match? ' + isMatch); // Output Is there a match? true

Extracting Email Addresses from Text String text = 'Contact us at [email protected] or [email protected] for assistance.';
String pattern = '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b';
Matcher matcher = Pattern.compile(pattern).matcher(text);
while (matcher.find()) {
System.debug('Found email ' + matcher.group());
}
// Output Found email [email protected]
// Found email [email protected]

Replacing Text String text = 'Hello, World!';


String pattern = 'World';
String replacement = 'Universe';
String updatedText = text.replaceAll(pattern, replacement);
System.debug('Updated Text ' + updatedText); // Output Updated Text Hello, Universe!

Validating a Phone Number (U.S. Format) String phoneNumber = '555-123-4567';


String pattern = '^(\\d{3}-)?\\d{3}-\\d{4}$';
Boolean isValid = Pattern.compile(pattern).matcher(phoneNumber).matches();
System.debug('Is the phone number valid? ' + isValid); // Output Is the phone number valid? true

Removing Non-Alphanumeric Characters String text = 'Hello, @World!';


String pattern = '[^A-Za-z0-9 ]';
String cleanedText = text.replaceAll(pattern, '');
System.debug('Cleaned Text ' + cleanedText); // Output Cleaned Text Hello World

1. Email Address Validation - Pattern `^[\w\.-]+@[\w\.-]+\.\w+$`


- Meaning Matches a valid email address.

2. URL Validation - Pattern `^(http|https)\/\/[\w\.-]+\.\w+$`


- Meaning Matches a valid URL starting with "http//" or "https//".
3. Date (MM/DD/YYYY) Validation - Pattern `^(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/\d{4}$`
- Meaning Matches a date in MM/DD/YYYY format.

4. ZIP Code (U.S.) Validation - Pattern `^\d{5}(-\d{4})?$`


- Meaning Matches a U.S. ZIP code, with an optional 4-digit extension.

5. IPv4 Address Validation - Pattern `^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`


- Meaning Matches a valid IPv4 address.

6. Credit Card Number Masking (Show last 4 - Pattern `^(.*?)(\d{4})$`


digits) - Meaning Captures the last 4 digits of a credit card number while masking the rest.

7. Username Validation (Alphanumeric, - Pattern `^[a-zA-Z0-9_-]+$`


underscores, and hyphens) - Meaning Matches usernames consisting of alphanumeric characters, underscores, and hyphens.

You might also like