INTERVIEW

  Salesforce Interview Preparation:






HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('https://mocki.io/v1/0cf842e2-8624-49a4-8b44-f540552f1efb');
req.setMethod('GET');
res = http.send(req);

List<Account> accs=(List<Account>)
json.deserialize(res.getbody(),
List<Account>.class);
List<Account> accToInsert = new List<Account>();
System.debug('accs '+accs);
for(Account acc: accs){
    Account accObject = new Account();
    accObject.Name = acc.Name;
    accObject.Description = acc.Description + ' added by callout';
    accToInsert.add(accObject);
}
insert accToInsert;

Similarly if you've list of Accounts in your JSON then try like this:

[
  {
    "Name":"ABC",
    "AccountNumber":"1312321"
  },
  {
    "Name":"DEF",
    "AccountNumber":"456456"
  }
]

Apex code for list of Accounts:

String jsonString = '[{"Name":"ABC","AccountNumber":"1312321"},{"Name":"DEF","AccountNumber":"456456"}]';
List<Account> actList = (List<Account>) JSON.deserialize(jsonString, List<Account>.class);
System.debug('Count:'+actList.size());


Apex Class:

public class CustomClass {
    public Integer price;
    public date startDate;
    public date endDate;
    public String name;
    public String category;
}

Deserialize JSON:

String jsonString = '{"price":100,"startDate":"09-09-2009","endDate":"09-10-2009","name":"IPHONE","category":"Mobile"}';
CustomClass obj = (CustomClass) JSON.deserialize(jsonString, CustomClass.class);
System.debug('CustomClass:'+obj.name);


how-to-deserialized-json-response-in-apex
public List<CaseDetails> cases {get; set;}
cases = (List<CaseDetails>) JSON.deserialize(res.getBody(), List<CaseDetails>.class);






Child to parent: 
SELECT Contact.FirstName, Contact.Account.Name From Contact

Parent to Child:
SELECT Name, (SELECT LastName FROM Contacts) FROM Account.


XML Parsing: Parse XML response and store it in Account object and create Account records with XML received from workbench.


@RestResource(urlMapping = '/AccountXMLService/*')

global class AccountXmlParser {    

    @HttpPost

    global static void parse(){

        List<Account> accounts = new List<Account>();    

        String xml = RestContext.request.requestBody.toString();

        System.debug('xml received '+xml);

        Dom.Document doc = new Dom.Document();

        doc.load(xml);

        Dom.XmlNode root = doc.getRootElement();

        for(Dom.XmlNode accountNode: root.getChildElements()){

            Account account = new Account();

            for(Dom.XmlNode fieldNode: accountNode.getChildElements()){

                String fieldName = fieldNode.getName();

                String fieldValue = fieldNode.getText();

                if(fieldName == 'Id'){

                    account.Id = fieldName;

                }

                else if(fieldName == 'Name'){

                    account.Name = fieldValue;

                }

                else if(fieldName == 'Type'){

                    account.Type = fieldValue;

                }

            }

            accounts.add(account);

        }

        insert accounts;

        System.debug('accounts '+accounts);

    }

}


/*

 execute below xml from workbench ==> Rest explorer ==>Post ==> Request Body


/services/apexrest/AccountXMLService/*


<Accounts>

<Account>

<Name>Acc1-XML</Name>

<Type>Customer - Channel</Type>

<Industry>Manufacturing</Industry>

</Account>

<Account>

<Name>Acc2-XML</Name>

<Type>Prospect</Type>

<Industry>Retail</Industry>

</Account>

</Accounts>

*/





trigger AccountTrigger on Account (after insert) {
    
    List<Contact> listContact = new List<Contact>();
    for(Account acc: Trigger.new){
        Contact con = new Contact();
        con.AccountId = acc.Id;
        con.LastName = acc.Name;
        con.Description = 'Description added by AccountTrigger!';
        listContact.add(con);
    }
    if(!listContact.isEmpty()){
        try{
            Database.SaveResult[] srList = Database.insert(listContact, false);
            for(Database.SaveResult sr : srList){
                if(sr.isSuccess()){
                    System.debug('Account inserted successfully. Account Id: '+sr.getId());
                }
                else {
                    for(Database.Error err : sr.getErrors()){
                        System.debug('Error '+err.getMessage());
                    }
                }
            }
        }
        catch(Exception ex){
            System.debug('Exception occurred '+ex);
        }
    }
}


trigger OpportunityTrigger on Opportunity (after insert, after update, after delete, after undelete) {
    Set<Id> accountIdSet = new Set<Id>();
    Map<Id, Account> accountMap = new Map<Id, Account>();
    
    if (Trigger.isInsert || Trigger.IsUpdate|| Trigger.isUndelete) {
        for(Opportunity opp: Trigger.new){
            if(opp.AccountId != null){
                accountIdSet.add(opp.AccountId);
            }
        }
    }
    
    if (Trigger.isDelete) {
        for(Opportunity opp: Trigger.old){
            if(opp.AccountId != null){
                accountIdSet.add(opp.AccountId);
            }
        }
        
    }
    if(accountIdSet != null){
        for(AggregateResult ar: [SELECT sum(Amount) sumAmount, AccountId FROM Opportunity 
                                 WHERE AccountId in: accountIdSet GROUP BY AccountId ])
        {
            Account acc = new Account();
            acc.Id = (Id)ar.get('AccountId');
            acc.Sum_of_Opportunities_Amount__c = (Decimal)ar.get('sumAmount');
            accountMap.put(acc.Id, acc);
        }
    }
    if(accountMap != null){
        update accountMap.values();
    }
}


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

trigger TaskTrigger on Task (before insert, before update) {
    Trigger_Setting__mdt mdt = Trigger_Setting__mdt.getInstance('TaskTrigger');
    if(mdt.Active__c == TRUE){
        System.debug('Execute Task Trigger');
        //logic
    }
}
==========================================================================================
Country__mdt mdt = Country__mdt.getAll();
system.debug('mdt '+mdt);
if(mdt.ISO_Code__c == 'CHN'){
System.debug('inside if');    
}
else {
    System.debug('outside if');
}

Map<String, Country__mdt> mdt = Country__mdt.getAll();
system.debug('mdt '+mdt);
for(String md1: mdt.keyset()){
    System.debug('md1 '+md1);
}
=======================================================================================
trigger TaskTrigger on Task (before insert, before update) {
    Trigger_Setting__mdt mdt = Trigger_Setting__mdt.getInstance('TaskTrigger');
    if(mdt.Active__c == TRUE){
        System.debug('Execute Task Trigger');
        //logic
    }
}
============================================================================================

Create a custom setting (say Trigger_Settings__c).  Add a checkbox field “Is Active”.  So your custom settings will store the trigger name and its status in IsActive checkbox.
Then in your apex trigger, add an IF condition at the top to check if the Trigger status in Custom settings is TRUE, only then run the entire apex trigger code.
trigger oppTrigger on opportunity (before insert){
  Trigger_Settings__c TS = Trigger_Settings__c.getValues('oppTrigger');
  if(TS.is_Active__c == TRUE){
    //your trigger code
  }
}

Salesforce.com >> Using a validation rule, how to allow specific user to create a new record on Account and restrict other user?


A nice way to do this is to use custom permissions. With this you can create your very own permissions that can be added to profiles or permission sets. You can then insert a check for this permission in the validation rule itself.

For example, if you created a custom permission "Bypass Validation X" ("X" representing the meaning of the validation to be bypassed) you can add that to profiles or permission sets and do something like the following in your validation rule:

NOT($Permission.Bypass_Validation_X) AND (...)

Where "..." is the original validation rule content without any user ID checking parts.

Only users with the required custom permission will be able to bypass the validation.


Checking profile names/IDs have always been problematic in validation rules. You shouldn't do it. Instead, create a Custom Permission, assign it to the two profiles, then you can easily check for that:

ISCHANGED(Name) && NOT($Permission.Change_Account_Name)

Transaction Control using SavePoint and Rollback in Salesforce

SavePoint and Rollback will help us to maintain transaction for DML statement.
Suppose you  have written multiple lines of DML statements in a try block, If any error occurs during DML Operations, the operation will be rolled back to the most recent save point and the entire transaction will not be aborted.

Savepoint sp;
try{
   sp = Database.setSavepoint();
  
   Account a = new Account();
   a.Name = 'Test Account';
   insert a;
  
   Contact c = new Contact(Account = a.Id);
   c.FirstName = 'Biswajeet';
   c.LastName = 'Samal';
   insert c;
  }
catch(Exception e){
    Database.RollBack(sp);
}
In this example, if any error occurs while inserting the Account ‘a’ or Contact ‘c’, then the entire transaction will be rolled back to SavePoint ‘sp’, as specified in the catch section by Database.Rollback method.

1. Batch Apex: is asynchronous apex used to process the records in the background without user having to wait to complete the task.

global class sampleBatchClass implements Database.Batchable<sObject> {

global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator('SELECT Id FROM Account WHERE CreateDate < LAST_N_DAYS:7');
}

global void execute(Database.BatchableContext bc, List<Account> accts){
if(!accts.isEmpty){
try {
Database.Delete(accts, false);
}
catch(Exception ex){
System.debug('Exception occurred '+ex);
}
}
}

global void finish(Database.BatchableContext bc){

}
}


If you specify Database.Stateful in the class definition, you can maintain state across these transactions.

Below code snippet with an example how to count the number of records which are processed in batch operation.
 
public class BatchApexStateful implements Database.batchable<Sobject>,Database.Stateful{
public integer count = 0;
public Database.QueryLocator start(Database.BatchableContext bc){
String str ='select id,Name,Description from Account';
return Database.getQueryLocator (str);
}

public void execute(Database.BatchableContext bc, List<Account> accs){
for(Account a :accs){
a.Description = 'Description added by BatchApexStateful !'; 
}
 
try{
      
database.saveresult[] ds =  Database.update(accs,false);
    for(database.SaveResult d : ds){
        if(d.issuccess()){
            count++;
        }
        
    }
}
catch(exception e){
system.debug('update failed');
}
}

public void finish(Database.BatchableContext bc){
    system.debug(count);
//Send an email to the User after your batch completes
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'sohailmd60@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Batch Apex Job is done');
mail.setPlainTextBody('Total' +'  '+ count +'  '+ 'Records updated sucessfully');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}


Execution of batch job : 

BatchApexStateful b = new BatchApexStateful();
Database.executeBatch(b);


2. Schedulable Apex: is asynchronous process used to schedule the batch apex from Salesforce UI.


To schedule apex class ==> go to Apex Classes ==> Click on "Schedule Apex" button ==> Select class and time.
global class sampleSchedulableClass implements Schedulable {

global void execute(SchedulableContext sc){
sampleBatchClass s = new sampleBatchClass();
Database.executeBatch(s, 200);
}
}

Scheduled Apex Class Using Cron Expression: 

AccountBatchScheduled apexSch = new AccountBatchScheduled(); 

//Seconds, Minutes, Hours, Day of month, Month, Day of week, Optional year 
String CRON_EXP = '0 0 0 3 9 2 ?';
String jobID = System.schedule('AccountBatchScheduled Job', CRON_EXP, apexSch);
0 0 13 * * ?  ==> Class runs every day at 1 PM.

3. Future Method in Apex: is used to run processes in a separate thread at later when resources become available.

public class sampleFutureClass {

@future
public static void methodName(List<Id> accountIds){
// logic
}
}

You can use the future annotation when making an asynchronous Web service callout to an external service.

public class AccountProcessor 
{
  @future
  public static void countContacts(Set<id> setId) 
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
          
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

To allow callouts in a future method, specify (callout=true). The default is (callout=false), which prevents a method from making callouts.

The following snippet shows how to specify that a method executes a callout:

@future (callout=true)
public static void doCalloutFromFuture() {
    //Add code to perform callout
}

Using Callouts in Batch Apex
To use a callout in batch Apex, specify Database.AllowsCallouts in the class definition. For example:

global class SearchAndReplace implements Database.Batchable<sObject>,
   Database.AllowsCallouts{
}

4. Queueable Apex: You can chain one job to another job by starting a second job from a running job. Chaining jobs are useful when we need to do some sequential processing.

public class sampleQueueableClass implements Queueable {

public void execute(QueueableContext qc){
// logic
}
}

Queueable Apex Example:
In this example we will append sfdcpoint at the end of account name


public class AccountQueueableExample implements Queueable {
    public List<Account> accList ; 
    public AccountQueueableExample(List<Account> accList){
        this.accList = accList ;  
    }
    public void execute(QueueableContext context) {
        for(Account acc :accList){
            // Update the Account Name 
            acc.Name = acc.Name + 'sfdcpoint';
        }
        update accList;
    }
}

Run the job from the execute anonymous with below code.

List<Account> accList = [Select Id , Name from Account ];
ID jobID = System.enqueueJob(new AccountQueueableExample(accList));
System.debug('jobID'+jobID);

We can call a Queueable class from you Trigger/Class/Controller simply place use “System.enqueueJob(new ClassName())”.



5. Apex Trigger: is apex code which will execute before/after DML operation is performed on the database. 

Apex Trigger events: BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE, AFTER INSERT, AFTER UPDATE, AFTER DELETE, AFTER UNDELETE.

Context variables: IsBefore, IsAfter, IsInsert, IsUpdate, IsDelete, IsUndelete.

Trigger:

Trigger AccountTrigger on Account(Before Insert, Before Update, Before Delete, 
 After Insert, After Update, After Delete, After Undelete){

if(Trigger.IsAfter){
if(Trigger.isInsert){
AccountTriggerHelper.createContact(Trigger.new);
}
}
}


Trigger Helper Class:

 
public class AccountTriggerHelper {

public static void createContact(List<Account> listAcc){

List<Contact> listCon = new List<Contact>();
for(Account acc: listAcc){
Contact con = new Contact();
con.LastName = acc.Name;
con.AccountId = acc.Id;
listCon.add(con);
}
if(!listCon.isEmpty){
try {
Database.insert(listCon, false);
}
catch(Exception ex){
System.debug('Exception 'ex);
}
}
}
}

6. Apex Test Class: is used to test the apex code.

Test Class:
@isTest
public class sampleTestClass {

static testMethod void sampleMethod(){

LisT<Account> listAcc = TestDataUtility.createAccounts();
insert listAcc;
}
}

( or )

@isTest
public class sampleTestClass {

static testMethod void sampleMethod(){
Account acc = new Acount(Name = 'Test');
insert listAcc;
}
}


TestDataUtility class: is used to store bulk records in a separate class so that it can utilized whenever data is required in any test class. 

public class TestDataUtility {

public static List<Account> createAccounts(){
List<Account> accts = new List<Account>();
for(Integer i=1; i<=20; i++){
Account acc = new Account();
acc.Name = ConstantUtility.accName + i;
acc.Description = ConstantUtility.stringDescription;
accts.add(acc);
}
return accts;
}
}

Constant Utility Class: is used to store constant values in a separate class so that it can be utlized wherever is required.

public class ConstantUtility {
public static String accName = 'Test Account';
public static String stringDescription = 'Sample Description';
}

7. SOAP Inbound Web Service: is used to capture the data from external system and store in Salesforce.

global class sampleClass {

webservice Static String createAccount(String accName){
Account acc = new Account();
acc.Name = accname;
if(acc != null){
try {
insert acc;
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}
}
}


8. Rest Inbound Web Service: is used to capture the data from external system and store it in Salesforce org.

@RestResource(urlMapping = '/accounts/*')
global class sampleRestClass {

@HttpPost
global static Account createAccount(String accName){
Account acc = new Account(Name = accName);
insert acc;
return acc;
}
}



9. Lightning Web Component: is used to create UI for Salesforce applications.
LWC to display records:

Server Side Controller:

public  class AccountController 
{
   @AuraEnabled(cacheable=true)
   public static List<Account> displayAccounts(){
       return [select Id, Name, Site from Account];
   }
}


DisplayAccounts.html

<template>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
</tr>
<template for:each={accounts.data} for:item="acc">
<tr key={acc.Id}>
<td>
{acc.Name}
</td>
</tr>
</template>
</table>
</template>
</template>

DisplayAccounts.js

import { LightningElement,api,wire } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountController.displayAccounts';

export default class UpdateAccount extends LightningElement {
    @wire(displayAccounts) accounts;    
}

LightningApplication

<aura:application extends="force:slds">
<c:DisplayAccounts/>
</aura:application>


10. Trigger to fetch values from Custom Metadata type and update in ISO__c field of Account:

Trigger updateIsoCode on Contact(before insert) {
  List < Country_ISO_Code__mdt > countryIsoCodeMetadata = [SELECT Id,
  Country__c, ISO_Code__c FROM Country_ISO_Code__mdt
  ];
  Map < String, String > countryIsoCodeMap = new Map < String, String > ();
  if (countryIsoCodeMetadata != null && countryIsoCodeMetadata.size() > 0) {
   for (Country_ISO_Code__mdt cmd: countryIsoCodeMetadata) {
    countryIsoCodeMap.put(cmd.Country__c, cmd.ISO_Code__c);
   }
  }
  for (Contact con: Trigger.new) {
   if (countryIsoCodeMap.containsKey(con.Country__c)) {
    System.debug('inside Contact loop @@@ ' + countryIsoCodeMap);
    con.ISO_Code__c = countryIsoCodeMap.get(con.Country__c);
   }
  }
 }

11. Trigger to prevent duplicate primary contacts:

Trigger PrimaryContactChecking on Contact(after insert, after update) {
  Set < Id > accountIdSet = new Set < id > ();
  Map < Id, List < Contact >> accountIdContactMap = new Map < Id, List < Contact >> ();
  Account acc = new Account();
  for (Contact con: Trigger.New) {
   accountIdSet.add(con.AccountId);
  }
  for (Contact con: [SELECT Id, IsPrimaryContact__c, AccountId FROM Contact
    WHERE AccountId =: accountIdSet AND IsPrimaryContact__c = TRUE
   ]) {
   if (accountIdContactMap.containsKey(con.AccountId)) {
    accountIdContactMap.get(con.AccountId).add(con);
   } else {
    accountIdContactMap.put(con.AccountId, new List < Contact > ());
    accountIdContactMap.get(con.AccountId).add(con);
   }
  }
  for (Contact con: Trigger.New) {
   if ((accountIdContactMap.containsKey(con.AccountId)) &&
    (con.AccountId != NULL) && (con.IsPrimaryContact__c == TRUE)) {
    {
     con.IsPrimaryContact__c.addError('Primary Contact already exists');
     con.addError('Primary Contact already exists');
    }
   }
  }
 }

12. Rest callouts to send data to external syntax. 

Apex Rest callout - POST:

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}

Continuation:
public with sharing class ContinuationSampleController {
 //Action method
 @AuraEnabled(continuation=true)
 public static Object sendRequest() {
 Continuation con = new Continuation(40);
 con.continuationMethod='getResponse';
 HttpRequest req = new HttpRequest();
 req.setMethod('GET');
 req.setEndpoint('CALLOUT_URL');
 con.addHttpRequest(req);
 con.state='This is state from request method';
 return con;
    }
 // Callback method
 @AuraEnabled
 public static Object getResponse(List<String> labels, Object state) {
 HttpResponse response = Continuation.getResponse(labels[0]);
 String result = response.getBody();
 return result;
    }
}

Here’s the component’s JavaScript file.

import { LightningElement, track } from 'lwc';
import sendRequest from '@salesforce/apexContinuation/ContinuationSampleController.sendRequest ';
export default class ContinuationSample extends LightningElement {
    @track listOfRecords={};
    @track error;
 connectedCallback() {
 sendRequest()
            .then(result => {
 this.listOfRecords = result;
 this.error = undefined;
            })
            .catch(error => {
 this.error = error;
 this.listOfRecords = undefined;
            });
    }
 
}

HTML Code

<!-- ContinuationSample.html -->
<template>
 <div>
        Show result: {listOfRecords}
 </div>
</template>

13. Display and Update records using button in LWC:
 
Apex Class:

public  class AccountController 
{
   @AuraEnabled(cacheable=true)
   public static List<Account> displayAccounts(){
       return [select Id,Name,Site from Account];
   }
   @AuraEnabled
   public static List<Account> updateRecord(String accId){
       Account acc=[select Id,Name,Site from Account where Id=:accId];
       acc.site='Approved';
       try{
           update acc;
       }
   catch (Exception e) {
           System.debug('unable to update the record due to'+e.getMessage());
       }
       return displayAccounts();
   }
}

updateAccount.html

<template>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
<td><b>Site</b></td>
<td><b>Action</b></td>
</tr>
<template for:each={accounts.data} for:item="acc">
<tr key={acc.Id}>
<td>
{acc.Name}
</td>

<td>
<lightning-button label="update"  variant="brand" value={acc.Id} onclick={handleUpdate}>
</lightning-button>
</td>
</tr>
</template>
</table>
</template>
</template>

updateAccount.js

import { LightningElement,api,wire } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountController.displayAccounts';
import updateRecord from '@salesforce/apex/AccountController.updateRecord';
import { refreshApex } from '@salesforce/apex';
export default class UpdateAccount extends LightningElement {
@api currentRecordId;
@api errorMessage;
    @wire(displayAccounts) accounts;
    handleUpdate(event){
        this.currentRecordId=event.target.value;
        console.log('@@currentRecordId@@@'+this.currentRecordId);
        updateRecord({
            accId:this.currentRecordId
        })
        .then(() => {
            console.log('SUCCESS');
            return refreshApex(this.accounts);
        })
        .catch((error) => {
            this.errorMessage=error;
console.log('unable to update the record due to'+JSON.stringify(this.errorMessage));
        });
    }
}




    ********************  SOAP INTEGRATION  ********************
 
14. SOAP Web service to create Account record.

global class CreateAccountWebService{
   webservice  static String createAcc(String accountName){
        Account acc = new Account();
        acc.Name = accountName;
        insert acc;
        return 'Account is created successfully. Account Id is: '+acc.Id;
    }
}

Soap Inboud web service to create Account:

global class AccountCreationWebServiceUsingSoap {
    global class AccountRequestDetails {
        webservice String accountName;
        webservice String accountDescription;
    }
    
    global class AccountResponseDetails {
        webservice String accountCreationStatus;
        webservice String accountName;
    }
    
    private static AccountResponseDetails requiredFieldValidation(AccountRequestDetails accountRequest) {
        AccountResponseDetails accountResponse = new  AccountResponseDetails();
        if(accountRequest.accountDescription == NULL || accountRequest.accountDescription == '' ) {
            accountResponse.accountCreationStatus = 'Please enter description';
        }
        return accountResponse;
    }
    
    private static AccountResponseDetails insertAccount(AccountRequestDetails accRequest) {
        AccountResponseDetails accResponse = new AccountResponseDetails();
        accResponse = requiredFieldValidation(accRequest);
        if(accResponse.accountCreationStatus == NULL || accResponse.accountCreationStatus == '') {
            Account acc = new Account();
            acc.Name = accRequest.accountName;
            acc.Description = accRequest.accountDescription;
            try{
                insert acc;
                accResponse.accountCreationStatus = 'Account is created. Account Id is: '+acc.Id;
                accResponse.accountName = acc.Name;
                return accResponse;
            }
            catch(Exception e) {
                String msg = 'Error occurred' +e.getMessage();
                accResponse.accountCreationStatus = msg;
                return accResponse;
            }
        }
        return accResponse;
    }
    
    webservice static AccountResponseDetails createAccount(AccountRequestDetails accReq) {
        AccountResponseDetails accResponse =  insertAccount(accReq);
        return accResponse;
    }
}


Visualforce page and apex class for SOAP Outbound Account Creation:

public class SOAP_Outbound_Account_Creation {
    public Account acc {get; set;}
    public String destinationAccountStatus {get; set;}
    public String sourceAccountStatus {get; set;}
    public SOAP_Outbound_Account_Creation(){
        acc = new Account();
        destinationAccountStatus = '';
        sourceAccountStatus = ''; 
    }   
    
    public PageReference doSave(){
        partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();
        partnerSoapSforceCom.LoginResult log = sp.login('sohel@sf.com', 'so123');
        
        soapSforceComSchemasClassAccountcre.SessionHeader_element SessionHeader = 
        new soapSforceComSchemasClassAccountcre.SessionHeader_element();
        SessionHeader.sessionId = log.sessionId;
        
        soapSforceComSchemasClassAccountcre.AccountCreationWebServiceUsingSoap AccountCreationWebService = 
        new soapSforceComSchemasClassAccountcre.AccountCreationWebServiceUsingSoap();
        AccountCreationWebService.SessionHeader = SessionHeader;
        
        soapSforceComSchemasClassAccountcre.AccountRequestDetails AccountRequest = 
        new soapSforceComSchemasClassAccountcre.AccountRequestDetails();
        AccountRequest.accountName = acc.Name;
        AccountRequest.accountDescription = acc.Description;
        
        
        soapSforceComSchemasClassAccountcre.AccountResponseDetails response = 
        new soapSforceComSchemasClassAccountcre.AccountResponseDetails();
        response = AccountCreationWebService.createAccount(AccountRequest);
        insert acc;
        sourceAccountStatus = 'Source Org: Account is created. Account Id: '+acc.Id;
        destinationAccountStatus = 'Destination Org: '+response.accountCreationStatus;
        return null;
    }
}


<apex:page controller="SOAP_Outbound_Account_Creation">
 <apex:sectionHeader title="Create" subtitle="Account"/>
 <apex:form >
 <apex:outputText value="{!sourceAccountStatus }" style="color:green; font-weighte:bold;"/><br/><br/>
 <apex:outputText value="{!destinationAccountStatus }" style="color:green; font-weighte:bold;" />
     <apex:pageBlock title="Account Info">
         <apex:pageBlockSection >
             <apex:inputField value="{!acc.Name}"/>
             <apex:inputField value="{!acc.Description}"/>
         </apex:pageBlockSection>
         <apex:pageBlockButtons >
             <apex:commandButton value="Save" action="{!doSave}"/>
         </apex:pageBlockButtons>
     </apex:pageBlock>
 </apex:form>
</apex:page>

Result: 
Source Org: Account is created. Account Id: 0010I00002JiL1TQAV
Destination Org: Account is created. Account Id is: 0010K00002DQTBwQAP


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

15. Rest Inbound web service to create record.
   
   /*************
    Workbench rest post url: /services/apexrest/ ContactCreationRestservice2
    Request Body:
    {
    "req": {
    "contactLastName" : "Test",
    "contactEmail" : "test@test.com",
    "contactPhone" : "1212121212"
    }
    }
    ***************

   @RestResource(urlMapping='/ContactCreationRestservice2/*')

    global class ContactCreationRestservice2{
    global class ContactRequestDetails{
        webservice String contactLastName;
        webservice String contactEmail;
        webservice String contactPhone;
    }
    
    global class ContactResponseDetails{
        webservice String contactLastName;
        webservice String contactCreationStatus;
        webservice String errorMessageStatus;
    }
    
    private static ContactResponseDetails validateRequiredFields(ContactRequestDetails contactRequest){
        ContactResponseDetails contactResponse = new ContactResponseDetails();
        if(contactRequest.contactPhone == '' || contactRequest.contactPhone == NULL){
            contactResponse.contactCreationStatus = 'Please enter Phone Number';
        }
        return contactResponse;
    }
    
    private static ContactResponseDetails insertContactDetails(ContactRequestDetails contRequest){
        ContactResponseDetails contResp = new ContactResponseDetails();
        contResp = validateRequiredFields(contRequest);
        if(contResp.contactCreationStatus == NULL || contResp.contactCreationStatus == ''){
            Contact contactObject = new Contact();
            contactObject.LastName = contRequest.contactLastName;
            contactObject.Email = contRequest.contactEmail;
            contactObject.Phone = contRequest.contactPhone;
            try
            {
                insert contactObject;
                contResp.contactCreationStatus = 'Contact is created successfully. Contact Id: ' +contactObject.Id;
                contResp.contactLastName = contactObject.LastName;
                return contResp;
                }
            catch(Exception ex){
                String errorMessage = 'Error occurred' +ex.getMessage();
                contResp.contactCreationStatus = errorMessage;
                return contResp;
            }
            
        }
        else{
            return contResp;
        }
    
    }
    
    @HttpPost
    global static ContactResponseDetails createContact(ContactRequestDetails req){
        //RestRequest restReq = RestContext.request;
        //RestResponse restResp = RestContext.response;
        ContactResponseDetails res = insertContactDetails(req);
        return res;
    }
}
    
    Rest Outbound web service for above inbound rest service:
    ===================================

    public class ContactCreationRestservice_Outbound{

    public String contactPhone { get; set; }
    public String contactEmail { get; set; }
    public String contactLastName { get; set; }
    public String contReq { get; set; }
    public String response{get;set;}
    
    public class ContactRequestDetails{
        String contactLastName;
        String contactEmail;
        String contactPhone;
    }
    
    public PageReference CreateContact() {
        ContactRequestDetails contReq = new ContactRequestDetails();
        //find access token using Auth 2.0 
        String Access_Token='00D28000000JPGf!AQ8AQJH27ODTW8k4SQz1wd5zKMXKX7D7tGwmjkyETuNjdwgl94yIeBN8QFpVlRQg_xQWeEpBjhtKjWVurcU.EQUP0ND3Jovp';
        //String username = 'sohel@sf.com';
        //String password = 'so123';

        Httprequest req=new httprequest();
        String domainName= 'https://mohd-sohel-dev-ed.my.salesforce.com';
        String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/apexrest/ContactCreationRestservice2/';
        //String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/data/v27.0/sobjects/Account';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
        req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+contactLastName+'</name><email>'+contactEmail+'</email><phone>'+contactPhone+'</phone> </request>');
        req.setmethod('POST');
        
        //Blob headerValue = Blob.valueOf(username + ':' + password);
        //String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
        //req.setHeader('Authorization', authorizationHeader);

        
        req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        response=res.getbody();
        System.debug('****************res.getStatusCode();'+res.getStatusCode());
        System.debug('****************res.getbody();'+res.getbody());
        return null;
    }
}
    
    Visualforce page:
    
    <apex:page controller="ContactCreationRestservice_Outbound">
    <apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Create Contact in SF1 instance" action="{!CreateContact}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aname" value="Name"></apex:outputLabel>
                <apex:inputText value="{!contactLastName}" id="aname"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aphone" value="email"></apex:outputLabel>
                <apex:inputText value="{!contactEmail}" id="aphone"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aw" value="Phone"></apex:outputLabel>
                <apex:inputText value="{!contactPhone}" id="aw"/>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
    <apex:pageBlock title="Response">
        <apex:pageBlockSection >
            <apex:outputText value="{!Response}"></apex:outputText>
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
    </apex:page>



16. Dynamic search functionality in Lightning Web Component with event:

public with sharing class AccountDataController {
    public AccountDataController() {

    }
    @AuraEnabled
    public static List<Account> displayAccounts(String searchekey){
        String searchword='%'+searchekey+'%';
        List<Account> returnlist=new List<Account>();
        if(!String.isBlank(searchekey))
        for(Account acc:[select Id,Name,Site from Account where Name like:searchword]){
            returnlist.add(acc);

        }
        return returnlist;
    }
}
searchAccountComponent.html
<template>
    <lightning-input type="text"  class="accName" label="SearchAccounts" onchange={handleSearch}>
    </lightning-input>
</template>

searchAccountComponent.js
import { LightningElement,api } from 'lwc';

export default class SearchAccountComponent extends LightningElement {
    
    @api userInput;
    handleSearch(event){
        this.userInput=event.target.value;
        const newEvent=new CustomEvent('inputcarryevent',{
            detail:this.userInput

        });
        this.dispatchEvent(newEvent);

    }
}

accountDataComponent.html
<template>
    <c-search-account-component oninputcarryevent={displayData}>
    </c-search-account-component><br/><br/>
    <div if:true={isshow}>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
            <tr>
                <td><b>Name</b></td>
                <td><b>Site</b></td>
            </tr>
            <template for:each={records} for:item="acc">
                <tr key={acc.Id}>
                    <td>
                        {acc.Name}
                    </td>
                    <td>
                        {acc.Site}
                    </td>

                </tr>
            </template>
        </table>
    </div>
</template>
accountDataComponent.js
import { LightningElement,api } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountDataController.displayAccounts';

export default class AccountDataComponent extends LightningElement {
    @api records;
    @api error;
    @api isshow;
    displayData(event){
        console.log('@@@@Entered into the method@@@');
        displayAccounts({
            searchekey:event.detail
        })
        .then(result=>{
            this.records=result;
            console.log('@@@records'+JSON.stringify(this.records));
            if(result.length!=0){
                this.isshow=true;
            }
            else{
                this.isshow=false;
            }
            this.error=undefined;

        })
        .catch(error=>{
            this.records=undefined;
            this.error=error;
        });
    }
}

LightningApplication
<aura:application extends="force:slds" >
    <c:accountDataComponent/>
</aura:application>


17. REST Inbound Web service with all types of methods:

@RestResource(urlMapping='/Cases/*')
global with sharing class CaseManager {
    @HttpGet
    global static Case getCaseById() {
        RestRequest request = RestContext.request;
        String caseId = request.requestURI.substring(
          request.requestURI.lastIndexOf('/')+1);
        Case result =  [SELECT CaseNumber,Subject,Status,Origin,Priority
                        FROM Case
                        WHERE Id = :caseId];
        return result;
    }
    @HttpPost
    global static ID createCase(String subject, String status,
        String origin, String priority) {
        Case thisCase = new Case(
            Subject=subject,
            Status=status,
            Origin=origin,
            Priority=priority);
        insert thisCase;
        return thisCase.Id;
    }   
    @HttpDelete
    global static void deleteCase() {
        RestRequest request = RestContext.request;
        String caseId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
        delete thisCase;
    }     
    @HttpPut
    global static ID upsertCase(String subject, String status,
        String origin, String priority, String id) {
        Case thisCase = new Case(
                Id=id,
                Subject=subject,
                Status=status,
                Origin=origin,
                Priority=priority);
        upsert thisCase;
        return thisCase.Id;
    }
    @HttpPatch
    global static ID updateCaseFields() {
        RestRequest request = RestContext.request;
        String caseId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
        // Deserialize the JSON string into name-value pairs
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
        // Iterate through each parameter field and value
        for(String fieldName : params.keySet()) {
            // Set the field and value on the Case sObject
            thisCase.put(fieldName, params.get(fieldName));
        }
        update thisCase;
        return thisCase.Id;
    }    
}

 18. Apex trigger to update child record when parent record is updated. 
 trigger ContactUpdate on Account(after update) {
  Map < Id, Account > mapAccount = new Map < Id, Account > ();
  List < Contact > listContact = new List < Contact > ();

  for (Account acct: trigger.new)
   mapAccount.put(acct.Id, acct);

  listContact = [SELECT MailingStreet, MailingCity, AccountId FROM Contact
   WHERE AccountId IN: mapAccount.keySet()
  ];

  if (listContact.size() > 0) {
   for (Contact con: listContact) {
    con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
    con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
   }
   update listContact;
  }
 }

 19. Apex trigger to update parent record when child record is updated. 
 Trigger UpdateDescription on Contact(after insert, after update) { 
  Map < ID, Account > accIdMap = new Map < ID, Account > (); 
  //Making it a map instead of list for easier lookup
  
  List < Id > accIdSet = new List < Id > ();
  for (Contact childObj: Trigger.new {
    accIdSet.add(childObj.AccountId);
   }

   accIdMap = new Map < Id, Account > ([SELECT id, Description,
    (SELECT ID, Description FROM Contacts) FROM Account WHERE ID IN: accIdSet
   ]);

   for (Contact con: Trigger: new) {
    Account myParentOpp = accIdMap.get(con.AccountId);
    myParentOpp.Description = con.Description;
   }
   update accIdMap.values();
  }

20. Apex XML parsing:

String strResp = '<?xml version="1.0" encoding="UTF-8"?><breakfast_menu>  <food>    <name>Belgian Waffles</name>    <price>$5.95</price>    <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>    <calories>650</calories>  </food>  <food>    <name>Strawberry Belgian Waffles</name>    <price>$7.95</price>    <description>Light Belgian waffles covered with strawberries and whipped cream</description>    <calories>900</calories>  </food>  <food>    <name>Berry-Berry Belgian Waffles</name>    <price>$8.95</price>    <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>    <calories>900</calories>  </food>  <food>    <name>French Toast</name>    <price>$4.50</price>    <description>Thick slices made from our homemade sourdough bread</description>    <calories>600</calories>  </food>  <food>    <name>Homestyle Breakfast</name>    <price>$6.95</price>    <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>    <calories>950</calories>  </food></breakfast_menu>';  

Dom.Document doc = new Dom.Document();  
doc.load( strResp );  
Dom.XMLNode rootElement = doc.getRootElement();  
for ( Dom.XMLNode childElement : rootElement.getChildElements() ) {  
      
    for ( Dom.XMLNode detailElement : childElement.getChildElements() )  
        system.debug( detailElement.getName() + '-' + detailElement.getText() );  
      
 
Output:

name-Belgian Waffles
price-$5.95
-
-

21. Database.SaveResult: 


List<Account> listAccount = new List<Account>();
Account acc = new Account();
acc.Name = 'testAccount1';

Account acc2 = new Account();
acc2.Name = 'testAccount2';

listAccount.add(acc);
listAccount.add(acc2);

System.debug('listAccount '+listAccount);

if(listAccount != null && listAccount.size()>0){
    Database.SaveResult[] srList = Database.insert(listAccount, false);
    System.debug('srList ' +srList);
    for(Database.SaveResult sr: srList){
        if(sr.isSuccess()){
            System.debug('Records inserted successfully '+sr.getId());
        }
        else
        {
            for(Database.Error objErr: sr.getErrors()){
                System.debug('The following error has occurred ');
                System.debug(objErr.getStatusCode() + ': '+objErr.getMessage());
                System.debug('Error occurred by fields '+objErr.getFields());
            }
        }
    }
}

22. Trigger to count, sum, min, max, avg of child records using Aggregate Result:


Trigger ContactAggregateResult on Contact(after insert){
    
    Set<Id> accountIdSet = new Set<Id>();
    Map<Id, Account> accountMap = new Map<Id, Account>();
    for(Contact con: Trigger.new){
        if(con.AccountId != null){
            accountIdSet.add(con.AccountId);
        }
    }
    if(accountIdSet != null){
        for(AggregateResult ar: [SELECT count(Id) contactCount, sum(Amount__c) sumAmount, 
                                 avg(Amount__c) avgAmount, Max(Amount__c) maxAmount,
                                 min(Amount__c) minAmount, AccountId FROM Contact 
                                 WHERE AccountId in: accountIdSet GROUP BY AccountId ])
        {
            Account acc = new Account();
            acc.Id = (Id)ar.get('AccountId');
            acc.Count_of_Contacts__c = (Integer)ar.get('contactCount');
            acc.Sum_of_Contacts_Amount__c = (Decimal)ar.get('sumAmount');
            acc.Max_of_Contacts_Amount__c = (Decimal)ar.get('maxAmount');
            acc.Min_of_Contacts_Amount__c = (Decimal)ar.get('minAmount');
            acc.Average_Of_Contacts_Amount__c = (Decimal)ar.get('avgAmount');
            accountMap.put(acc.Id, acc);
        }
    }
    if(accountMap != null){
        update accountMap.values();
    }
}


23. Delete multiple object records using batch apex.

global class SampleBatchClass implements Database.Batchable<string>, Database.Stateful, Schedulable  {
    
    global boolean reRun = false; 
    global Set<string> setToAddresses = new Set<String>();
    global Set<string> setCcAddresses = new Set<String>();
    
    global List<string> setToAddressesList = new List<String>();
    global List<string> setCcAddressesList = new List<String>();
    
    global SampleBatchClass(){
        for(CEP_Storage_Email__mdt mdt: [SELECT Label, Set_To_Addresses__c, Set_Cc_Addresses__c FROM CEP_Storage_Email__mdt 
                                         WHERE Active__c = TRUE LIMIT 50000 ])
        {
            if(mdt.Set_To_Addresses__c){
                setToAddresses.add(mdt.Label);
            }
            if(mdt.Set_Cc_Addresses__c){
                setCcAddresses.add(mdt.Label);
            }
        }
        setToAddressesList = new List<String>(setToAddresses);
        setCcAddressesList = new List<String>(setCcAddresses);
    }
    
    global Iterable<string> start(Database.BatchableContext ctx) {
        Set<String> setMetadata = new Set<String>();
        for(CEP_ObjectName__mdt mdt: [SELECT Label, Days__c FROM CEP_ObjectName__mdt WHERE Active__c = FALSE  
                                     /* AND Days__c != NULL AND Days__c = 90 */  LIMIT 50000])
        {
            //setMetadata.add(mdt.Label);
            setMetadata.add(mdt.Label+'-'+mdt.Days__c); //
        }
        List<String> listMetadata = new List<String>(setMetadata);
        return listMetadata;
    }
    
    global void execute(Database.BatchableContext ctx, list<string> lstsObjectName) {
        list<sObject> objectRecords = new list<sObject>();
        List<String> valueArray = new List<String>(); //
        for(string strObjectName : lstsObjectName) {
            valueArray = strObjectName.split('-'); //
            
            System.debug('valueArray[0] $$$ '+valueArray[0]);
                System.debug('valueArray[1] $$$ '+valueArray[1]);
            
            Integer numV = Integer.valueOf(valueArray[1]);
            for(sObject sObj : Database.query('SELECT Id FROM ' + valueArray[0] + ' WHERE CreatedDate < Last_N_days:' + Integer.valueOf(valueArray[1]) + ' limit 150')) {
                System.debug('sObj $$$ '+sObj);
                if(objectRecords.size() < 200*(500 - objectRecords.size()) + objectRecords.size()){ // Here 500 is batch size.
                    objectRecords.add(sObj);
                }
                else {
                    reRun = true;
                    break;
                } 
            }
        }
        if(objectRecords != NULL && objectRecords.size()>0){
            objectRecords.sort();
            try{
                database.delete(objectRecords, false);
            }
            catch(Exception ex){
                System.debug('Exception occurred '+ex);
            }
        } 
    }
    
    global void finish(Database.BatchableContext ctx) {
        if(reRun) {
            Database.executebatch(new SampleBatchClass());
        }
        if(!reRun) {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            
            AsyncApexJob a = [SELECT a.TotalJobItems, a.Status, a.NumberOfErrors,
                              a.JobType, a.JobItemsProcessed, a.CompletedDate, a.ApexClassId  
                              FROM AsyncApexJob a WHERE id = :ctx.getJobId()];
            
            String sandboxUrl1=String.valueOf(System.Url.getOrgDomainUrl());
            String sandboxUrl2=sandboxUrl1.replace('Url:[delegate=','');
            String sandboxUrlValue = sandboxUrl2.replace(']','');
            
            mail.setToAddresses(setToAddressesList);
            mail.setCcAddresses(setCcAddressesList);
           // mail.setReplyTo(Label.CEP_Set_Reply_To_Email_Address);
            mail.setSenderDisplayName('Scheduled Batch Apex Processing');
            mail.setSubject('Batch Apex Processing status for 7 days old records: '+a.Status);
            String htmlBody = '';
            //open table..
            htmlBody ='Hi, <br/> <br/> As part of Platform Environment Management, the scheduled batch apex job has processed & 
            cleared all the test data which are created 7 days ago for specific objects.<br/><br/>';
            htmlBody +='Please find below details of scheduled batch apex job.<br/><br/>';
            htmlBody += '<table border="1" style="border-collapse: collapse">';
            htmlBody += '<tr><td>' + '  &nbsp; Apex Job Processing status  &nbsp; ' + '</td><td>' + ' &nbsp;'+ a.Status + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Total Batch Apex Job Items  &nbsp;' + '</td><td>' + ' &nbsp;' +  a.TotalJobItems + ' &nbsp;' +  '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Job Item processed  &nbsp;' + '</td><td>' + ' &nbsp;' + a.JobItemsProcessed + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Number Of Failures   &nbsp;' + '</td><td>' + ' &nbsp;' +  a.NumberOfErrors + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Job Completed Date and Time  &nbsp;' + '</td><td>' + ' &nbsp;' +  a.CompletedDate + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Job Type  &nbsp;' + '</td><td>' + ' &nbsp;' + a.JobType + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Apex Class Id  &nbsp;' + '</td><td>' + ' &nbsp;' + a.ApexClassId  + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Scheduled Apex Class Name  &nbsp;' + '</td><td>' + ' &nbsp;' + 'CEP_BatchDelete7DaysOldRecords'  + ' &nbsp;' + '</td></tr>';
            htmlBody += '<tr><td>' + '  &nbsp; Sandbox URL  &nbsp;' + '</td><td>' + ' &nbsp;' + sandboxUrlValue + ' &nbsp;' + '</td></tr>'; 
            htmlBody += '</table>'; //close table
            htmlBody +='<br/><br/>Thank you.<br/>';
            
            mail.setHTMLBody(htmlBody);
            Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
        }  
    } 
    
    global void execute(SchedulableContext SC) {
        Database.executebatch(new SampleBatchClass());
    }
}

 24. Apex trigger to prevent duplicate Account records. 
 Trigger preventDuplicateAccount(before insert, before update) {
  Set < String > setAccountNames = new Set < String > ();
  Map < String, Account > mapAccount = new Map < String, Account > ();
  for (Account acc: Trigger.new) {
   setAccountNames.add(acc.Name);
  }
  for (Account acc: [SELECT Id, Name FROM Account 
WHERE Name IN: setAccountNames]) {
   mapAccount.put(acc.Name, acc);
  }
  for (Account acc: Trigger.new) {
   if (mapAccount.containsKey(acc.Name)) {
    acc.Name.addError('Account name already exists for Account id ' + mapAccount.get(acc.Name) + '.');
   }
  }
 }


trigger AccountDuplicateTrigger on Account (before insert, before update) {
    Set<String> accountNameSet = new Set<String>();
    for(Account acc: [SELECT Name FROM Account]){
        accountNameSet.add(acc.Name);
        System.debug('accountNameSet @@ '+accountNameSet);
    }
    for(Account acc: Trigger.new){
        if(accountNameSet.contains(acc.Name)){
            System.debug('accountNameSet.contains(acc.Name) '+acc.Name);
            acc.Name.addError('An Account exists with same name ! ');
        }
    }
    }


 25. Trigger to count, sum child records and display in parent record 
        in case of lookup relationship.
 
        
 Trigger ContactCountTrigger on Contact(After insert, After Delete,  After Undelete, After Update) {
  Set < Id > setAccountIds = new Set < Id > ();
  if (Trigger.isInsert || Trigger.isUndelete || Trigger.IsUpdate) {
   for (Contact con: Trigger.new) {
    setAccountIds.add(con.AccountId);
   }
  }
  if (Trigger.isDelete) {
   for (Contact con: Trigger.old) {
    setAccountIds.add(con.AccountId);
   }
  }
  List < Account > listAccs = [Select id, name, number_of_contacts__c,
   (Select id from contacts) from Account
   where Id in: setAccountIds
  ];
  for (Account acc: listAccs) {
   acc.number_of_contacts__c = 

acc.contacts.size();
  }
  update listAccs;
 }


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





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

<address>

    <name>Kirk Stevens</name>

    <street1>808 State St</street1>

    <street2>Apt. 2</street2>

    <city>Palookaville</city>

    <state>PA</state>

    <country>USA</country>

</address>

The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request.

public class DomDocument {

    // Pass in the URL for the request

    // For the purposes of this sample,assume that the URL

    // returns the XML shown above in the response body

    public void parseResponseDom(String url){

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        // url that returns the XML in the response body

        req.setEndpoint(url);

        req.setMethod('GET');

        HttpResponse res = h.send(req);

        Dom.Document doc = res.getBodyDocument();

        //Retrieve the root element for this document.

        Dom.XMLNode address = doc.getRootElement();

        String name = address.getChildElement('name', null).getText();

        String state = address.getChildElement('state', null).getText();

        // print out specific elements

        System.debug('Name: ' + name);

        System.debug('State: ' + state);

        // Alternatively, loop through the child elements.

        // This prints out all the elements of the address

        for(Dom.XMLNode child : address.getChildElements()) {

           System.debug(child.getText());

        }

    }

}


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

trigger AccountTrigger on Account (before insert, before update, before delete,

                                   after insert, after update, after delete, after undelete) 

{

    Boolean run = true;

    if(run == false){

        if(Trigger.isBefore){

            if(Trigger.isInsert) {

                AccountTriggerHandler.beforeInsert(Trigger.new);

            }

            

            if(Trigger.isUpdate){

                AccountTriggerHandler.beforeUpdate(Trigger.new);

            }

            

            if(Trigger.isDelete){

                AccountTriggerHandler.beforeDelete(Trigger.old);

            }

        }

        

        if(Trigger.isAfter){

            if(Trigger.isInsert){

                AccountTriggerHandler.afterInsert(Trigger.new);

            }

            

            if(Trigger.isUpdate){

                AccountTriggerHandler.afterUpdate(Trigger.new);

            }

            

            if(Trigger.isDelete){

                AccountTriggerHandler.afterDelete(Trigger.old);

            }

            

            if(Trigger.isUndelete){

                AccountTriggerHandler.afterUndelete(Trigger.new);

            }

        }    

    }

}


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

public class AccountTriggerHandler {

    

    //Update Account Description when Account is created.

    public static void beforeInsert(List<Account> newAccounts) {

        for(Account acc: newAccounts){ 

            acc.Description = 'Test Description';

        }

    }

    

    //Update Account Rating based on Account Industry

    public static void beforeUpdate(List<Account> newAccounts) {

        for(Account acc: newAccounts){ 

            if(String.isNotBlank(acc.Industry)){ 

                if(acc.Industry == 'Banking'){

                    acc.Rating = 'Hot';

                }

                else if(acc.Industry == 'Agriculture'){

                    acc.Rating = 'Warm';

                }

                else {

                    acc.Rating = 'Cold';

                } 

            }

        }

    }

    

    // Restrict the deletion of Account if Industry = 'Banking'.

    public static void beforeDelete(List<Account> oldAccs) {

        for(Account acc: oldAccs){

            if(String.isNotBlank(acc.Industry) && acc.Industry == 'Banking'){

                acc.addError('Account cannot be deleted if Industry is Banking.');

            }

        }        

    }

    

    //Create Contact record when Account is created.

    public static void afterInsert(List<Account> newAccounts) {

        List<Contact> listContact = new List<Contact>();

        for(Account acc: newAccounts){

            Contact con = new Contact();

            con.LastName = acc.Name + ' Contact';

            con.AccountId = acc.Id;

            listContact.add(con);

        }

        if(!listContact.isEmpty()){

            try{

                Database.insert(listContact, false);

            }

            catch(Exception e){

                System.debug('Exception '+e);

            }

        }        

    }

    

    //Update Contact record when Account is updated.

    public static void afterUpdate(List<Account> newAccounts) {

        Map <Id, Account> mapAccount = new Map <Id, Account>();

        List <Contact> listContact = new List <Contact>();

        

        for (Account acct: newAccounts){

            mapAccount.put(acct.Id, acct);

        }

        listContact = [SELECT Description, AccountId FROM Contact 

                       WHERE AccountId IN: mapAccount.keySet()];

        

        if (listContact.size() > 0) {

            for (Contact con: listContact) {

                con.Description = mapAccount.get(con.AccountId).Description;                

            }

            update listContact;

        }

    }

    

    //Send email notification when Account is deleted.

    public static void afterDelete(List<Account> oldAccounts) {

        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();

        for (Account acc : oldAccounts) {

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

            String[] toAddresses = new String[] {'sohelsalesforcetraining@gmail.com'};

                mail.setToAddresses(toAddresses);

            mail.setSubject('Your Account is deleted');

            String body = 'Your Account is deleted successfully from Salesforce org.';

            mail.setHtmlBody(body);

            mails.add(mail);

        } 

        Messaging.sendEmail(mails);

    }

    

    // Update Account Name when Account is undeleted/restored.

    public static void afterUndelete(List<Account> newAccounts) {

        List<Account> listAccount = new List<Account>();

        for(Account acc : [SELECT ID, Name, Description from Account where Id IN : newAccounts]){ 

            acc.Name = acc.Name + ' - Undeleted';

            acc.Description = 'This Account is undeleted by Apex Trigger';

            listAccount.add(acc);

        } 

        update listAccount;

    }

}

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

Trigger ContactTrigger on Contact(after , after update, after delete, after undelete){

Boolean maxContact = false;

List<CustomRecord__c> crList = new List<CustomRecord__c>();

List<Account> accList = new List<Account>();

Set<Id> accountIdSet  = new Set<Id>();

if(Trigger.isAfter){

if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){

for(Contact con: Trigger.new){

if(con.AccountId != NULL){

accountIdSet.add(con.AccountId);

}

}

}

if(Trigger.isDelete){

for(Contact con: Trigger.old){

if(con.AccountId != NULL){

accountIdSet.add(con.AccountId);

}

}

}

}

accList = [SELECT Id, CountOfCOntacts__c, (SELECT Id FROM Contacts) FROM Account WHERE AccountId IN: accountIdSet];

if(!accList.isEmpty()){

for(Account acc: accList){

acc.CountOfCOntacts__c = acc.contacts.size();

if(acc.contacts.size() >='100'){

maxContact = true;

}

}

}

if(maxContact != TRUE){

if(!accList.isEmpty()){

try {

Database.update(accList, false);

}

catch(Exception ex){

System.debug('Exception '+ex.getMessage());

}

}

}

else {

for(Contact con: Trigger.new ){

CustomRecord__c c = new CustomRecord__c;

c.Account__c = con.AccountId;

c.Contact__c = con.Id;

crList.add(c);

}

insert crList;

}

}

No comments:

Post a Comment