Sunday, August 11, 2019

Accessing Child Records from sObjects using getSobjects method

Dynamic queries plays very important role when we need to run different SOQL based on different inputs. By using dynamic apex, we can store the output of queries in sObjects list and then can even check if parent record contains any child records. Even if you want to fetch child record information then you can use "getSobjects('relationshipname') method to get child information.

Below is code snippet to get all opportunities and contacts information related to Account:

Hope this will help!!!

Thursday, June 13, 2019

Accessing Parent Field Values from sObjects in Dynamic Queries Using Dynamic Apex

In case of dynamic queries, we often store queries output in sObject and then refer field values. In order to refer field values, we first type cast generic sObject into specific objects like Account, Contact or custom objects as mentioned below:

string qString = 'Select id, name from Account Limit 1';
sObject sb = database.query(qString);
Account acc = (Account)sb;
string accountName = acc.Name;

Suppose we know the field API names then we can utilize the concept of sObject to get field values directly without type casting as mention below:

string qString = 'Select id, name from Account Limit 1';
sObject sb = database.query(qString);
string accountName = sb.get('Name');

So now with the help of sObjects concept, we can access parent field values from child records.

Now consider a scenario in which I have list which stores all field API names which can be used to query opportunity line items. I will generate the dynamic query and will use concept of sObject to access Opportunity fields from sObject which is output of dynamic query.

List<string> fieldAPINamesList = new List<string>{'Id','Opportunity.Name','Opportunity.Partner__r.Name'};
string qString ='Select '+string.join(fieldAPINamesList,',')+ ' from OpportunityLineItem where id=\'00k90000002z4ml\'';
sobject sb = database.query(qString);
//syntax to get OpportunityLineItem Id  value from sObject
string OpportunityLineItemId = string.valueof(sb.get('Id'));
//syntax to get Opportunity.Name field value from sObject
string OpportunityName = string.valueof(sb.getSobject('Opportunity').get('Name'));
//syntax to get Opportunity.Partner__r.Name field value from sObject
//If partner field in opportunity is blank then you will get null pointer exception
string partnerName = string.valueof(sb.getSobject('Opportunity').getSObject('Partner__r').get('Name'));

Note: While accessing the parent record details in child to parent query, you will get null pointer exception if parent is blank in child record.

I have written an utility method which takes sObject and fieldAPIName as a parameter and returns field value. Please refer below code for reference:

If you run above script in developer console by specifying correct opportunityLineItem Id, then you will see below logs:

Hope this will help!!!

Thursday, June 6, 2019

Fire Platform Events from Batch Apex using Database.RaisesPlatformEvents Interface

With Summer'19 release (API version 44 or later), now it is possible to fire platform events from batch apex. So whenever any error or exception occurs, you can fire platform events which can be handled by different subscriber.

Batch class needs to implement "Database.RaisesPlatformEvents" interface in order to fire platform event.

global class SK_AccountProcessBatch implements Database.Batchable<sObject>,Database.RaisesPlatformEvents{
   //batch logic

To understand more about platform events please refer below links

Platform Events : Way to Deliver Custom Notifications within Salesforce or to external Application

Here I will be writing simple batch class which process account records and if any errors occurs during update, then all account record Ids will be published using platform event.

I have created platform event with below mentioned fields:

Below is batch apex code which will fire platform event and I wrote a trigger which will subscribe to platform event.

I have used Database.Stateful interface to store the record ids which are getting failed in each batch execution. In finish method, I am firing platform event with all failed records Ids.

Below is logs generated by trigger which will get executed whenever platform event is fired.

In order to see debug logs for platform events subscription, add a trace flag entry for the Automated Process entity in Setup. The debug logs aren’t available in the Developer Console’s Log tab.

Navigate to SetUp --> Debug Logs --> New
  • For Traced Entity Type, select Automated Process.
  • Select the time period to collect logs and the debug level.
  • Click Save.
I have also created a lightning component which will subscribe to platform events and will display the event message as shown below in snapshot:

Please refer below link to understand how to use platform events in lightning components:

Handling Platform Events in Lightning Components

Hope this will help!!!

Saturday, June 1, 2019

How to Get List of All Child Records for Given Parent Records in .csv File using Apex

If we have lot of child object for a parent object, then it becomes very difficult to find out list of all related records for a given parent. For example, Account and Contact is reference by many standard and custom objects.

Consider a scenario in which Account is parent for more than 50 objects. In this case if we have to check if account record is being reference in any of these child objects, then how we are going to do that.  Its very difficult to add all related list on account page layout or to write SOQL queries to get this information.

If we use nested queries as mentioned below, then we have limit to use only 20 nested queries.

select id, (Select id from Cases),(Select id from Contacts) from Account where Id='0010000xxxxxxx'

In order to overcome these issues, I have written a script which you can run in developer console and you will receive email with .csv file containing all child records for a given parent record.

In below mentioned script, specify the object API name and 15 or 18 digit record id.

After running this script, you will receive .csv file in email as shown below:

If you are getting below mentioned error, while running the script, the make note of below points:

  • This exception can not be handled by try and catch
  • SOQL is not performing well may be because the large volume of data or due to indexing issues on table.
  • Instead of running this script developer console, use batch apex to run this logic. You can create a custom object and first run a script to store all child objects details like relationship name, child object name. Then you can execute the logic in batch class to first fetch all these records from custom object and then fire nested queries by using relation names and store output in variable. Make sure your batch size is not greater than 20 as we have limit of 20 nested queries in SOQL. In finish method write send email code to get .csv file. If you are still getting this error, then keep on reducing the batch size.
Hope this will help!!

Looking forward for your comments and suggestions.

Thursday, May 30, 2019

How to get all Child Objects List along with Relationship Names related to Parent Object using Apex

Sometimes it is required to get the list of all child relationship names in order to identify all related child objects to a parent object.

Dynamic apex helps to find out all related child object. Suppose you want to find all related object for Account then use below code snippet:

You can specify any object API name and run this code snippet in developer console.

You can also use workbench to find out list of child objects. Navigate to Info tab and select Standard & Custom Objects.

Hope this will help!!

Sunday, May 19, 2019

Lightning:NotificationsLibrary : Easy Way to Display Toast or Notices in Lightning

In order to display the toast messages, we have to fire standard event "force:showToast". Now Salesforce recommend using lightning:notificationsLibrary for displaying messages in lightning via notices and toasts.

Toast helps in providing information about status on user action.
Notices helps in displaying the system related issue or update about any maintenance.

NotificationsLibrary makes very easy for developer to display notices and toast.

How to display Notices using lightning:notificationsLibrary

Below is sample code:

How to display Toast using lightning:notificationsLibrary

Below is sample code:

Hope this will help!!!

Thursday, May 16, 2019

Handling Platform Events in Lightning Components

The lightning:empApi component gives methods for subscribing to a streaming channel and listening to event messages. It supports all streaming channels including channels for platform events, pushTopic events and Change Data Capture events. The lightning:empApi component uses a shared CometD connection.

  • This component is available in 44.0 api version or later.
  • This is available in Lightning Experience and only supported in desktop browsers.
To call the component's methods, add the lightning:empApi component inside your custom component and assign an aura:id attribute to it.

If you want to learn more about platform events then refer below blog:

Platform Events : Way to Deliver Custom Notifications within Salesforce or to external Applications

I have created a lightning component which will subscribe to platform event "Demo_Event__e" which we have created in our previous blog.

I have created an app page using lightning app builder named as "Platform Events App Page". and added this lightning component into it.

Code Snippet:

Below is snapshot of Lightning App page before platform event is fired.

Now fire platform event using workbench through REST API call

Platform event notification received in lightning component.

Hope this will help to understand platform events handling in lightning components. 

Looking forward for everyone's suggestions and comments!!!

Monday, April 22, 2019

Platform Events : Way to Deliver Custom Notifications within Salesforce or to external Applications

Salesforce provides Platform events which can be used create custom notification which can be used within Salesforce app or can be send to external applications. These notification are secure and scalable.

Platform events are part of Salesforce’s enterprise messaging platform. It utilizes publish and subscribe flow. One or many subscribe to same event and carry out different actions.

In lightning events, we define event and then create attributes through which information can shared between lightning components. Similar to this, you create platform event through point and click and then create custom fields which will be used to publish information by using platform events and subscriber can utilize this information.

Platform Events v/s Streaming API

  • In Streaming API (using Push Topics), subscriber receive notification based on changes or updates to records.
  • You can not edit or delete platform event records. You can only create or insert platform events.
  • Visualforce and Lightning component apps can subscribe to platform events using CometD similar to push topics.
  • You can not view platform event in Salesforce user interface and cannot query it through SOQL.
  • You can handle or subscribe platform events through triggers by using after insert.
  • Only "AfterInsert" event is available for platform event objects.
  • Platform events can be published by Process builder, Process Flow, apex, REST API by inserting an sObject.
  • Platform events persist for 24 hours only.
Permission for platform events is controlled through profile or permission sets.

Platform events can be used to publish information and has no dependency on existing salesforce records.

In order to create platform events, navigate to Setup --> Platform Events --> New Platform Event.

I have created a platform event "Demo Event" and going to use apex in order to publish event and subscribe this event through triggers.

When you create a platform event, the system appends the __e suffix to create the API name of the event.

How to fire/publish platform event
  • You have to create record in order to fire platform event.
To publish event messages, you create an instance of the event and pass it to the EventBus.publish method. Use below code snippet to publish event:

// Create an instance of the Demo event 
Demo_Event__e demoEvent = new Demo_Event__e(
           Event_Info__c='Demo event is fired using Apex', 
           Event_Publisher__c='Apex Code');
// Call method to publish events
Database.SaveResult sr = EventBus.publish(demoEvent);
// Inspect publishing result 
if (sr.isSuccess()) {
    System.debug('Successfully published event.');
} else {
    for(Database.Error err : sr.getErrors()) {
        System.debug('Error returned: ' +
                     err.getStatusCode() +
                     ' - ' +
  • You can create record using process builder or process flow.
  • You can create event using REST API. Below is details of HTTP Request:
Endpoint- /services/data/v45.0/sobjects/Demo_Event__e/
   "Event_Info__c" : "Demo event is fired using REST API CALL",
   "Is_Event_Valid__c" : true,
   "Event_Publisher__c" : "REST API CALL"
Method - POST
HTTP Response:

   "id" : "e00xx0000000ccf",
   "success" : true,
   "errors" : [ ],
   "warnings" : [ ] 

How to Subscribe Platform Events using Apex Triggers

Whenever a record is created for platform event, after insert trigger gets fired. You can use below code to subscribe for platform event and perform logic as per your need:

trigger DemoEventTrigger  on Demo_Event__e (after insert) {
List<Task> taskList = new List<Task>();
for (Demo_Event__e event: Trigger.New) {
if (event.Is_Event_Valid__c == true) {
//perform logic based on event information

Below is snapshot explaining Platform Events.
Hope this will help!!!

Friday, April 19, 2019

Way to export Code Coverage of Individual ApexClass or Trigger in .csv format

Salesforce provide Tooling API (REST API) through which we can find org metadata information.  Tooling API provide object called "ApexCodeCoverage" which can be used to find code coverage information about individual class or trigger or Org complete code coverage information.

I have created a apex script which can be run in developer console in "Execute Anonymous Window". After running this script, you will receive an email with .csv file which will contain information about code coverage for each apex class or trigger.

Below is snapshot of .csv file which you will recieve:

By using Tooling API you can find overall code coverage of your organization. Below is script which you can use in "Execute Anonymous Window".

Important things to consider in order to get have reliable coverage details:

  • Go to setup --> apex test execution ---> click on Options ---> deselect the Store only aggregate code coverage option.
  • Go to Setup --> Apex test execution ----> Clear all test history.
  • Go to Setup --> Apex classes ---> Compile all classes.
  • Go to Setup ---> Apex test execution ---> Run all test.
Once Run All Test is completed, then above scripts to get actual code coverage details of all classes or trigger or to get overall Org code coverage percentage.

You can also run the queries on "apexCodeCoverage" and "ApexOrgWideCoverage" object in developer console query editor by selecting tooloing api checkbox.

To get Org Overall Code coverage use below Query:

"SELECT PercentCovered FROM ApexOrgWideCoverage "

To get code coverage of specific apex class or trigger use below query:

SELECT Coverage FROM ApexCodeCoverage WHERE ApexClassOrTriggerId = 'xxxxxxxxx'
where xxxxxxxxx = 15 or 18 digit apex class or apex trigger id.

Hope this will help!!

Looking forward for everyone comments and suggestions...

Sunday, March 17, 2019


I am really excited to share that I have cleared "IDENTITY AND ACCESS MANAGEMENT DESIGNER" exam yesterday and going to share my inputs for people who are preparing for it.

I have successfully completed "Application Architect" credentials and if you would like to prepare for that then refer below links:

Data Architecture and Management Designer : Exam preparation guide and tips
Sharing and Visibility Designer : Exam preparation guide and tips

As usual I started with Resource Guide for Identity and Access Management designer exam. This time while preparing I gave more preference to Trailmix-Architect Journey: Identity and Access Management  specially to hand on training section.

This was really a tough exam for me as everything was theoretical as SSO is already configured in all companies. Also we won't get chance to work on identifying the identity provider and service provider configurations as my job roles mainly include to provide solutions to streamline business process. But anyhow is was mandatory exam in order to get "System Architect" credential, I started preparing for it just after clearing my "Salesforce Certified Integration Architecture Designer".

If you are preparing for Salesforce Certified Integration Architecture Designer exam then refer below link:
SALESFORCE INTEGRATION ARCHITECTURE DESIGNER : Things to consider before appearing for this exam

Below are the points which you should cover before appearing for exam:

My Domain
  • My domain is required to configure SSO.
  • Add a subdomain to your Salesforce org with the My Domain Salesforce Identity feature. If you specify as entity id in SSO, then identity provider will redirect to genric salesforce domain and salesforce again will open login page as it will not be able to understand on which subdomain user needs to be redirected. If you enable my domain and specify my domain in entity id, then redirection from identity provider will be easy.
  • My domain is required for Single sign-on (SSO) with external identity providers, Social sign-on with authentication providers, such as Google and Facebook and lightning components in Lightning component tabs, Lightning pages, the Lightning App Builder, or standalone apps.
  • You can rename your My Domain subdomain in production orgs. But you can't rename a sandbox, developer, or trial org subdomain.
  • Authentication Configuration under My domain controls which all authentication services will be presented to user.
  • If you want user to get authenticated from external identity provider then deselect login form from authentication services. 
  • If login form is enabled as authentication services, then user may complain saying that they get redirected to salesforce login page instead of redirecting to identity provider login screen.
Salesforce 2 factor authentication 
  • You can use out of box two factor authentication provided by salesforce. Create a permission set and assign “enable 2 factor authentication” permission in it. Now assign this permission set to user for which you want to enable 2 factor authentication. User needs to download Salesforce authenticator app and link their salesforce account. Now whenever user logged in, will get approve or reject option on salesforce authenticator. Salesforce authenticator will display device and location for log in and you can specify to remember that location so that next time you will not get notification when you log in. 
Custom Login Flow
Salesforce OAuth Flows
Oauth Scope Parameter Values
  • The scope parameter fine-tunes the permissions associated with the tokens that you’re requesting. Scope is a subset of values that you specified when defining the connected app.
  • Different scope values are:
    • api : Allows access to the current, logged-in user’s account using APIs, such as REST API and Bulk API. This value also includes chatter_api, which allows access to Chatter REST API resources.
    • chatter_api : Allows access to Chatter REST API resources only.
    • custom_permissions : Allows access to the custom permissions in an organization associated with the connected app, and shows whether the current user has each permission enabled.
    • full : Allows access to all data accessible by the logged-in user, and encompasses all other scopes. full does not return a refresh token. You must explicitly request the refresh_token scope to get a refresh token.
    • id : Allows access to the identity URL service. You can request profile, email, address, or phone, individually to get the same result as using id; they are all synonymous.
    • openid : Allows access to the current, logged in user’s unique identifier for OpenID Connect apps. Use the openid scope in the OAuth 2.0 user-agent flow and the OAuth 2.0 web server authentication flow to receive a signed ID token conforming to the OpenID Connect specifications in addition to the access token.
    • refresh_token : Allows a refresh token to be returned when you are eligible to receive one. Then the app can interact with the user’s data while the user is offline, and is synonymous with requesting offline_access.
    • visualforce : Allows access to customer-created Visualforce pages. Doesn’t allow access to standard Salesforce UIs.
    • web :   Allows the ability to use the access_token on the web, and includes visualforce, allowing access to customer-created Visualforce pages.
Identity License and External Identity License
  • Identity license connects Salesforce users with external applications and services, while giving administrators control over authentication and authorization for these users.
  • External Identity license is used for users outside of your organization’s user base (such as non-employees). Store and manage these users, choose how they authenticate (username/password, or Single Sign-On social sign-on through Facebook, Google+, LinkedIn, and others), and allow self-registration.
IDP-initiated or SP-initiated
  • When salesforce act as service provider and identity provider is external app. If now user login by using my domain of salesforce, then it is called as SP initiated single sign on flow. In this case, salesforce will first redirect user to identity provider to get authorized and based on response from identity provider, will allow user to go to salesforce.
  • If user login in identity provider and then redirect to service provide using some link, then it is called as IP initiated Single sign on flow.
  • If you are using third party app as IP and salesforce and some external app are using third party as IDP. So if user click a link for salesforce resource on external app, then you need to configure SP initiated SSO that passes the SAML token to authentication provider when salesforce resource is requested.
  • With an IdP-initiated login process, you typically set up a link on the company intranet that users click to get access to Salesforce. 
Identity Connect
  • Identity Connect is a Salesforce Identity product that helps Salesforce admins apply all the data collected in AD to automate Salesforce user management. It syncs changes in AD within seconds.
  • Identity Connect is on-premises software that sits behind your firewall and pushes data to Salesforce. Identity Connect’s server runs within the corporate network and communicates with the AD server over LDAP(S). It communicates with in-the-cloud Salesforce over HTTPS. Work with your networking engineer to ensure that these paths are open so that Identity Connect can connect to both AD and Salesforce.

  • When Identity Connect detects differences between AD and Salesforce, it updates Salesforce with the information in AD. Data transfer is in one direction and AD is the source of truth. Identity Connect never changes information that's stored in AD.
  • You can set up Identity Connect to manage multiple production orgs. And you can set up Identity Connect to manage multiple nonproduction orgs. But you can’t mix production and sandbox orgs in one Identity Connect environment.
  • Different ways through which identity connect map AD Group user to Salesforce user are:
    • Profile mapping with AD groups
    • Permission set mapping with AD groups
    • User role mapping with AD groups
    • Salesforce groups to AD groups 
Self Registration - Communities
  • Enable self-registration to allow unlicensed guest users to join your community. When your users self-register, you can choose to save them as contacts under a business account or create a person account for each self-registering user.
  • If your business deals mostly with individuals, instead of creating them as contacts under a single business account, you can assign each self-registering user to a person account.
  • If you want to create person account from self register page, then don’t specify account Id while creating account. You can also manually create person accounts and assign them to community users with Customer Community and Customer Community Plus licenses.
Canvas App
  • Canvas enables you to easily integrate a third-party application in Salesforce. Canvas is a set of tools and JavaScript APIs that you can use to expose an application as a canvas app. This means you can take your new or existing applications and make them available to your users as part of their salesforce experience.
  • The third-party app that you want to expose as a canvas app can be written in any language. The only requirement is that the app has a secure URL (HTTPS).
  • Canvas app appearance in salesforce depends on the values you select in the locations field when creating the connected app in salesforce. 
  • Canvas app can appear in chatter feed, Chatter tab, Console, navigation menu in salesforce app, VF page, Page layouts and mobile cards, Open CTI (in the call control tool), Chatter publisher and action bar.
  • Canvas can use web Server OAuth Authentication Flow and User-Agent OAuth Authentication Flow.
Single Sign On Settings
  • Configure single sign-on in order to authenticate users in from external environments
  • With Just-in-Time provisioning, you can use a SAML assertion to create regular and portal users on the fly the first time they try to log in. This eliminates the need to create user accounts in advance. 
  • Just-in-Time provisioning works with your SAML identity provider to pass the correct user information to Salesforce in a SAML 2.0 assertion attribute statement. You can both create and modify users, contacts, and accounts this way. Because Just-in-Time provisioning uses SAML to communicate, your organization must have SAML-based single sign-on enabled.
  • To enable Just-in-Time provisioning, you must explicitly enable the checkbox in Single Sign-On Settings.
  • Entity Id controls the redirection of user once it gets authorized by identity provider.
  • If user is getting redirected always to home page after getting authenticated successfully, then it means identity provider is not able to preserve the relay state which specify where to redirect user after authentication.
Connected App
  • A connected app integrates an application with Salesforce using APIs. Connected apps use standard SAML and OAuth protocols to authenticate, provide single sign-on, and provide tokens for use with Salesforce APIs. In addition to standard OAuth capabilities, connected apps allow Salesforce admins to set various security policies and have explicit control over who can use the corresponding apps.
  • If you want your user to access salesforce using mobile devices and IP restriction is applied on user profiles, then if you relaxed IP restrictions for your OAuth-enabled connected app then user can access salesforce using mobile devices.
  • IP relaxation does not apply to SAML-enabled connected apps unless they are also OAuth-enabled for single sign-on.
  • Refresh Token Policy can also be set in connected app. If users are complaining that they need to login after some time on their mobile device, then check refresh token policy on connected app.
  • Create connected app for external application to configure SSO for external application from salesforce. You can add profile and permission set to connected app to pre-authorize the user. Connected app is mainly used for inbound request to salesforce.
Federated Authentication
  • Federated Authentication using SAML Federated authentication uses SAML, an industry standard for secure integrations. Investing in SAML with can be leveraged with other products or services. If you use SAML, you don't have to expose an internal server to the Internet: the secure integration is done using the browser. In addition, never handles any passwords used by your organization.
  • When SAML is configured, the user (via their browser) hits either a URL at the enterprise Identity Provider (IdP) or, if My Domain is configured, any My Domain URL at Salesforce - e.g. The SAML protocol redirects them for authentication in the enterprise, and sends them to Salesforce with a signed XML message representing that authentication.
  • Signed XML request message contains federation Id to uniquely identify the user in salesforce.
  • Salesforce user record Id, federation Id and username can be used to represent the identity of the user when Salesforce is acting as a Service Provider in a SAML configuration.
  • User will face issues with SSO if federation Id is not specified in salesforce correctly which is being returned by identity provider.
Delegated Authentication
  • Another option for authenticating users on Mobile and Desktop devices is Delegated Authentication. If enabled for an organization and user's profile, when a user attempts to authenticate directly to Salesforce, the credential is sent back to a customer configured endpoint over a HTTPS secured web-service.
  • You need to request to salesforce in order to enable this feature.
  • Salesforce uses the following process for authenticating users using delegated authentication:
    • When a user tries to log in, Salesforce validates the username and checks the user’s profile settings.
    • If the user’s profile has the Is Single Sign-On Enabled user permission, then Salesforce does not validate the username and password. Instead, a Web services call is made to the user’s organization, asking it to validate the username and password. Note Salesforce doesn't store, log, or view the password in any way. It is disposed of immediately once the process is complete.
    • The Web services call passes the username, password, and IP address of the user to the customer's Web service. Your implementation of the Web service validates the passed information and returns either true or false.
    • If the response is true, then the login process continues, a new session is generated, and the user proceeds to the application. If false is returned, then the user is informed that his or her username and password combination is invalid.
    • Using this process, customers can easily use their existing authentication systems to validate credentials. This approach works will all mobile and desktop clients. Once a delegated authentication service is built and enabled for a user, there is no additional configuration required. Users will login using the regular Salesforce login screens, but their credential will simply be validated remotely.
  • Salesforce sends the user request over SAML, but the request is sent back using delegated authentication. The RelayState parameter is transformed into the startURL parameter to redirect the user to the correct page. Using this technique, mobile and desktop clients that use SAML with Salesforce can also take advantage of SSO over delegated authentication.
  • For security reasons, make your web service available by TLS. Webservice can be REST or SOAP.
  • Delegated authentication offers the following benefits.
    • Uses a stronger form of user authentication, such as integration with a secure identity provider.
    • Makes your login page private and accessible only behind a corporate firewall
    • Differentiates your org from all other companies that use Salesforce to reduce phishing attacks.
Federated Authentication vs Delegated Authentication
  • Delegated authentication is inherently less secure than federated authentication. Even if encrypted, delegated authentication still sends the username and password (possibly even your network password) over the internet to Some companies have policies that preclude a third party for handling their network passwords. 
  • Delegated authentication requires much more work for the company implementing it. The Web services endpoint configured for the org must be developed, hosted, exposed on the Internet, and integrated with the company's identity store.
  • Federated authentication happens through web browser and can not be used for mobile and desktop applications. Use federated authentication for mobile and desktop app.
Looking forward for everyone's comments and suggestion and best of luck for exam...

Hope this will help!!!

Wednesday, March 13, 2019

Salesforce OAuth Flow - Implementation guidelines and tips

Whenever an external app request to access salesforce data, authentication needs to be done on salesforce side. Different authentication flows are available as governed by OAuth standards.

Through this blog, i will share commonly used OAuth flows and factors which you need to consider while deciding which one to use.

OAuth 2.0 Web Server Authentication Flow
  • This flow is mainly used by applications hosted on web server.
  • If external application is trusted one and hosted on secure server and can securely store client_secret, then flow can be used.
  • This flow is used mainly to build web application.
  • First of all external application will request for access_token and user will be redirected to login page for authentication. After authentication, user will approve salesforce access by external app.
  • After successful approval to grant access, authentication code will be returned through callback. External app will utilize this temporary OAuth token( valid for 10 mins) and send POST request to get access_token by sending temporary OAuth code, client_id and client_secret.
  • Salesforce will return access_token and refresh_token. Refresh token can be used to regenerate the access token by external app so that user is not required to authenticate every time.
  • Instead of sending client credentials as parameters in the body of the access token POST, Salesforce supports the HTTP Basic authentication scheme. This scheme's format requires the client_id and client_secret in the authentication header of the post as follows:         Authorization: Basic64Encode(client_id:secret)
  • This flow is not recommended for application (like ETL or middleware's) which will access salesforce using API's and no UI is involved.

OAuth 2.0 User Agent Flow
  • This flow is recommended when you build mobile or desktop application and your application can be distributed to anyone. So these kind of application are not considered as safe to store client secret because source code of application will be accessible to everyone and client secret can be exposed easily.
  • This flow is used when external system application wants to login into salesforce using salesforce login credentials. Once user logged in, then he/she to approve that external application can fetch salesforce data(scope defined in connected app).
  • In this flow, external application will pass only client id and user login page opens and user authenticate themselves to get access token, refresh tokens.
  • External application can use use refresh token to get new access token if it get expired and can avoid logging user again in salesforce.
  • With the user-agent authentication flow, the client app receives the access token as an HTTP redirection. The client app requests the authorization server to redirect the user-agent to another web server or to an accessible local resource. The server can extract the access token from the response and pass it to the client app. For security, the token response is provided as a hash (#) fragment on the URL. It prevents the token from being passed to the server or to any other servers in referral headers.

OAuth 2.0 JWT Bearer Token Flow
  • Ideal for application which access sfdc only through API as there is no UI involved. For example ETL tools or middleware.
  • A JSON Web Token (JWT) enables identity and security information to be shared across security domains. 
  • JWT is basically a JSON file consisting of a header and claims object, where the header contains the signature algorithm and the claims object contains specific information such as the username and consumer key. At a high level, you will then sign the JSON object with the private key of your certificate and send the JWT to Salesforce to obtain an access token.
  • When a client wants to use this flow, posts an access token request that includes a JWT to Salesforce’s OAuth token endpoint. Salesforce authenticates the authorized app through a digital signature that is applied to the JWT. 
  • Digital certificates are required in this flow. Upload certificate (X509 ) to connected app which will be used to authenticate JSON web tokens.
  • External application send request for access token by passing JWT token in body. SFDC server validate JWT and return access token to external app.
  • No refresh token is returned in this flow. So if access token expires then send request to generate access token again.

OAuth 2.0 SAML Bearer Assertion Flow
  • A SAML assertion is an XML security token issued by an identity provider and consumed by a service provider.
  • The external app or client isn’t required to store client_secret.
  • If you use active directory or LDAP as identity provider, then you will use SAML assertion from your SSO flow to obtain an access token to Salesforce.
  • This flow used SAML assertion (XML token generated by Identity provide) and applied digital signature to it using certificates.
  • In connected app, you upload this certificate (X509 ) containing private key. This key should be used while signing SAML asseration(base 64 encoded).
  • The SAML assertion is posted to the OAuth token endpoint, which in turn processes the assertion and issues an access_token based on prior approval of the app(users are pre- authorized in connected app). 
  • This flow also return only access token not refresh token

SAML Assertion Flow
  • The SAML assertion flow is an alternative for Orgs that are currently using SAML to access Salesforce and want to access the web services API the same way. 
  • You can use the SAML assertion flow only inside a single org.  So it means it can be used to connect to single sfdc org
  • You don’t have to create a connected app to use this assertion flow. Clients can use this assertion flow to federate with the API using a SAML assertion, the same way they federate with Salesforce for web single sign-on.
  • If you have SSO configured specifically for the Salesforce org that your partner application is authenticating to, you can also use the SAML Assertion Flow. 
  • Configure SAML for your org. SAML version 2.0 is required. Exchange a SAML assertion for an access token. Use a JSON parser to process the response from salesforce to extract the access_token.
  • The benefit of this flow is that you can use a Base-64 encoded, then URL encoded, SAML assertion that is normally used for web single sign-on. This makes it significantly more simple from a development perspective because you don't need to create a connected app but requires you to have SSO enabled for your Salesforce instance.
  • No refresh token is issued in this flow.

OAuth 2.0 Username and Password Flow
  • Use the username-password authentication flow to authenticate when the consumer already has the user’s credentials.
  • Avoid using this flow because you have to send username and password un-encrypted to Salesforce.
  • Use this flow only when there is no way to connect by using other available flows.
  • Salesforce communities don’t support the OAuth 2.0 username-password authentication flow.
  • In this flow, external app or client sends client_id,client_secret, username and password in POST request.
  • The security token must be added to the end of the password to log in to Salesforce from an un-trusted network. Concatenate the password and token when passing the request for authentication.
  • No refresh token is issued.
OAuth 2.0 Device Authentication Flow
  • The OAuth 2.0 device authentication flow is typically used by applications on devices with limited input or display capabilities, such as TVs, appliances, or command-line applications. 
  • This flow returns access_token and refresh_token.
  • When device requests authorization by specifying client_id, Salesforce verifies the request and returns the following: human-readable user code, verification URL, device code, and minimum polling interval (in seconds).
  • User navigate to verification URL and enters user code received.
  • User prompted to login and approve access to salesforce data.
  • In the meantime, the application running on the device should keep polling Salesforce (polling interval is also returned by Salesforce) and once the user has approved access, the application on the device will get an access token issued.
  • After the access token is granted, the device can use it in API requests to access data on the user’s behalf. The device uses a refresh token to get a new access token if the access token becomes invalid.

OAuth 2.0 Asset Token Flow
  • Client applications use the OAuth 2.0 asset token flow to request an asset token from Salesforce for connected devices. 
  • In this flow, the device obtain an access token (in any of the above ways) and use this token alongside additional information to create an actor token. This token contains valuable information about the asset which is then send to Salesforce where it is exchanged for an asset token. Subsequent requests to protected resources at Salesforce can then be made with the asset token.
  • In this flow, an OAuth access token and an actor token are exchanged for an asset token. This flow combines asset token issuance and asset registration for efficient token exchange and automatic linking of devices to Service Cloud Asset data.

OAuth 2.0 Refresh Token Flow
  • The OAuth 2.0 refresh token flow renews tokens issued by the web server or user-agent flows.

Revoking Tokens
  • Revoke an OAuth token if you don’t want the client app to access Salesforce data or if you don’t trust the client app to discontinue access on its own.
  • When users request their data from within an external app (the consumer’s page), they’re authenticated. You can revoke their access tokens, or the refresh token and all related access tokens, using revocation. Developers can revoke the token when configuring a log-out button in their app.
  • You can use POST method to revoke token as mentioned below

To revoke OAuth 2.0 tokens, use the revocation endpoint. 
Construct a POST request that includes the following parameters using the application/x-www-form-urlencoded format in the HTTP request entity-body. For example:
    POST /revoke HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
  • Salesforce also supports GET requests with the query string parameter token and the current token. If an access token is included, Salesforce invalidates it and revokes the token. If a refresh token is included, Salesforce revokes it and any associated access tokens. For example:

The authorization server indicates successful processing of the request by returning an HTTP status code 200. For all error conditions, status code 400 is used.
  • If an access token is included, Salesforce invalidates it and revokes the token. If a refresh token is included, Salesforce revokes it and any associated access tokens.
You can also navigate to "Connected Apps OAuth Usage" under set up and block external app to create new sessions with connected app.

Hope this will help!!!

Thursday, February 28, 2019

Login Flows - Way to Customize User Authentication Flow

Login flows acts as business process which you want to invoke for user after logging. Login flows are assigned at profile level.

How Login Flow works?

Custom 2 Factor Authentication

Login flows can be used to provide custom 2 factor authentication. Below is flow chart that I have prepared to implement this:

Different steps involved:
  • Once user logged in, will be redirected to login flow.
  • From login flow, call apex call which can either perform callout to external system which can send authentication code to user via SMS or email. You can use twilio app to send sms to users. You can store the auth code from callout response in salesforce(may be in some custom field on user object).
  • If you don't want to use external app, then generate random code in apex and store it in custom field in user object and send email to user with code using apex email message methods.
  • Once user receives the code will enter it in input text on login flow. 
  • If user entered code matches with code stored in user object custom field then allow user to navigate to Salesforce. As a best practice clear the code stored in user object once validation completed so that user can not reuse the same code again.
  • If there is mismatch, you can deny user access.

Important considerations while using login flows
  • Login flow can not be used to replace Salesforce authentication but can used as additional set of authentication.
  • Login flow can be used to display some important messages to users once they login. Refer Login Flows to Display Important Messages to User After Login to learn about this in detail.
  • Login flows are only applicable for UI login not for API login.
  • Login flow can be used with SAML JIT. If user doesn't exist then during JIT, first user will be provisioned and then login flow will kick off. If user fails 2 factor authentication from login flow,then deactivate the user again in salesforce.
  • When user login, user login date like type of device, IP address, session id, user agent etc are available in visual workflow designer. This can be used to provide different user experience to user based on login device.
  • As a best practice, do not enable custom 2 factor authentication for system administrators.

Hope this will help!!

Thursday, February 21, 2019

How to update Chatter User Profile Photo using Connect API

The "connectapi" provide classess and static methods to access chatter data which is available through Chatter REST API. This is also referred as "Chatter in Apex". It exposes the data in localized and structured way.

Chatter in apex provides "UserProfiles" class which provides different methods to access information about users profile data.

Before version 35, "Chatterusers" class was there which was used to access information about users, such as activity, followers, subscriptions, files, and groups. Now this class is not available.

We will use UserProfiles class to update chatter user photo. You can either upload the image in documents or at any place. We need blob representation of that image and can be used to update profile photo using blob variable.

Below is sample code:

Document doc=[SELECT id, body FROM Document  WHERE Name='ProfilePhoto' LIMIT 1];
//set the photo on the user's profile
ConnectApi.UserProfiles.setPhoto(null, UserInfo.getUserId(), new ConnectApi.BinaryInput(doc.body,'image/jpg','user.jpg'));

I Have uploaded image in documents and then updating the profile photo on chatter.

setPhoto method require below attributes:
  • communityId (string)- specify the community Id or specify null for internal users
  • userid(string)- 15 digit or 18 digit user recordId 
  • Image details (ConnectApi.Binary​​Input) -  you need to specify the blob(content of file), MIME type of content and file name(string).

If you store profile photo in files, then you can use below syntax to update chatter profile photo:

ConnectApi.UserProfiles.setPhoto(null, UserInfo.getUserId(), '0690I00000D42WT',null);

This method takes 4 parameters
  • communityId (string)- specify the community Id or specify null for internal users.
  • userid(string)- 15 digit or 18 digit user's recordId.
  • fileId(string) - 15 or 18 digit file Id.
  • version number(integer) - Version number of the existing file. Specify either an existing version number, or null to get the latest version.
Hope this will help!!

Saturday, February 16, 2019

How to get User Locale information in Lightning Components

Lightning framework provide $Locale which can be used to get current user preferred locale. For example you can get user preferred timezone, language, currency format etc.

In Spring'19, Salesforce introduces new date-time $Locale attributes for date- time formattingas mentioned below:
  • longDateFormat ("MMMM d, yyyy")                              
  • shortDateFormat ("M/d/yyyy")
  • shortDatetimeFormat ("M/d/yyyy h:mm a")
  • shortTimeFormat ("h:mm a")
You can refer this global variable either directly in lightning component markup or in controller.js  file.

Below is sample code:

Snapshot of lightning component

For detailed information on Locale global variable, please refer below URL:
$Locale in Lightning Component

Hope this will help!!!

Tuesday, February 12, 2019

Way to avoid Callouts during maintenance or site switching activity (during read only mode)

Salesforce maintain each instance in 2 different geographical locations and perform site switching after every 6 months. One location act as "active site" with all transaction and replicate all transaction in second location called as "ready site" in near real time.

Site switching helps Salesforce to perform maintenance activity and to plan for disaster recovery. Ideally this activity takes 1 hour and Salesforce instance will be available in read only mode.

If you have callout to external system and based on response you are trying to update anything inside salesforce then during read only mode Salesforce execute all callout but update on salesforce will be blocked. This may create some inconsistency in your program flow.

To avoid this scenario, first check if system is in read only mode or not then perform write operation in salesforce.

Salesforce provide below method through which you can identify if instance is read only mode or in default mode.


If this method return "ApplicationReadWriteMode.READ_ONLY" enum value, then the org is in read-only mode. If it return "ApplicationReadWriteMode.DEFAULT" then org is available in read/write mode.

Below is sample code which you can use in your apex logic

// check read only status for org
ApplicationReadWriteMode currentMode = System.getApplicationReadWriteMode();
String returnValue = '';

if (currentMode == ApplicationReadWriteMode.READ_ONLY) {
// avoid callout

} else if (currentMode == ApplicationReadWriteMode.DEFAULT) {
//perform callout
// write back in salesforce based on callout response


How to test read only mode in sandbox

Contact salesforce to enable read only test mode option for sandbox. Once enabled, you can toggle read only mode test functionality in sandbox.

Hope this will help!!!

Friday, January 18, 2019

Lightning:map - Way to display location on map either by using address or geo-location

Salesforce introduces new tag in lightning framework "lightning:map" which can be used to securely displays map of one location or many locations.

You can either use address (make sure postalcode,country are specified) or geolocation (latitude and longitude).

Below is syntax to use lightning:map


where mapMarkers is an array of marker to display location. Below is JSON sample for markers:

"location": {
"Country": "USA",
"State": "CA"
"icon": "standard:account",
"title": "Western Telecommunications Corp.",
"description": "CA,USA"
"location": {
"City": "Lawrence",
"Country": "USA",
"PostalCode": "66045",
"State": "KS"
"icon": "standard:account",
"title": "Dickenson plc",
"description": "Lawrence,KS,66045,USA"

If you know geo-location of address then, you can pass latitude and longitude in location as shown below:

    location: {
'Latitude': '37.790197',
'Longitude': '-122.396879'
    title: 'Western Telecommunications Corp',
    description: 'Western Telecommunications Corp',
    icon: 'standard:account'

I have created a sample lightning component which fetch account billing address and display it on google maps using Lightning:map tag.

Complete Code:

  • If you specify address, then you must specify City, PostalCode, State or Country.
  • If you specify both address and geo-location, then map will be plotted using latitude and longitude.
  • If any mapMarker is invalid, then nothing will be plotted on map even other map markers.

Hope this will help!!!