Saturday, 15 July 2023

Duplicate id in list

 

Error 'System.ListException: Duplicate id in list' in Apex :

list can hold duplicate values, but if you try to add duplicate sObject IDs in the list and then update the list you'll get the error. 

Duplicate id in list' in Apex.

List should not hold multiple instances of the same object.

Suppose you are trying to update Account record 

id aid = '0010o000030nWBe';

list <account> al = new list <account>();

for(account a : [select id from account where id ='0010o000030nWBe']){
account acc = new account(id = aid);
    al.add(a);
    al.add(acc);
}
update al;

You will receive error '


To resolve this, we need to create a map and then update

id aid = '0010o000030nWBe';
list <account> al = new list <account>();

for(account a : [select id from account where id ='0010o000030nWBe']){
account acc = new account(id = aid);
    al.add(a);
    al.add(acc);
}
//update al;
map<id,account> accmap = new map<id,account>();

//put all the values from the list to map. 
accmap.putall(al);
if(accmap.size()>0){
update accmap.values();
}

Saturday, 28 January 2023

Holiday Consideration in salesforce

 

Recently, I came across one requirement, where we need to consider holiday.

Suppose, we have one custom object, which has SubmittedDate field, DueDate field.

We have to complete all cases before DueDate, but suppose, if there is any company holidays, we get less time to complete Cases.

Sol:

First we have create Business Hours. To create Business hours, you can search in quick find box “business hours”. On Satuday and Sunday, we don’t have working hours. So , we have metioned “no hours”.



Then we have to create Holidays and associate with business hours.




Suppose, we are submitting the case on 27th January 2023, the due date should be 03rd February 2023, without considering Holidays. It should be 5 business days mainly, excluding holidays and weekends.

With Holiday consideration, the duedate will be 06th February. As, 30th January( Test1), i have considered holiday.




addGmt(businessHoursId, startDate, intervalMilliseconds) :

Adds an interval of milliseconds from a start Datetime traversing business hours only. Returns the result Datetime in GMT.

Wednesday, 14 September 2022

Basic Integration interview Questions

 What is integration? Why we need integration in Salesforce?

Integration is a process of connecting two applications. Enterprise system uses many applications, many or most of which are not designed to work with one another out of the box. Each application can have data, business logic, presentation, and security layers, all of which are possible targets for integration.

 Integration comes in picture when some interaction is required from external system. Let us take example, we want to validate address of account record. This can be done using google address validation or smarty street API integration.

What Is Webservices?

Webservices is a functionality or code which helps to us to do integration. Web services are open standard (XML, SOAP, HTTP, etc.) based web applications that interact with other web applications for the purpose of exchanging data.

There are two types of Webservices:

·       SOAP web services.

·       RESTful web services.

What is REST API?

A REST API is also known as RESTful API. It stands for representational state transfer. REST API has a lightweight request and response framework. It is a simple, easy-to-use, and powerful web service based on RESTful principles. REST API supports both XML and JSON. The protocol for REST is HTTP.

 @RestResource(urlMapping='/your URL/*')

 Methods used in REST:

@HTTPDELETE : The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent, and deletes the specified resource.  

To use this annotation, your Apex method must be defined as global static.

 @HTTPGET : The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource. These are some considerations when using this annotation:

·        To use this annotation, your Apex method must be defined as global static.

·        Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.

 @HTTPPATCH : The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource.

To use this annotation, your Apex method must be defined as global static.

 @HTTPPOST : The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent, and creates a new resource.

To use this annotation, your Apex method must be defined as global static.

 @HTTPPUT : The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent, and creates or updates the specified resource.

To use this annotation, your Apex method must be defined as global static.

  What is Remote Site Settings?

Before any apex callout can call an external site, that site must be registered in the remote site settings page or the callout fails. Salesforce prevents callout to unauthorized network access.

  What is Named Credentials?

Using Named credentials, We can make callout to external system without supplying username and password. A Named credentials specifies the URL of a callout endpoint and its required authentication parameters in one definition.

  What is SOAP API?

SOAP is the Simple Object Access Protocol which supports XML only. you can create, get, delete, and update records using the SOAP API (Simple Object Access Protocol API). Any language that supports web services can utilize the SOAP API. Here are the features of SOAP API.

·        Relies on XML and Schema.

·        Strongly types messaging framework.

·        Operations and its XML structure of request and response defined.

·        Communicated through WSDL.

·        The underlying transport protocol can be sent over almost any protocol, server-side such as HTTP, SMTP, TCP, or JMS.

  Difference Between REST and SOAP.

 

REST

SOAP

 

REST is not a protocol; it is an architectural style.

SOAP is a protocol.

REST uses URL to expose the web service.

SOAP uses WSDL class to expose the web service

REST allows different data formats: XML, JSON, plain text.

SOAP Allows Only XML format

REST requires less bandwidth than SOAP.

SOAP requires more bandwidth than REST.

RESTful services inherit security measure from underlying transport layer

SOAP uses its own security measures. SOAP is based on standardized Web service security. Thus, better secured compared to REST. SOAP is more reliable in terms of security than REST

 What is Connected App?

A connected app is a framework that enables an external application to integrate with Salesforce using APIs and standard protocols, such as SAML, OAuth, and OpenID Connect. Connected apps use these protocols to authenticate, authorize, and provide single sign-on (SSO) for external apps.

 What is OAuth?

OAuth is short for open authorization. OAuth 2.0 is a framework that allows for a secure way for systems to establish trust with one another. The end goal is to obtain an access token that can be used by to access protected resources without ever providing your username or password to the other system.

How Many Callouts To External Service Can Be Made In A Single Apex Transaction?

Governor limits will restrict a single Apex transaction to make a maximum of 100 callouts to an HTTP request or an API call.

What Is Call In And Call Out?

Call In is used to exposing our webservices to another users Call Out is used to invoking or consuming our webservices to others.

What is JSON ?

JSON stands for JavaScript Object Notation. JSON is light weighted than XML.  When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

 

 

Friday, 2 September 2022

Salesforce lightning flow

                            LIGHTNING FLOW

What is Flow?

The Salesforce Flows are an automated application that captures and records all data and takes necessary actions accordingly. It’s an automated application that collects data and performs the required steps in the system.

What is Flow Builder?

Flow Builder is a declarative way to automate complex business processes. For example, flow builders can automate processes that need creating/updating unrelated records, querying multiple objects, or running loops on the data. Flow builders can also access external systems. Flows can be further extended by adding Apex actions.

What are different types of flows?

1.      Screen Flow: It can be called using a button or an action or displayed in a Lightning Page or the Utility Bar. It appears as a screen for the user to interact with. Screen flow cannot be automatically triggered.

 

2.     Record Triggered Flow: It begins when a record is created or updated.

3.     Auto launch Flow: These can be called by Apex, Process Builder, or another Flow.

4.     Scheduled Triggered Flow: It runs automatically on a recurring schedule. It is helpful for jobs performed frequently or on a schedule (once, daily, weekly).

5.     Platform event-triggered Flows: These are called when a platform event is received

 

What are elements in Flow?

Elements tab displays Interaction, logic, and data elements available for the flow. Each element is an action the flow can execute. New elements can be created from the Elements Tab.

Interaction Elements

1.     Screen: Screen element / User interface for the flow. The screen can be used to display information or can be used to collect data from the user. This element is available only in Screen Flows.

2.     Actions: Actions are external actions that further extend the functionality of the flow. Some examples for actions – Apex, Send emails, etc.

3.     Subflow: A flow can initiate another flow.

Logic Elements

1.     Decisions: Decision split the flow depending on the data that’s being sent through the decision element.

2.     Assignments: Assignments give a value to a variable.

3.     Loops: Loops handle multiple variables at once using collections.

Data elements

Data elements allow the flows to fetch, create, update or delete records in the database. The elements include Get Record, Create Record, Update Record, and Delete Record. Get Record is used to fetch record/s from the database. Create Record, Update Record, and Delete Record are used to activate the data in the database.

What is difference between flow and process builder?

  • Flows can be designed to trigger upon creation, update, or deletion of a record. Processes can trigger only for creation or updates to a record.
  • Flows allow you to add screens where users can enter data. Processes do not have this capability.
  • Flows can be paused by users, but processes run when the criteria is met and cannot be paused.
  • Process actions are executed in the order in which they appear in the process definition, but flows can have different and more complex orders of operations.
  • Flows can be designed to run either before or after a record has been saved to the database, but processes can only trigger after a record has been saved.
  • Flows can be built to cycle through multiple unrelated and related objects. Processes, however, are limited to the base object (opportunities, for example) and related objects (accounts).

·        The following actions are only available for processes: QUIP Actions, send survey invitation.

How to handle fault in Salesforce flow?

If any element is connected to second screen, it automatically becomes fault screen and we can use “$Flow.FaultMessage” on screen to show error message. output text can be added on screen with message something like “Sorry, an error occurred in the page. 

What is Flow interview in Salesforce?

A flow interview is a running instance of a flow. A flow is an application built by your administrator that asks you for inputs and does something in Salesforce based on those inputs.

 

 

 

Sunday, 3 July 2022

Salesforce Lightning Aura interview Questions Part-2

 

What are the different Lightning component bundles?

  • Component or Application - sample .cmp/.app - The only required resource in bundle contains markup for the component or app. Each bundle contains only one app or component resource.
  • Controller - .js - Contains client-side controller methods to handle events in the component.
  • Helper - .js - JavaScript functions that can be called from any JavaScript code in a component’s bundle
  • Style- .css - Contains styles for the component.
  • Documentation-. auradoc - A description, sample code, and one or multiple references to example components
  • Design- .design- Design time/ compile time properties of a lightning component. A lightning component can be published multiple times in a page. If we want the behaviour of the component to change with each publish, we use this. File required for components used in Lightning App Builder, Lightning pages, or Community Builder.
  • SVG(Scalable vector graphics)- .svg- Custom icon resource for components used in the Lightning App Builder or Community Builder.
  • Renderer- .js - Client-side renderer to override default rendering for a component. When the component is launching in the browser if we want to implement a different functionality or behaviour at runtime, we use this.

 

How to add lightning component in visualforce page?

Lightning component can be added to visualforce page using ltng:outApp

How can we subscribed to an event in lightning component?

Use <aura:handler> in the markup of the handler component.

What is aura:registerevent in lightning component?

A component registers that it may fire an event by using <aura:registerevent>.

 

What is the use of implements in lightning component?

implement is used to implement multiple interface in lightning component. e.g. flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId

What is lightning: or ui: in any Lightning Component?

lightning: and ui: are two namespaces for core lightning component. The lightning namespace components are optimized for common use cases.

 

How can we extend any component?

Lighting component can be extended using extensible=”true” attribute in aura:component

What is the purpose of a helper file in an Aura Component?

It's always a best practice to move the complete business logic in Lightning Components to a helper file and have the controller.js file just as a messenger.

When a component is used (or embedded) multiple times in another component or when it's embedded multiple times in any of the lightning entities (Lightning Pages, Lightning Record Pages etc) then the helper.js file of the component(though embedded multiple times) is loaded only once which in-turn will be shared by the components.

So the resources used to load the same file multiple times is saved and response time can be reduced by a fraction of a second. It basically enhances the user experience(UX).

what is lightning container?

The lightning:container component allows you to host content developed with a third-party framework within a Lightning component. The content is uploaded as a static resource, and hosted in an iFrame. The lightning:container component can be used for single-page applications only.

Which type of attribute we can use in lightning component to store fractional values?

Doubletype.

To form a container around a information related to single item or group of item what we need to use in lightning component?

  Lightning:card.

How to ensure field level security while working with lightning components?

Make use of Lightning:recordForm or Standard controller of lightning component (force:recordData).

How to use lightning component with salesforce mobile app?

Make a tab for lightning component and include this tab in Salesforce1 mobile navigation.

Suppose we have a requirement to create an account using a new button and some default values in the new account screen. How can we achieve this requirement?

We can make use of force:createRecord; it is an event that opens a page to create a record for a specific entity. 

createRecord : function (component, event, helper) {

    var createRecordEvent = $A.get("e.force:createRecord");

    createRecordEvent.setParams({

        "entityApiName": "ObjectApiName"

    });

    createRecordEvent.fire();

}

 Is Lightning an MVC framework?

No, it’s a component-based framework.

Can we access one lightning component inside another lightning component in salesforce?
Yes, we can.

Can we access one JavaScript controller method on another controller method in lightning component?
No, we cannot access them.

Can we access one JavaScript helper method on another helper method in lightning Component?
Yes, we can access using this keyword.



How to use static resources in Lightning Components/Application?
Using $Resource.yourNamespace__resourceName. 

How we can access Custom Label in Lightning?
Syntax : $A.get(“$Label.namespace.labelName”)

How to add a lightning button in Salesforce Lightning?
use the lightning button tag to add the button in the component.
Example:
<lightning:button variant="base" label="Base" title="Base action" onclick="{! c.handleClick }"/>

What is Lightning Locker?

Lightning Locker is a powerful security architecture for Lightning components. Lightning Locker enhances security by isolating Lightning components that belong to one namespace from components in a different namespace. Lightning Locker also promotes best practices that improve the supportability of your code by only allowing access to supported APIs and eliminating access to non-published framework internals.

How we can access apex method in Lightning?

@AuraEnabled helps to access methods in Lightning.

var action = component.get(actionName);

action.setParams({ v : val });

action.setCallback(this, function(response) {

     console.log(response.getReturnValue());

});

$A.enqueueAction(action);

Why do we use @AuraEnabled annotation?

Use @AuraEnabled on Apex class static methods to make them accessible as remote controller actions in your Lightning components.

Use @AuraEnabled on Apex instance methods and properties to make them serializable when an instance of the class is returned as data from a server-side action.

What is Lightning Data Service in Salesforce Lightning?

Use Lightning Data Service to load, create, edit, or delete a record in your component without requiring Apex code. Lightning Data Service handles sharing rules and field-level security for you. In addition to simplifying access to Salesforce data, Lightning Data Service improves performance and user interface consistency.

lightning:recordForm

Display, create, or edit records

lightning:recordViewForm

Display records with lightning:outputField

lightning:recordEditForm

Create or edit records with lightning:inputField

force:recordData

Display, create, edit, or delete records with granular customization.

What is the difference between bound and unbound expression?

Bound expression {!expression}: Any change to the value of the childAttr attribute in c:child also affects the parentAttr attribute in c:parent and vice versa. When we use a bound expression, a change in the attribute in the parent or child component triggers the change handler in both components.

Unbound expression {#expression}: Any change to the value of the childAttr attribute in c:child doesn’t affect the parentAttr attribute in c:parent and vice versa. Data updates behave as you would expect in JavaScript. Primitives, such as String, are passed by value, and data updates for the expression in the parent and child are decoupled.

Why we use of THIS CSS class?
All top-level elements in a component have a special THIS CSS class added to them. This, effectively, adds namespacing to CSS and helps prevent one component’s CSS from overriding another component’s styling. The framework throws an error if a CSS file doesn’t follow this convention.

What is aura:if tag and uses ?
aura:if evaluates the isTrue expression on the server and instantiates components in either its body or else attribute. Only one branch is created and rendered.

<aura:component>

    <aura:if isTrue=”{!v.truthy}”>

           True

           <aura:set attribute=”else”>

           False

           </aura:set>

    </aura:if>

 </aura:component>

How to ensure FLS while working with Lightning Component?

Lightning Data Services already ensures Field Level Security and we can also use the Apex using isAccessible, isCreateable, isDeleteable, isCreateable and etc methods of Schema class. We cannot validate them in JS controller so we do this in APEX if have written our custom code.

 What are different events fired during component rendering lifecycle?

During component rendering, there are several events which gets fired.

·        Init event – The component service that constructs the components fires the init event to signal that initialization has completed.

·        Render event – This event is called when component starts rendering. You can override this either by handling this event, or by creating custom renderer resource file.

·        After render – This event is called once rendering is completed.

 

How to get event source in JavaScript controller?

event.getSource() method is used to identify event source

How to set attribute value from JavaScript?

Use component.set() method to set an attribute value in JavaScript. Example:

<aura:attribute name=“greeting” type=“String” />

 

In JavaScript you can set attribute value like below:

component.set(“v.greeting”, “Hello World”);

How to get attribute value in JavaScript?

Use component.get() method to get an attribute value in JavaScript. Example:

<aura:attribute name=“greeting” type=“String” />

 

In JavaScript you can get attribute value like below:

var gettingValue = component.get(“v.greeting”);

What is component. Find() method and why is it being used?

component.find() method is used to find an element from component markup using aura:id. This method return complete element and can be used to set attribute values of element or performing any other operations like changing CSS classes etc.

<lightning:input aura:id=“nameInput”  value=“Madhu”/>


In JavaScript, you can dynamically change the value attribute of above lightning:input-

var inputElement = component.find(“nameInput”);

inputElement.set(“v.value”, “Gaurav”);

Why we use component.getEvent() method?

component.getEvent() method is used to get a reference of registered component event in component markup. Once the event is retrieved, same can be fired from JavaScript. Example:

<aura:registerEvent name=“onTileSelect” type=“c:TileSelectEvent”/>


You can get above component event in controller:

var tileSelectEvent = component.getEvent(“onTileSelect”);

tileSelectEvent.fire(); //fire the event

 

What are different ways to communicate between components?

If component hierarchy is same

·        Parent to Child Communication-

1.     Attributes can be used to create a binding between parent and child.

2.     Aura methods can be used if parent component wants to access a function in child component

 

Child to Parent Communication-

1.     Attributes can be used to create a binding between parent and child.

2.     Component event can be used to perform functionality in parent component based on an event in child component.

 

If components are in different hierarchy

Application events is the best solution for this type of communication.

 

What is the purpose of <aura: method/> tag ?

This tag is used to send data from the Parent Component to the Child Component.

What is Flexipage in lightning?

Flexipage represents the metadata associated with a lightning page.

How to call the parent component method from the child component without using events?

1.     Define aura:id of the child component in parent.

2.     Define <aura: method> in child component and it will link to method of child controller.

3.     Define a lightning :button on parent component and on click of this button get the reference of the child component as mentioned in step 1 & call aura: method as mentioned in step 2

What is Aura definition bundle?

A bundle contains an aura definition and its related resources. The definition can be a component, application, event, interface or a token collections.

How can we display loading spinner in lightning component?

Spinners are CSS loading indicators that should be shown when retrieving data or performing slow computation. lightning: spinner displays an animated spinner image to indicate that a request is loading.

What is difference between Visualforce and lightning components?

Visualforce components are page centric and most of the work is done on server. Lightning is designed from the component up, rather than having the concept of a page as its fundamental unit. Lightning component are client side centric which makes them more dynamic and mobile friendly.

What is SLDS?

Salesforce lightning design system helps you to build applications with the look and feel of lightning experience without writing a single line of CSS. SLDS is a CSS framework that gives you access to the icons, colour palettes, and font that your developers use to create lightning experience.

What do you mean by promises?

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

·        A Promise has four states: 

1.     fulfilled: Action related to the promise succeeded

2.     rejected: Action related to the promise failed

3.     pending: Promise is still pending i.e. not fulfilled or rejected yet

4.     settled: Promise has fulfilled or rejected.

 

 

 

 

 

 

 

 

 

 

 

 

Duplicate id in list

  Error 'System.ListException: Duplicate id in list' in Apex : list  can hold  duplicate values, but if you try to add duplicate  sO...