Thursday, September 30, 2021

Queueable Apex

 First Batch:

global class BatchCalledThroughQueueable implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts {

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

        return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext bc, List<Lead> records){

    }

    global void finish(Database.BatchableContext bc){

    }

}

Second Queueable Class:

public class ExecuteBatchQueueableJob implements Queueable {

    public void execute(QueueableContext context) {

        try{

            BatchCalledThroughQueueable b = new BatchCalledThroughQueueable();

            Database.executeBatch(b, 200);

        }catch(Exception e){

            System.debug('@@@ Error Message : '+e.getMessage());

        }

    }

}

Third Batch:

global class BatchUpdate implements Database.Batchable<sObject>, Database.StatefulDatabase.AllowsCallouts {

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

            Note: Calling Queueable job for calling the next batchfor chaining.

                System.enqueueJob(new ExecuteBatchQueueableJob());

            return Database.getQueryLocator(query);

        }

    global void execute(Database.BatchableContext bc, List<Contact> records){

    }

    global void finish(Database.BatchableContext bc){

    }

}

Wednesday, September 15, 2021

Instance Refresh and find hardcode instance like : NA65, CA38 in entire org

 


To find hardcode instances like NA65, CA38 in the entire org. 

Need to check below in components and follow reference links :

1. Static Resources

2. Custom Button or Link (Javascript)

3. Email Template 

4. Remote site settings

5. Visualforce pages

6. Custom lables





Reference links:

Lightning Experience Configuration Converter: https://lightning-configuration.salesforce.com/

https://www.infallibletechie.com/2018/09/things-to-consider-during-salesforce.html

Wednesday, September 8, 2021

LWC NavigationMixin - Redirect to parent record and LWC Headless action redirection

1. Reference link for LWC Headless action:

NOTE: This headless action is supported only on the standard record page. - Not worked for community's ref link:  

https://help.salesforce.com/s/articleView?language=en_US&type=5&release=232&id=release-notes.rn_lwc_quick_actions.htm


2. Navigate to LWC or Aura component with RecordId

handleAction(event) {
  var RecIdJSON.stringify(event.detail.row.Id);
    this[NavigationMixin.Navigate]({
        "type": "standard__component",
        "attributes": {
            "componentName": "c__TestForm" //if LWC component : c___test_form
        },
        state: {
            c__recordId: JSON.parse(RecId)
        }
    });
}
(OR)
    renderedCallback() {
        this.sfdcBaseURL = window.location.origin;
    }
 
    handleAction(event) {
var RecIdJSON.stringify(event.detail.row.Id);
       this[NavigationMixin.Navigate]({
                 "type": 'standard__webPage',
                 "attributes": {
                   "url": this.sfdcBaseURL+'/lightning/cmp/c__TestForm?c__recordId='+JSON.parse(RecId)
                 }
             });
    }


3. Sample Redirection to parent record:

XML:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
            <actionType>ScreenAction</actionType>
        </targetConfig>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Contact</object>
            </objects>
        </targetConfig>
        <targetConfig targets="lightningCommunity__Default">
            <property name="recordId" type="String" label="Record ID" 
description="Should be set to {!recordId}" default="{!recordId}"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

 Template:

<template>
    <div class="slds-clearfix">
        <div class="slds-float_right">
            <lightning-button label="Return to Roadmap" 
onclick={navigateToViewAccountPage}></lightning-button>
        </div>
    </div>
</template>


JS

  import { LightningElementapiwire } from 'lwc';
  import { getRecord } from 'lightning/uiRecordApi';
  import { NavigationMixin } from 'lightning/navigation';
  
  const FIELDS = ['Contact.Account.Name',
'Contact.Account.Id']; 

  export default class ReturnToRoadmapLWC extends NavigationMixin (LightningElement){
      @api recordId;  

      connectedCallback(){
        console.log('recordid========='+this.recordId);
      }

      //Wire the output of the out of the box method getRecord to the Contact object
      @wire(getRecord, { recordId: '$recordId'fields: FIELDS })
      Contact;
  
      //Navigate to Account record from Contact
      navigateToViewAccountPage(event) {
        var AccountName this.Contact.data.fields.Account.value.fields.Name.value;
        var AccountId this.Contact.data.fields.Account.value.fields.Id.value;            
          console.log('Contact Account name ========='AccountName);
          console.log('Contact Account ID ========='AccountId);
        this[NavigationMixin.Navigate]({
            type: 'standard__webPage',
            attributes: {
              url: '/'+AccountId
                //url: '/hello/s/testurl/'+AccountId+'/'+AccountName
            }
        });
      }
  }

Thursday, July 29, 2021

Date.ValueOf not accepting null

 String str = null;

 Date d = Date.valueOf(str);

I am getting the following error when running the above snippet in Anon Apex.


Line: 2, Column: 1


System.NullPointerException: Argument cannot be null.


Resolution:  Using Ternary Operator we can fix the null check

Date d = String.isBlank(str)  ?  null  : Date.valueOf(str);

Thursday, July 1, 2021

Salesforce to Amazon s3 bucket Integration


Pre Requisites:


Bucket name: testbucket1

 

Region: us-east-2

 

Access key ID: XXXXXXXXXXXXXXXXXX

 

Secret access key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX



NOTE

1. Aws s3 storage server, storing the data only in the file format (Ex: Upload-Test-3.xml).

2. PUT is used to create the record or update records in s3 bucket

3. Host header is followed by bucket, region, and base URL (Ex:s3.us-east-2.amazonaws.com).



1. Insert the Data into Amazon s3 bucket through XML Payload

public  class AWSS3 {

    public  void uploadToAmazonS3() {   

String xmlStringxmlRes= '<?xml version="1.0" encoding="UTF-8">'+

                                '<my:myField>'+

                                '<my:LANID>12345678910</my:LANID>'+

                                '</my:myField>';

 Blob xmlContentBlob = Blob.valueOf(xmlStringxmlRes);


 String attachmentBody = EncodingUtil.base64Encode(xmlContentBlob);

 String formattedDateString = Datetime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');

 String key = 'XXXXXXXXXXXXXXXXX'; //Access key ID

 String secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //Secret access key

//https://testmay21.s3.us-east-2.amazonaws.com/

 String bucketname = 'testmay21'; //Bucket Name

 String host = 's3.us-east-2.amazonaws.com';

 String method = 'PUT'; //Create a file in Amazon s3 bucket

 String filename = 'Upload-Test-3.xml'; //Give any Name

 String fileType = 'text/xml'; //text/xml


 HttpRequest req = new HttpRequest();

 req.setMethod(method);

 req.setEndpoint('callout:AWS_S3' + '/' + filename); //Named credentials (Refer below 'Screenshot')

 req.setHeader('Host', bucketname + '.' + host);

 req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));

 req.setHeader('Content-Encoding', 'UTF-8');

 req.setHeader('Content-type', fileType);

 req.setHeader('Connection', 'keep-alive');

 req.setHeader('Date', formattedDateString);

 req.setHeader('ACL', 'public-read-write');

 req.setBodyAsBlob(EncodingUtil.base64Decode(attachmentBody));


 Http http = new Http();

 HTTPResponse res = http.send(req);


 System.debug('>>>> The response');

 System.debug(res);

 System.debug('>>>> The body');

 System.debug(res.getBody());

 System.debug('>>>> Status code');

 System.debug(res.getStatusCode());

 System.debug('>>>> Finished method');

    }

}

Screenshot




2. Get data from the amazon s3 bucket.


Endpoint Url : https://s3.us-east-2.amazonaws.com/buckename/Upload-Test-3.xml

Authorization : 






Reference links:



Friday, June 11, 2021

Salesforce Sample Rest API using Authentication

    

Salesforce Sample Rest API using Authentication:


   HTTPRequest r = new HTTPRequest(); 

    r.setEndpoint('https://test.com');

    Blob headerValue = Blob.valueOf('username' + ':' + 'password');

    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);

    r.setHeader('Authorization', authorizationHeader);

    r.setHeader('Content-Type','text/xml;charset=UTF-8'); //application/json

    r.setMethod('GET'); //POST,PUT..

    r.setBody(strSetBody);

    HTTP h = new HTTP(); 

    HTTPResponse resp = h.send(r);

    system.debug('body===>'+resp.getBody());

    system.debug('getStatusCode==>'+resp.getStatusCode());

    system.debug('getStatus'+resp.getStatus());

Convert Encryption key to string (Decode the string)

Convert Encryption key to string or Decode the string or Covert MD5 hash to string :


Blob targetBlob = Blob.valueOf('ad89a9b94b5efd734e0c75a1480c20a4AD64439');

Blob hash = Crypto.generateDigest('MD5', targetBlob);

string hexDigest = EncodingUtil.convertToHex(hash);

system.debug('hexDigest==>'+hexDigest);

CSS Styling

Styling: 1. Inline Styling: < div style = "font-size: 2rem;font-weight: 400;" > Good Evening </ div > 2. Usi...