Salesforce Certified CPQ Specialist Preparation Guide

Trailhead link to get started with CPQ - https://trailhead.salesforce.com/en/modules/sf_cpq

Install Salesforce CPQ - http://www.infallibletechie.com/2018/04/how-to-install-salesforce-cpq.html

Setup CPQ Product Layout Salesforce - http://www.infallibletechie.com/2018/05/setup-cpq-product-layout-salesforce.html

Introduction to Salesforce CPQ - https://www.youtube.com/watch?v=si8ubeICIGw

How to create Product Families and select the product in Salesforce? - http://www.infallibletechie.com/2018/05/how-to-create-product-families-and.html

How to create/add New Product(s) in Salesforce? - http://www.infallibletechie.com/2018/05/how-to-createadd-new-products-in.html

How to configure Product Description in Salesforce CPQ? - http://www.infallibletechie.com/2018/05/how-to-configure-product-description-in.html

Block Pricing in Salesforce CPQ - http://www.infallibletechie.com/2018/05/block-pricing-in-salesforce-cpq.html

Customer Specific Price in Salesforce CPQ - http://www.infallibletechie.com/2018/04/customer-specific-price-in-salesforce.html

Summary Variables in Salesforce CPQ - http://www.infallibletechie.com/2018/05/summary-variables-in-salesforce-cpq.html

How to group Products in Quote creation in Salesforce CPQ? - http://www.infallibletechie.com/2018/05/how-to-group-products-in-quote-creation.html

How to import Quote lines in Salesforce CPQ? - http://www.infallibletechie.com/2018/05/how-to-import-quote-lines-in-salesforce.html

How to set Quote Line Visibility in Salesforce Product Option?  - http://www.infallibletechie.com/2018/04/how-to-set-quote-line-visibility-in.html

How to install Salesforce CPQ?

1. Go to https://steelbrick2.force.com/apex/installPremium

2. Select the version and click Production or Sandbox to install.


Difference between lightning:input and ui:input in Lightning in Salesforce

lightning:input

Base Lightning components are the building blocks that make up the modern Lightning Experience, Salesforce1, and Lightning Communities user interfaces.
Beyond being equipped with the Lightning Design System styling, they handle accessibility, real-time interaction, and enhanced error messages.

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/lightning_overview.htm

ui:input

Lightning Design System styling is not applied by default.

Items to approve in Salesforce

Items to Approve in Lightning Experience

1. Add the Items to Approve component to home page.


2. You can see the Items to Approve on the home page.


Items to Approve in Salesforce Classic

1. Go to Home Page Layouts.

2. Edit the layout and add Items to Approve.


2. Go to home page to view Items to Approve.


lightning:datatable with buttons in Salesforce

Sample Code:

AccountListController.apex:

public class AccountListController {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
    }
    

}

AccountList.cmp:

<aura:component implements="force:appHostable"
controller="AccountListController">
                
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"
                         onrowaction="{!c.viewRecord}"/>
    

</aura:component>

AccountListController.js:

({
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'},
            {type: "button", typeAttributes: {
                label: 'View',
                name: 'View',
                title: 'View',
                disabled: false,
                value: 'view',
                iconPosition: 'left'
            }},
            {type: "button", typeAttributes: {
                label: 'Edit',
                name: 'Edit',
                title: 'Edit',
                disabled: false,
                value: 'edit',
                iconPosition: 'left'
            }}
        ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    viewRecord : function(component, event, helper) {
        var recId = event.getParam('row').Id;
        var actionName = event.getParam('action').name;
        if ( actionName == 'Edit' ) {
            alert('Edit');
            var editRecordEvent = $A.get("e.force:editRecord");
            editRecordEvent.setParams({
                "recordId": recId
            });
            editRecordEvent.fire();
        } else if ( actionName == 'View') {
            alert('view');
            var viewRecordEvent = $A.get("e.force:navigateToURL");
            viewRecordEvent.setParams({
                "url": "/" + recId
            });
            viewRecordEvent.fire();
        }
    }

})

Output:


If you click View button, it will take you to the Account detail page.

If you click Edit button, it will popup Account Edit form.

How to sign up for Salesforce Summer '18 pre-release org?

1. Go to https://www.salesforce.com/form/signup/prerelease-summer18.jsp.

2. Enter all your information and submit it.


3. You will receive an email with credentials.

How to add multiple Leads and Contacts to a Campaign in Lightning Experience in Salesforce?

1. Add the Campaign Members related list to the page layout.

2. Use Add Leads and Add Contacts button in the related list to add multiple Leads and Contacts to a Campaign.


How to give access to Apex Class for multiple profiles in Salesforce?

1. Go to Apex Classes.


2. Click Security for the apex class to which access should be given.


3. Select the profiles and click Save button.

Simple Forgot Username feature in Salesforce Community

1. Create Forgot Username Lightning Component and Apex Class.

Lightning Component:

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" controller="ForgotUsernameController">

    <aura:attribute name="email" type="String"/>
    <aura:attribute name="searchBool" type="Boolean"/>
    <aura:attribute name="userRecord" type="User"/>
    
    <div class="slds-grid slds-grid_vertical slds-grid_vertical-align-center">
        <div class="slds-col">
            <span>Enter your email address</span>
        </div>
        <div class="slds-col">
            <span><lightning:input type="text" value="{!v.email}"/><br/></span>
        </div>
        <div class="slds-col">
            <span><lightning:button label="Find Username" onclick="{!c.findUser}"/></span>
        </div>
    </div>
    
     <div class="slds-grid slds-grid_vertical slds-grid_vertical-align-center">
        <div class="slds-col">
            <span>
            <aura:if isTrue="{!v.searchBool}">
                    <aura:if isTrue="{!v.userRecord}">
                        Username is {!v.userRecord.Username}<br/><br/>
                        User Active? {!v.userRecord.IsActive}
                        <aura:set attribute="else">
                            User not matched with this email.
                        </aura:set>
                    </aura:if>
                </aura:if>
            </span>
        </div>
    </div>
    
</aura:component>

Lightning Controller:

({
findUser : function(component, event, helper) {
        component.set("v.searchBool", true);
        var action = component.get("c.fetchUser");
        action.setParams({
            emailAddress : component.get("v.email")
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.userRecord", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
}
})

Apex Class:

public class ForgotUsernameController {
    
    @AuraEnabled
    public static User fetchUser(String emailAddress) {
        List < User > listUsers = [ SELECT Id, Username, IsActive FROM User WHERE Email =: emailAddress ];
        if ( listUsers.size() > 0 ) {
            User usr = listUsers[0];
            return usr;
        }
        else
        return null;
    }

}

2. Create Forgot Username page in Salesforce Community with Page Access set to Public.


3. Drag and Drop the Forgot Username Lightning Component.

4. Open the Forgot Username page in a new browser to test it.


Continuation Class Example in Salesforce

Use the Continuation class to make callouts asynchronously to a SOAP or REST Web service.

Visualforce page:

<apex:page controller="ContinuationController">

    <apex:pageMessage rendered="{!statusBool}" severity="Info" summary="Long running process. So, do not press Start Request multiple times."/>
   <apex:form >
      <apex:commandButton action="{!startRequest}" 
              value="Start Request" reRender="result"/> 
   </apex:form>

   <apex:outputText id="result" value="{!result}" />
   
</apex:page>

Apex Class:

public with sharing class ContinuationController {

    public String requestLabel;    
    public String result {get;set;}
    private static final String LONG_RUNNING_SERVICE_URL = 'https://api.github.com/users/hadley/orgs';
    public Boolean statusBool {get;set;}
    
    public ContinuationController() {
        statusBool = false;
    }
       
    // Action method
    public Object startRequest() {
        statusBool = true;
        Continuation con = new Continuation(40);
        // Set callback method
        con.continuationMethod='processResponse';
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint(LONG_RUNNING_SERVICE_URL);
        this.requestLabel = con.addHttpRequest(req);
        
        return con;  
    }
    
    // Callback method 
    public Object processResponse() {   
        statusBool = false;
        HttpResponse response = Continuation.getResponse(this.requestLabel);
        this.result = response.getBody();
        return null;
    }
    
}

When the user hits Start Request button, the callout is made to the URL. Once the response is sent, processResponse method will be called. statusBool variable will be true when the request is hit and it shows the message. Once we get the response, statusBool will be false and hide the message.

How To Create Survey Using Salesforce Surveys?

1. Go to Survey Settings.


2. Enable Surveys and Select the Community.

Note:
To create surveys that are accessible to people who don’t have Salesforce accounts in your company, select a community.


3. Create a Permission Set and give access to Surveys and Survey Invitations objects.



4. Assign the Permission Set to the user who wants to create Surveys.

Salesforce Spring '18 Release Overview

Einstein Forecasting

With Einstein Forecasting, trade guesswork for accurate forecasts at the rep, team, and company levels. Machine learning spotlights the key business factors driving sales predictions, making insights immediate and actionable. And you can quickly address the most valuable and at-risk deals with Opportunity Scoring.

Lightning Dialer Call Monitoring

With Lightning Dialer Call Monitoring, managers can listen in to their sales reps’ phone conversations with customers and prospects and give real-time input. Feedback, commentary, and encouragement help sales reps immediately understand where to improve, where they’re doing well, and where they can improve their skills.

Macros in Lightning Sales Console

Macros are available in Lightning Sales Console.

Opportunity Splits in Lightning Experience

Opportunity Splits is available in Lightning Experience

Omni-Channel Setup Flow

Omni-Channel Setup Flow makes it easy for admins to set up multiple queues so agents can sit back and wait for the cases to roll in.

Add Pinned Regions to Your Console Pages and Never Toggle Tabs Again

A pinned region remains displayed as you navigate between subtabs in a Lightning console app. Customize your Lightning console app with pinned region pages so that console users can view and work with record information on different subtabs. Choose from three templates to pin a page’s header, left sidebar, or both. Previously, this feature was available only in Salesforce Classic Consoles. This feature is new in Lightning Experience.

Snap-Ins Pre-chat form

Now in Spring ’18, customize the pre-chat form and use direct-to-button routing, automated invitations, and sensitive data rules to ensure you’re delivering a personalized experience to your customers.

Schedule Service Crews

Service crews, introduced in Winter ’18, are now available for scheduling in the Field Service Lightning managed package. Assign predefined teams of workers to service appointments, saving time and ensuring that every appointment is handled by the right workers.

Get Field Service on the Road with Guided Setup

The Field Service guided setup steps you through creating service territories and operating hours, defining your work types and skill sets, assigning your agents, dispatchers, and service resources, and configuring your scheduling policies. You can use the guided setup as often as you like to adjust your field service setup.

GDPR Compliance Support

On May 25, 2018, a new landmark privacy law called the General Data Protection Regulation (GDPR) takes effect in the European Union. Marketing Cloud GDPR readiness will address four key areas: consent management, data deletion (right to be forgotten), restriction of processing, and data portability.

Know How Well Your Community Deflects Cases

Get insight into how well the Contact Support Form and Case Deflection components actually deflect cases from being created. Using the Case Deflection Dashboard, get real-time metrics on potential and confirmed case deflections, the most helpful articles and discussions, and the least helpful articles and discussions.

Calendar Component

Organize your events and view other users’ calendars in one view directly from your community. Access Salesforce calendars from your Lightning community and share your calendar with others

Report Builder in Lightning Experience

The new report builder in Lightning Experience is now available.

MySalesforce

Custom brand every employee’s mobile experience. With mySalesforce, customers can publish Salesforce apps in the App Store and Google Play with their own branding.

Private Space Peering

Build secure multi cloud apps that span AWS and Salesforce. Heroku Private Space Peering connects the isolated private space network to apps and services in Amazon Virtual Public Clouds that are controlled by the customer.

Platform Encryption

In the Spring ’18 Release, new fields available for encryption include opportunity name, description, next step, contract address, and individual’s name. New Encryption Statistics offers increased visibility into how much of the org’s field and file data is encrypted at rest, and whether they’re using the most current, active key.


Salesforce Surveys

Get intelligent assessments inside your CRM. With Salesforce Surveys, users can create beautiful, easy-to-use forms for collecting feedback and data using the Salesforce platform. These flexible survey and assessment tools are designed to enhance customer engagement and can be sent with one click. Watch the results roll in on reports and dashboards inside Salesforce.

Personalized Navigation

As part of myLightning, Personalized Navigation in Lightning Experience lets you personalize the navigation bar to suit the unique way you work. You can reorder items, and even rename or remove items you’ve added. You can even add temporary tabs to the navigation bar to access items like a dashboard, list, or record, and make the temporary tab permanent.

Dynamic Lightning Pages

Make your Lightning app and home pages dynamic. As part of myLightning, Dynamic Lightning pages let you control when a component appears on a Lightning record page by adding filter conditions and logic to its properties.

Lightning Flow

As part of myLightning, Lightning Flow lets you build flows with Lightning components on your screens. You can make your flows a beautiful guided experience by overriding the elements of the flow with the design built by your Lightning component.

Save Time by Cloning Sandboxes (Beta)

You can create a sandbox by cloning an existing sandbox rather than using your production org as your source. Save time by customizing a sandbox with a set of data and metadata and then replicating it. Sandbox cloning simplifies having multiple concurrent streams of work in your application lifecycle.

Change Package Primary Contact

The Primary Contact name is visible to ISVs from the Push Package Upgrade page, where it initially displays the name of the person who installed the package in a subscriber org. Previously, it could not be changed. If you have the Download AppExchange Packages permission, you can now choose Become Primary Contact from the Installed Packages page to become the primary contact for a package.

Remove Deprecated Package Archives

ISVs can now request that Salesforce delete zip files for old versions of a managed package if needed for data privacy reasons.

Clear All Reminders at Once

No more sifting through individual reminders. Clear all task and event reminders with one click. The Clear All button appears after you’ve received a fourth notification. After you clear all reminders, only new reminders appear. This feature is new in Lightning Experience.

Use Web Tabs to Display Third-Party Content in the Lightning Console

Let Lightning console users access web applications or other websites from within the application. Use the openTab or openSubtab JavaScript API methods to open web tabs inside Lightning console apps. Third-party domains such as https://www.yourappdomain.com must be whitelisted in the CSP Trusted Sites. This feature is new in Lightning Experience.

Gather Feedback from Your Community with the Survey Component

The Survey component embeds an active survey into any Lightning community template. When your community members log in, they have the option to participate in the survey.

http://www.infallibletechie.com/2018/04/how-to-create-survey-using-salesforce.html

Organize Your Community’s Content Up to Eight Levels with Navigational Topics

Navigational topics are a fantastic tool to organize your community’s content for your members. Previously, you were limited to three levels of content organization—a parent, a child, and a grandchild topic. Now you can go up to eight levels and organize to your heart’s content. It’s now much easier to match your community topic hierarchy to your actual product catalog, which my go deeper than three levels. Add up to 25 navigational topics and 10 subtopics for each topic. Each subtopic can also have 10 subtopics. You can create five more levels of subtopics with the API, for a combined maximum of 2,775 navigational topics and subtopics per community.

How to give access to Lightning Sync Setup, Configurations, and Status pages in Salesforce Setup

To access Lightning Sync setup, below permissions are required

1. Customize Application

2. Manage Users

3. Manage Lightning Sync

These permissions under System Permissions in Profile/Permission Set gives access to Lightning Sync Setup, Configurations, and Status pages in Salesforce Setup.


Users with these permissions can add config, edit config, add/remove users in the config and so on.

How to tackle technical debt in Salesforce?

Technical debt (also known as design debt or code debt) is a concept in software development that reflects the implied cost of additional rework caused by choosing an easy solution now instead of using a better approach that would take longer.

In Salesforce context

1. Poor Customization(Point and Click and Coding)
2. Bad Configuration(Report, List Views, etc)
3. Bad design and not following standard and best practices

How to overcome?

Following are some possible ways

1. Utilize Salesforce out of box feature rather than building custom solution.

2. Follow Salesforce standard and best practices.

3. Implement exception handling in the code and capture all the exceptions in a Custom object to handle it.

4. Set API usage notification - http://www.infallibletechie.com/2017/04/api-usage-notifications-in-salesforce.html as a proactive step to catch the API limits.

5. Set Up Governor Limit Email Warnings in Salesforce - http://www.infallibletechie.com/2017/04/set-up-governor-limit-email-warnings-in.html.

6. Increase the API version of the component when you get an opportunity to update/enhance it.

7. Use Salesforce Optimizer - http://www.infallibletechie.com/2017/02/salesforce-optimizer.html.

8. Use Code Scanner from Salesforce - http://www.infallibletechie.com/2015/03/how-to-check-code-quality-in-salesforce.html.

7. Use Field Trip AppExchange to find the usage of fields.

8. Use Salesforce Adoption Dashboards AppExchange product to find the user adoption.

9. Develop Test Class to test your code instead of cheating to achieve code coverage.

10. Utilize Trailhead, Release notes from Salesforce, Certifications, etc.

11. Utilize Query Plan for SOQLs - http://www.infallibletechie.com/2015/07/query-plan-in-salesforce.html.

12. Apex Exception Email in Salesforce - http://www.infallibletechie.com/2018/08/apex-exception-email-in-salesforce.html


Sync both ways not showing in Lightning Sync in Salesforce

Few Considerations to use Bi-directional sync with Lightning Sync:

1. "Sync both ways" sync setting option will only appear under Events, if you have Lightning Experience enabled on your Salesforce Org.

2. Events from Salesforce will only sync if they are created either from Lightning Experience (LEX) or Salesforce for iOS and Android. Events created or edited from Salesforce Classic don’t sync with Google/Microsoft outlook calendar.

3. ​If the Events are created in Salesforce using API like Workbench/Dataloader or through visualforce pages or synced using any other third-party integrations, they will not sync using Lightning Sync.

Check the below link for additional questions

https://help.salesforce.com/articleView?id=000268388&type=1

Lightning for Gmail and Sync Salesforce

1. Go to Lightning for Gmail and Sync Settings.


2. Enable Lightning Sync.


3. Click Register Site and add https://www.googleapis.com to the Remote Site Settings.


4. In Prepare your G Suite account, add the JSON file shared by your Google Admin.

5. In Test Your Connection, enter your email address and click Test button to verify it.


6. Click New Config.


7. Click New Lightning Sync Configuration.


8. Enter Name, Description and setup settings for Contacts and Events.

Note:
1. Lightning Sync for Google requires a G Suite account.
2. Sync both ways not showing in Lightning Sync - http://www.infallibletechie.com/2018/04/sync-both-ways-not-showing-in-lightning.html

Moderate Chatter Free Users in Salesforce

A moderator is a Chatter user with some additional privileges.

These privileges include:
Activate or deactivate Chatter Free users
Assign a Chatter Free user as moderator or take the privilege away
Delete posts and comments that they can see

To make a user as Chatter user as Moderator:


To remove a Chatter user as Moderator:


Do external objects in Salesforce take up space?

External objects are not stored in Salesforce. So, it does not count towards your storage limit.

Use the below link to monitor storage and data resources

https://help.salesforce.com/articleView?id=admin_monitorresources.htm&type=5

As per the above link, External Objects are not included for storage calculation in Salesforce, so it won't take any space or storage from Salesforce.

How to use onsuccess action in lightning:recordEditForm?

Sample Code:

Component:

<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable" >
    
    <lightning:recordEditForm recordId="0036A00000QAY0CQAX" objectApiName="Contact" onsuccess="{!c.callSuccess}">
        <lightning:messages />
        <lightning:inputField fieldName="FirstName" />
        <lightning:inputField fieldName="LastName" />
        <lightning:inputField fieldName="Email" />
        <lightning:button class="slds-m-top_small" variant="brand" type="submit" name="update" label="Update"/>                          
    </lightning:recordEditForm>
    

</aura:component>

Controller:

({
callSuccess : function(component, event, helper) {
            var params = event.getParams();
            alert(params.response.id);
}

})

Output:


Mapping field between Accounts and Contacts

Account is the mapping field between Accounts and Contacts.


Create Multiple Opportunities on Lead Conversion in Salesforce

There are multiple ways to create multiple opportunities on lead conversion in Salesforce.

Check the below link for Salesforce recommended solution

https://help.salesforce.com/articleView?id=000220210&type=1

Vote for this idea too - https://success.salesforce.com/ideaView?id=08730000000BpFhAAK

Generate Leads from LinkedIn in Salesforce

This feature automatically add leads to Salesforce from LinkedIn Lead Gen advertisements.

1. Go to https://business.linkedin.com/marketing-solutions/native-advertising/lead-gen-ads and create a form.

2. Go to LinkedIn Accounts in Salesforce


3. Click Connect LinkedIn Member Account.


4. Enter the credentials.

5. Go to Lead Gen Fields to map the fields.


Note:
1. Use your business LinkedIn Account.
2. You can get up to 500 leads per day.

How to count the child records for each parent record in Salesforce?

Sample SOQL:

SELECT AccountId, COUNT(Id) ContactCount FROM Contact GROUP BY AccountId

Output:


Apex Design Patterns in Salesforce

Singleton:
The Singleton pattern attempts to solve the issue of repeatedly using an object instance, but only wishing to instantiate it once within a single transaction context.

Sample Code:

Apex Class:
public class Utility {
    
    public static Utility objInstance = null;
    public Integer acctCount;
    
    public Utility() {
        acctCount = [ SELECT COUNT() FROM Account ];
    }
    
    public static Utility getInstance() {
        if ( objInstance == null )
            objInstance = new Utility();
        return objInstance;
    }
    
}

If you execute the below code, the SOQL will be executed only once.

for ( Integer i = 0; i < 3; i++ ) {
    Utility obj = Utility.getInstance();
    system.debug('Count is ' + obj.acctCount);
}



Strategy:
Defining a family of algorithms, enscapsulating each one and making them interchangeable and selectable at runtime.

Sample Code:

1. Create an interface.

public interface Strategy {

   Integer doOperation(Integer num1, Integer num2);
   
}

2. Create concrete classes implementing the same interface.

public class OperationAdd implements Strategy {

   public Integer doOperation(Integer num1, Integer num2) {
      return num1 + num2;
   }
   
}

public class OperationSubstract implements Strategy {

   public Integer doOperation(Integer num1, Integer num2) {
      return num1 - num2;
   }
   
}

3. Create Context Class.

public class Context {

   private Strategy strategy;

   public Context(Strategy strategy) {
      this.strategy = strategy;
   }

   public Integer executeStrategy(Integer num1, Integer num2) {
      return strategy.doOperation(num1, num2);
   }
   
}

4. Use the Context to see change in behaviour when it changes its Strategy.

      Context context = new Context(new OperationAdd());
      System.debug('10 + 5 = ' + context.executeStrategy(10, 5));

      context = new Context(new OperationSubstract());
      System.debug('10 - 5 = ' + context.executeStrategy(10, 5));


Decorator:
Extending the functionality of an sObject in Apex.

Example is Wrapper Class - http://www.infallibletechie.com/2015/03/sample-wrapper-class-using-apex-in.html

Facade:
Simplifying the execution of classes with complex interfaces (e.g. web service callouts).

Sample Code:

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

/* Facade */

class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

Composite:
Treating a group of objects in a similar manner to a single instance of that object. Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.

Sample Code:

Apex Class:

public class Employee {

   private String name;
   private String dept;
   private Integer salary;
   private List<Employee> subordinates;

   // constructor
   public Employee(String name,String dept, Integer sal) {
      this.name = name;
      this.dept = dept;
      this.salary = sal;
      subordinates = new List < Employee >();
   }

   public void add(Employee e) {
      subordinates.add(e);
   }

   public List<Employee> getSubordinates() {
     return subordinates;
   }

}

Execute the below code to set the hierarchy and view the debug log.
      
      Employee CEO = new Employee('John','CEO', 30000);

      Employee headSales = new Employee('Robert','Head Sales', 20000);

      Employee headMarketing = new Employee('Michel','Head Marketing', 20000);

      Employee clerk1 = new Employee('Laura','Marketing', 10000);
      Employee clerk2 = new Employee('Bob','Marketing', 10000);

      Employee salesExecutive1 = new Employee('Richard','Sales', 10000);
      Employee salesExecutive2 = new Employee('Rob','Sales', 10000);

      CEO.add(headSales);
      CEO.add(headMarketing);

      headSales.add(salesExecutive1);
      headSales.add(salesExecutive2);

      headMarketing.add(clerk1);
      headMarketing.add(clerk2);

      //print all employees of the organization
      System.debug(CEO); 
      
      for ( Employee headEmployee : CEO.getSubordinates() ) {
         System.debug(headEmployee);
         
         for ( Employee employee : headEmployee.getSubordinates() ) {
            System.debug(employee);
         }

      }


Bulk State Transition:
Efficiently tracking the change of a field value in a trigger and executing functionality based on this change.

Example is bulking the trigger.

How To Get The Record Count Of SOQL query into a variable in Salesforce?

Sample Code:

    public static Integer findAcctCount() {
        return [ SELECT COUNT() FROM Account ];
    }

Or

Integer i = [ SELECT COUNT() FROM Account ]; 

Formula Fields and Workflow Field Updates

Both are easy to configure and no code is involved.

Formula Fields 

1. Changes in Parent record will be automatically reflected in child records.
2. Change in Formula field cannot invoke trigger or workflows.
3. Formula field values cannot be modified manually.

Workflow Field Updates

1. Changes in Parent record cannot be updated in child records.
2. If the record was updated with workflow field updates, fires before and after triggers one more time. Custom validation rules, duplicate rules, and escalation rules are not run again.
3. It considers criteria before updating the field value.

Workflow field update is recommended over formula field for better performance.

App under App Manager is not visible in Lightning Experience

Edit the app and enable Show in Lightning Experience.


Using Custom Permission in Workflow Rule in Salesforce

Select formula evaluates to true in the Workflow Rule.


$A.getCallback() usage for polling in Lightning Component

Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call. The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

Sample Code:

Component:

<aura:component implements="force:appHostable">
    
    <aura:attribute type="Integer" name="count" default="1"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <div class="slds-box slds-theme_default">
        {!v.count}
    </div>
        

</aura:component>

Controller:

({
    doInit : function(component, event, helper) {
        //execute again after 5 sec each
        window.setInterval(
            $A.getCallback(function() { 
                helper.increment(component,helper);
            }), 5000
        ); 
    }

})

Helper:

({
increment : function(component, event) {
var i = component.get("v.count");
        component.set("v.count", i+1);
}

})

Output:


SVG in Lightning Component Bundle

Sample Code:

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg xmlns="http://www.w3.org/2000/svg"
     width="400" height="400">
  <circle cx="100" cy="100" r="100" stroke="black"
    stroke-width="5" fill="red" />

</svg>

Output:


Documentation in Lightning Bundle in Salesforce

Sample code:

<aura:documentation>
    <aura:description>
        <h1>Documentation of Sample Component</h1>
    </aura:description>
<aura:example name="Sample" ref="c:Sample" label="Sample Component">
Sample component view.
</aura:example>
</aura:documentation>

description is to show the description of the component. example is to show look and feel of the component.

The documentation you create will be available at https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the name of your custom Salesforce domain and in the Component Library (Beta) at https://<myDomain>.lightning.force.com/componentReference/suite.app where <myDomain> is the name of your custom Salesforce domain.



Advantages of Lightning Data Service in Salesforce

1. Used to load, create, edit, or delete a record in your component without requiring Apex code
2. Handles Sharing Rules
3. Handles Field Level Security
4. Consistent User Interface
5. Better performance

Examples:

http://www.infallibletechie.com/2017/11/forcecreaterecord-example-in-salesforce.html

http://www.infallibletechie.com/2018/02/forceeditrecord-example-in-salesforce.html

Salesforce Interview Questions with Answers Part 51

1. How to get the current hour in the local time zone of the context user using apex in Salesforce?

hour() returns the hour component of a Datetime in the local time zone of the context user.

http://www.infallibletechie.com/2018/02/how-to-get-current-hour-in-local-time.html

2. What is the use of nextStartDate?

Starting from the specified target date, returns the next date when business hours are open. If the specified target date falls within business hours, this target date is returned.

http://www.infallibletechie.com/2018/02/what-is-use-of-nextstartdate.html

3. Types of events in Lightning in Salesforce

Component events are handled by the component itself or a component that instantiates or contains the component.
Application events are handled by all components that are listening to the event. These events are essentially a traditional publish-subscribe model.

4. Lightning Data Service

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 not needing Apex, Lightning Data Service improves performance and user interface consistency.

Examples:

http://www.infallibletechie.com/2017/11/forcecreaterecord-example-in-salesforce.html

http://www.infallibletechie.com/2018/02/forceeditrecord-example-in-salesforce.html

5. What is Concurrent Request Limit in Salesforce?

Once a synchronous Apex request runs longer than 5 seconds, it begins counting against this limit. Each organization is allowed 10 concurrent long-running requests. If the limit is reached, any new synchronous Apex request results in a runtime exception. This behavior occurs until the organization’s requests are below the limit.

Some useful tips:

a. Convert synchronous processes to asynchronous processes. Batch Apex might be a viable alternative. Limit synchronous Web service callouts.
b. Use the Streaming API instead of polling
c. Tune SOQL and DML operations. Make sure that your queries are selective. Limit the number of records in your list views. Avoid data skew.

6. What is the use of Individual object and how to enable it?

Represents a customer’s data privacy and protection preferences. Data privacy records based on the Individual object store customer's privacy preferences and are associated with a lead or a contact.

http://www.infallibletechie.com/2018/03/what-is-use-of-individual-object-and.html

7. With SeeAllData=true, will changes to live data be visible to the user?

No. Only the test method will see those changes, because an incomplete transaction is "isolated" from the rest of the database. This means that at no point will the changes made in the test method will be visible to any user.

8. How to navigate from one component to the other component in Salesforce lightning?

force:navigateToComponent can be used.

Sample Code - http://www.infallibletechie.com/2018/03/lightning-component-navigation-in.html

9. force:hasRecordId

Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record. The current record ID is useful if the component is used on a Lightning record page, as an object-specific custom action or action override in Lightning Experience or the Salesforce app, and so on.

If your component implements force:hasRecordId, you don’t need to add a recordId attribute to the component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a runtime error.

The recordId attribute is set only when you place or invoke the component in an explicit record context. For example, when you place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home. In all other cases, such as when you invoke the component as a global action, or create the component programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.

http://www.infallibletechie.com/2018/03/forcehasrecordid-in-custom-lightning.html

10. What is the use of Time-Based Workflow under Monitor in Setup?

Time-Based Workflow shows only pending actions and allow us to cancel them if necessary.

11. Why trigger over workflow field update and process builder?

If field update is done using Process builder, then record will go through complete Save cycle again.

If field update is done using Workflow field update, then Custom validation rules, duplicate rules, and escalation rules will not run again.

If trigger is already written then instead of creating workflow or process builder field update, it is best to use existing trigger for field update. Multiple execution of trigger could cause hitting various governor limits like SOQL query or concurrent apex limit.

12. How to secure Outbound Message in Salesforce?

You configure an outbound message to include a sessionId and specify a user in the User to send as field. The user doesn’t have outbound messaging disabled.

Your application (endpoint) server's SSL/TLS may be configured to require client certificates (two-way SSL/TLS), in order to validate the identity of the Salesforce server when it takes the role of client to your server. If this is the case, you can download the Salesforce client certificate from the Salesforce application user interface. This is the client certificate that Salesforce sends with each outbound message for authentication.

a. Go to API.
b. On the API WSDL page, click Manage API Client Certificate.
c. On the Certificate and Key Management page, in the API Client Certificate section, click the API Client Certificate.
d. On the Certificates page, click Download Certificate. The .crt file is saved in the download location specified in your browser.
e. Import the downloaded certificate into your application server, and configure your application server to request the client certificate. The application server then checks that the certificate used in the SSL/TLS handshake matches the one you downloaded.

13. Use of Documentation in Lightning Bundle in Salesforce

description is to show the description of the component. example is to show look and feel of the component.

The documentation you create will be available at https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the name of your custom Salesforce domain and in the Component Library (Beta) at https://<myDomain>.lightning.force.com/componentReference/suite.app where <myDomain> is the name of your custom Salesforce domain.

http://www.infallibletechie.com/2018/04/documentation-in-lightning-bundle-in.html

14. Use of SVG in Lightning Component Bundle

You can use an SVG resource to define a custom icon for your component when it appears in the Lightning App Builder’s component pane. Include it in the component bundle.

http://www.infallibletechie.com/2018/04/svg-in-lightning-component-bundle.html

15. $A.getCallback()

Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call. The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

http://www.infallibletechie.com/2018/04/agetcallback-usage-for-polling-in.html

16. Difference between Database.query() and Database.getQueryLocator

http://www.infallibletechie.com/2013/05/difference-between-databasequery-and.html

17. What happens when SELECT COUNT() FROM Employee__c is executed in a trigger for a user who doesn't have access to Employee object?

It will return the no of records in the employee object.

18. What happens when SELECT COUNT() FROM Employee__c is executed in a trigger handler with "with sharing" keyword for a user who doesn't have access to Employee object?

It will return 0.

19. What happens when SELECT COUNT() FROM Employee__c is executed in a trigger handler with "without sharing" keyword or with no sharing keyword(public class classname) for a user who doesn't have access to Employee object?

It will return the no of records in the employee object.