Tuesday, September 22, 2020

Different ways of calling Apex Class from Lightning Web Component

 

To call apex from Lightning Web Component, you need to import the apex method in JavaScript class.

There are three ways by which we can call an apex from LWC-

·       Wire a property

·       Wire a function

·       Call apex imperatively

The syntax of importing apex class in JavaScript is like-

import apexMethodName from ‘@salesforce/apex/Namespace.ClassName.apexMethodName’;

@AuraEnabled annotation must be use to expose an apex class to LWC. The apex method must be static global/public

Wire a Property:

The apex class must be declared with @AuraEnabled(cacheable=true) when using wire service to call apex. Making a method cacheable improved the component performance by showing the client side cached data instead of invoking server side controller.

 

Scenario: calling apex method without parameter

In this scenario, the syntax to call apex is

@wire (<METHOD_NAME>)<WIRE_PROPERTY>

@wire indicates that you are using wire service to call Apex and to call the method before you use @wire decorator, import the method like-

import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';

WIRE_PROPERTY is the private property of the component which received the returned result of the wire service. There are two properties within the wire property. The data property stores the returned result and error property return in case any error.


import { LightningElement,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';
export default class AccountSearchLwc extends LightningElement {
    @wire(getAccountList)
    accounts;
}

Apex Class:

public with sharing class AccountSearchLwcController {
    @AuraEnabled(cacheable=true)    
    public static List<Account> getAccountList() {
    string queryStr = 'select id,name,Phone,Email__c, Accountnumber from Account';
        List<Account> listofAccounts =Database.query(queryStr);
        
        return listofAccounts;
    }

html:

<template>
    <div class="slds-var-m-around_medium">
        <template if:true={accounts.data}>
            <template for:each={accounts.data} for:item="account">
                <p key={account.Id}>{account.Name}</p>
            </template>
        </template>
        <template if:true={accounts.error}>
            <p>SOME ERROR OCCURS </p>
        </template>
    </div>
</template>

Scenario: Call apex with parameter

Here the apex method takes an input and returned the list of account where account name contains the input parameter.

To call the apex method with parameter using @wire service, the syntax is:

@wire(<METHOD_NAME>,{<Apex_Class_Paramerter>:<INPUT_PARAMETER_FROM_LWC>})

<WIRE_PROPERTY>

Here we need to use ‘$’ symbol with the JavaScript parameter to indicate that its dynamic and reactive which means if value of the searchKey parameter changes in LWC then the template will be rendered in html.

import { LightningElement,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';
export default class AccountSearchLwc extends LightningElement {
    searchKey='Josh';
    @wire(getAccountList,{searchKey:'$searchKey'})
    accounts;
}

APEX Class:

public with sharing class AccountSearchLwcController {
    @AuraEnabled(cacheable=true)    
    public static List<Account> getAccountList(String searchKey) {
        string searchStr = '';
        if (searchKey!='') {
            searchStr = ' where name LIKE \'%'+searchKey+'%\'';
        }
        string queryStr = 'select id,name,Phone,Email__c, Accountnumber from Account';
        queryStr = queryStr+searchStr;
        List<Account> listofAccounts =Database.query(queryStr);
        
        return listofAccounts;
    }
}

Wire a function:

Use wire a function when you want to operate on return data. This @wire service as function retuned the result as an object with either data property or error property. If data property is there then it is assigned to this.accounts and for error it is assigned to this.error. If the value of this property changes, then the template rerenders.


import { LightningElement,track,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';
export default class AccountSearchLwc extends LightningElement {
    searchKey='Josh';
    accounts;
    error;
    @wire(getAccountList,{searchKey:'$searchKey'})
    Wiredaccounts({error,data}){
If(data){
            this.accounts= data;
 	     this.error = undefined;
}else if(error){
      this.error = error;
      this.data = undefined;
}	
    }
}

Call Apex Imperatively:

Apex needs to call imperatively when you need to control when the invocation needs to be there for example, on-change event or button click event. Here in this example, the getListOppty() JS method gets  called on click of a button which in turn call the getOpptyList() apex method and return list of opportunity.

import { LightningElement,track,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';

export default class AccountSearchLwc extends LightningElement {
    opptyList;
    error;
    
    getListOfOppty(){
        getOpptyList() //getOpptyList() is the apex Method Name
        .then(result=>{
            this.opptyList = result;
            this.error = undefined;
        })
        .catch(error=>{
            this.opptyList = undefined;
            this.error = error;
        });      
    }
}

Thursday, September 17, 2020

Integrating two Salesforce Org Using Named Credential



Security is the one which every customer concern about while implementing SF application and integrating with external system. So if we want to hide the external url, username, password while connecting external system, then Named Credential is something that you need to implement.

Named credential specifies the call out end point url and authentication in one definition. It doesn’t require to add end point URL in Remote Site settings. Named credential support two types of authentication protocol Basic User Name/Password Authentication and OAuth 2.0 protocol.

In this blog article, we will be going to connect two salesforce Org using Named Credential and OAuth 2.0 authentication protocol.

Following steps, we need to perform –

Steps#1: Create connected App in destination org

Steps#2: Create AuthProvider in source Org

Steps#3: Create named Credential in source Org

Steps#4: Write apex in source Org to fetch data from destination Org.

 

Connected App in destination Org:

A connected app is a framework that enables an external application to integrate with Salesforce using different authentication protocol. Please check salesforce article about Connected App

 

Go to SetupàCreateàAppsà New (Connected App)

Checked Enable OAuth Settings and select the OAuth scope. OAuth scope is basically the level access that connected App needed for the integration.



Put callback url as dummy url which we will change later.

 

Create Auth Provider in Source Org:

Go to SetupàSecurity Controls à Auth. Provider à New



Copy the Consumer Key/Consumer Secret of the connected app created in destination org.

The Authorization end point should be -

https://<base url of the destination org>/services/oauth2/authorize

and Token Endpoint Url should be-

https://<base url of the destination org>/services/oauth2/token

Default Scope is the permission scope which need to be enter. There should be a space between two scope.

Upon clicks on save, it will generate call back url-

Copy the call back url and paste the same in the connected App in destination Org.


Named Credentials in source Org:

Go to SetupàSecurity Controls à Named Credentials à New Name Credential

Select Authentication Protocol as OAuth 2.0 and choose Authentication Provider which has been created in earlier steps. On clicks on save the page will redirect to destination Org where you need to login to verify the authentication.

 



Write Apex to connect destination org and fetch data:

Now calling an external system is only 5-6 lines code. No user name, No password, No end point URL. You only need to specify the named credential name which will take care the authentication.

Set httpsRequest endpoint as-

callout:<NAMED_CREDENTIAL>/<SOME_PATH>






Thursday, June 4, 2020

Secure Password Input in ANT

While doing ANT deployment in salesforce, in general we have to store user name and password in build.properties file which is also a big concern for organization in terms of security. Since we are storing the credential in a file, so there may have chance of unauthorized person to access SF due to inappropriate handle of the local machine.

So I am trying to find out a solution in which we do not need to store username and password in build.properties.

We will do some modification in the build.xml file which will eventually ask user to enter user name and password in every ANT command.

Added the following script withing the every <target> tag in build.xml file.

            <input message="User Name :" addproperty="username"/>
            <input message="Password :" addproperty="password">
            <handler type="secure"/>
            </input>

So the build.xml file will looks like-


Note that you do not need to store the credential in build.properties file.


Now run your ANT command in command prompt-

Here I am running ant deployCode command to deploy the package.xml

Then it will prompt for user name inputà input your user name and press Enter

Input your password and press Enter

Here the password that you will type will not be visible.

 



Tuesday, May 5, 2020

PMD Source code analyzer | Automated Apex Code Review

What is PMD?
PMD stands for Programming Mistake Detector is an open source code analyzer tool which is used to generate code quality report.
Here we will discuss about how PMD can be used to generate code quality report for standalone application.
Step 1:
Download PMD from here à Unzip the download file
Step 2:
Now Retrieve the code through package.xml from workbench-
Now unzip the source code after downloaded from workbench.
Step 3:
Run the below pmd command to generate the report




You can define the rule set as per your need or else you can use the built-in rule set. See the below table for build in rule set path
Rule Name
Description
Rule Set Path
Best Practices
Rules which enforce generally accepted best practices.
Category/apex/bestpractices.xml
Code Style
Rules which enforce a specific coding style.
Category/apex/codestyle.xml
Design
Rules that help you discover design issues.
Category/apex/design.xml
Documentation
Rules that are related to code documentation
Category/apex/documentation.xml
Error Prone
Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.
Category/apex/errorprone.xml
Performance
Rules that flag suboptimal code.
Category/apex/performance.xml
Security
Rules that flag potential security flaws.
category/apex/security.xml


Sunday, May 3, 2020

SFDX Setup – Dev Hub | Scratch Org | VS Code IDE


Salesforce DX will provide you a series of new tools and features that will change the way developer build Salesforce application.
Salesforce DX introduce a new type of environment which is called as ‘Scratch Org’. To create this scratch org, you need to enable the org as Dev Hub. The scratch will be the copy of Dev Hub though you can configure which parts of your org copy over and it can be disposable over a specified period of time.

Here I will setup SFDX in my Org and will create a Scratch org to implement a lightning component using VS Code IDE and push the component from VS Code IDE to Target org.

Step 1:

Enable Deb Hub in your Salesforce Org. Go to Setup à Development à Dev Hub and click Enable. Once you enable Deb Hub, you cannot disable it again.













Step 2:

Download and Install VS Code IDE.
Download and Install Command Line Interface (CLI). Make sure you have checked the checkbox to set the Salesforce CLI bin path in PATH environment variable while installing CLI.
Open command prompt and run sfdx to check whether CLI installed properly or not

Step 3:

Open Visual Studio Code IDE and Install Salesforce Extension Pack extension.


Step 4:

To create a project in VS Studio Code IDE-
Press CTRL+SHIFT+P
Use SFDX:Create Project, System will ask for SFDX Project Name and then choose the directory where you want to save the project and clicks on ‘Create Project’



Step 5:
Now we are going to integrate the VS Code project to Dev Hub.
Press CTRL+SHIFT+P à SFDX:Authorize a Dev Hub
VS Studio Code IDE will redirect to login Dev Hub and after successfully login, you will get success message in VS Studio for Authorizing a Dev Hub


Step 6:
Now you need to create a Scratch Org by using –
CRTL+SHIFT+P à SFDX:Create a default Scratch Org..


Choose default scratch Org definition JSON


Put a scratch Org Alias name-


Enter the no of day you want to work in the scratch Org. You can choose between 1-30 days. After that no. of days the scratch org will be expired.


Step 7:
Once you get Salesforce CLI message that scratch org has been created, you need to run the below command to open the scratch org-
sfdx force:org:open


So as of now we have created a scratch org from a Dev Hub. Now we are going to create a lightning component in VS Code IDE and move the component to scratch org.

Step 8:
To create a lightning component, CTRL+SHIFT+P à SFDX:Create Lightning Component and give a name to lightning component.



Step 9:
Now we will push the lightning component from VS Code IDE to scratch Org.
Press CTRL+SHIFT+P à SFDX:Push Source to Default Scratch Org
You can see the push request status in Output window. Once push request is successful the same component will be available in the scratch Org to use.





Saturday, May 2, 2020

Salesforce ANT Deployment – Retrieve |Validate | Deploy


Setup the ANT into your system properly before going to use it. Please check here the ANT setup guide if you haven’t done it so far

Understanding build.xml | build.properties | package.xml

build.properties – you must update this file to specify the salesforce org credential in order to complete the ANT task in build.xml

build.xml – you must modify the build.xml file to indicate the location of ant-salesforce.jar file. Modify the path the of the ant-salesforce.jar in location attribute of <pathelement> in build.xml.


Package.xml – you need to update the metadata component in this xml file. package.xml is a collection of metadata components which are identifies by the programming interface.
Here are the steps that need to follow to retrieve code from source org and deploy the code in Target org-

Step#1
Update the build.properties file with source org credential and server url. For non-production org server url would be test.salesforce.com

Step#2
Modify the package.xml with the necessary component which needs to be deployed from source org to Target org.
Here we are going to deploy one Apex class (OrderHelper) and one Apex Trigger (OrderTrigger) to understand the process-


Step#3
Run the command ant retrieveCode in command prompt to retrieve the code from source org to local machine.

retrieveTarget=”codepkg” – This attribute indicates that the component mentioned in the package.xml will be retrieve to codepkg folder.




Step#4
As of now we have retrieved the component from Source org to local machine. Now we are going to push the same components to production.
Update the credential in build.properties with server url. To deploy into the production change the server url to Login.salesforce.com
Make sure that you have included the necessary test class in the package.xml within the <runTest></runTest> tag under <target name=”deployCode”> element.
testLevel=RunSpecifiedTests indicates that the command will run only specific test classes that are mentioned within <runTest> tag.


Step#5
Run the command ant deployCode .
To validate the component with test coverage use checkOnly attribute.
checkOnly=true indicates that the command will only validate with test class coverage (Similar to validate change set with run as specific test class)
checkOnly=false indicates that the command will validate and deploy the component to Target org.
You can also check the validation status in salesforce- Setup->Deploy->Deployment Status



Step#6
Now its time to Quick Deploy!
Copy the Request Id from command prompt and paste it in build.properties file as recentValidationId.


Now Run the ant quickDeploy command to deploy the recently validated components.



Congratulations! You have completed deployment using ANT deployment tool