Adsense

Showing posts with label Salesforce. Show all posts
Showing posts with label Salesforce. Show all posts

April 15, 2020

Salesforce Process Builder

Salesforce Process Builder
Process Builder is a tool provided by Salesforce to automate your business process via point and click.For Example:If Amount has crossed its threshold(1000) then send a notification to the sales representative with the details.


Actions Available In Process Builder
There are several different actions you can trigger the process builder. These actions are:
  • Trigger Apex code: You can use the Salesforce process builder to invoke Apex code you have written within Salesforce. Apex can be anything from custom logic to save a record to complex business processes. To invoke an apex class in process builder we have to use @InvocableMethod attribute.Example:There is a Apex class named CampingListController having a method defined as @InvocableMethod. Hence we can call this method from Process builder as shown below:
    Calling Apex from Process Builder
  • Create a record: This will allow you to create new records and set certain field values for the new record.Example: When an opportunity is 'Closed Won' then create a case for the sales team.
    New Case Creation
  • Email alerts: Once a criteria is met then you can send a notification to pre defined user. To do so you first create an email alert and associate it with an existing Email Template. Email Template will be having the format in which recipients will get the message.Example: If Opportunity is 'Closed Won' and Account's industry is Banking then send an email alert to users.
    Process Builder to send email alert
  • Trigger a flow: You can launch a flow from your process to automate complex business processes.Only active autolaunch flows can be launched from Process Builder. It can launch active flows which do not contain screens.Example: If Opportunity is 'Closed Won' and Account's industry is Banking then launch a flow for his/her experience on the Opportunity journey.
  • Post to Chatter: Process builder post to chatter action helps to post information to any user or group chatter feed within Salesforce. The post will appear in the chatter field as if the person who triggered the process had written it. You can reference groups or topics and add merge fields.Example: When a case status is changed, post to chatter so that user knows that some action has been taken on the case.
    Process Builder posting to Chatter
  • Submit for approval: Only the record that started the process will be submitted. You can’t submit any related records for approval.
  • Update records: Update one or more records that are related to the record that started the process. You can update the record with manually entered values or by using the values from related records. We can update records of parent or child whereas workflow only updates same or parent object from the child.
  • Quick actions: You must already have global actions or an object specific action created within Salesforce to use these quick actions. You can then select to log a call, send an email, or update a record.Example: A contact will be created for Camping Item once the flow returns a CampList item.
    Quick Action via Process Builder
  • Process: This action will call another process to another process. For this action, you need to choose process type as it invoked by another process.You can invoke processes with objects that share at least one unique ID. For example, in the Account and Case objects, the AccountId field is unique to Account and also used by Case. You can create an invocable process that updates a Case record. Then you can invoke it from:
           A process that updates an Account record’s owner
               A process that adds an Account shipping address or updates it


Read More »

March 13, 2020

WhoId and WhatId in salesforce

WhoID in Salesforce refers to people things. So that would be typically a Lead ID or a Contact ID. The WhoId represents a human such as a lead or a contact. WhoIds are polymorphic. Polymorphic means a WhoId is equivalent to a contact ID or a lead ID. The label is Name ID.

Example: Use of whoId in salesforce. Create a visualforce page:

<apex:page controller="checkwhocontroller" >
<apex:pageBlock>
<apex:pageBlocktable value="{!mywho}" var="w">
  <apex:column width="400px">
                  <apex:facet name="header">Name</apex:facet>
<apex:outputLink value="/{!w.whoid}" >
                        <apex:outputText value="{!w.who.name}"/>
                   </apex:outputLink>
        </apex:column>
        </apex:pageBlocktable>
</apex:pageBlock>
</apex:page>

Apex Class:
public class checkwhocontroller {
    public Task[] getMywho() {
    task[] mytaskArray = new task[]{};
    mytaskArray=[SELECT Subject, Who.Name FROM Task LIMIT 20];

        return mytaskArray;
    }
}


WhatID in Salesforce refers to object type things. That would typically be an Account ID or an Opportunity ID. The WhatId represents nonhuman objects such as accounts, opportunities, campaigns, cases, or custom objects. WhatIds are polymorphic. Polymorphic means a WhatId is equivalent to the ID of a related object.The label is Related To ID.

Example: Create a task whenever a case is inserted into salesforce.

trigger CaseTrigger on Case (after insert, after update){
    List<task> taskList = new List<task>();
    for (Case c : trigger.new){
        //Create a task when case is created
        if(trigger.isInsert){
            task t = new task();
            t.whatId = c.Id;
            t.Subject = c.Subject;
            taskList.add(t);
        }
    }
insert taskList;
}
Read More »

November 30, 2019

Queueable Apex - The middle way

The last post was a comparison between batch apex and @future apex. There are some advantage and disadvantage with both of them. When batch and @future needs to meet in between - queueable comes for rescue.

There are a few things that @future did not provide:
  1. @future requires the arguments be primitives, which means reconstructing a structure once the method is called.
  2. Difficult access to job ID. The executeBatch method returns a jobID, while calling an @future job does not give you the ID of the related job.
  3. No chaining - Chaining of batch apex is not allowed.
Q - Why we go for queueable Apex?
A - When the job such as extensive database operations or external Web service callouts is long running and is running asynchronously and you want to monitor the job status. It can be done via queueable apex and adding a job to the ApexJob queue. In this way, your asynchronous Apex job runs in the background in its own thread and doesn’t delay the execution of your main Apex logic.

Queueable jobs are similar to future methods in that they’re both queued for execution, but they provide you with these additional benefits.

Getting an ID for your job: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record.
This ID helps you identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.

Using non-primitive types: Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types.

Chaining Jobs: In queueable you can also chain Jobs from a running job. It is very helpful if some processing needs to be done which depends on the last results.

Example:
This example is an implementation of the Queueable interface. The execute method in this example inserts a new account.

public class QueueableExample implements Queueable {

    public void execute(QueueableContext context) {
        Account acc = new Account(Name='Test Account Neeraj');
        Insert acc;     
    }
}

To add this class as a job on the queue, call this method:
ID jobID = System.enqueueJob(new QueueableExample());

After you submit your queueable class for execution, the job is added to the queue and will be processed when system resources become available. We can monitor the status of our job programmatically by querying AsyncApexJob or through the user interface Setup --> Monitor --> Jobs --> Apex Jobs.

Test class for queueable apex:

@isTest
public class AsyncExecutionExampleTest {
    static testmethod void testAccount() {
     
        Test.startTest();     
        System.enqueueJob(new QueueableExample());
        Test.stopTest();

        Account acct = [SELECT Name FROM Account WHERE Name='Test Account Neeraj' LIMIT 1];
        System.assertEquals('Test Account Neeraj', acct.Name);
    }
}

Few things can be noted here:

  • The execution of a queued job counts against the shared limit for asynchronous Apex method executions.
  • We can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
  • Use Limits.getQueueableJobs() to check how many queueable jobs have been added in one transaction.
  • No limit is enforced on the depth of chained jobs.
  • We can add only one job from an executing job with System.enqueueJob, that means only child job can exist for parent queueable job.

Read More »

October 06, 2019

@Future vs Batch Apex in salesforce

Future Annotation: 
  1. Future Annotation(@Future) is used to separate methods that are to be executed asynchronously.
  2. If Future Annotation is not used in a web service callout, the thread will wait until the response comes and other processes will not be executed.
  3. Mixed DML Exception can be avoided with the use of @future annotation.
  4. @future annotation - Must be static and return void - Specify (callout=true) to allow callouts.
  5. Parameters passed to this can only be primitive.
  6. Tracking future is difficult as you don't have any jobId to track it.
  7. Future can be used to resolve mixed DML exception.
Example: You cannot insert a setup object and a non-setup object in same context. You'll encounter mixed DML exception. @Future comes for rescue in this situation.
public class MixedDMLFuture {
    public static void useFutureMethod() { 
        //First DML operation- Insertion of non-setup object(Account)
        Account a = new Account(Name='Vydehi Hospital'); 
        insert a; 
        
        // This next operation (insert a user with a role)  can't be mixed with the previous insert unless it is within a future method. 
        /*// Other DML Operation -- commented the code with a reason, if you use the commented code you will get mixed DML exception error
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        UserRole r = [SELECT Id FROM UserRole WHERE Name='COO']; 
        // Create new user with a non-null user role ID 
        User u = new User(alias = 'ranvk', email='dummyMail@gmail',                   
                          emailencodingkey='UTF-8', lastname='niru',languagelocalekey='en_US',     
                          localesidkey='en_US', profileid = p.Id, userroleid = r.Id,  
                          timezonesidkey='America/Los_Angeles',  
                          username='dM@gmail.com'); 
        insert u; */
        //Call future method to insert a user(setup object) with a role. 
        UtilClass.insertUserWithRole( 'dummyMail@gmail.com', 'ranvk', 'dM@gmail.com', 'niru'); 
    } 
}

public class UtilClass { 
      @future 
       public static void insertUserWithRole(String uname, String al, String em, String lname) { 
               Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
               UserRole r = [SELECT Id FROM UserRole WHERE Name='COO']; 
               // Create new user with a non-null user role ID 
               User u = new User(alias = al, email=em, emailencodingkey='UTF-8',   
                              lastname=lname, languagelocalekey='en_US', localesidkey='en_US', 
                              profileid = p.Id, userroleid = r.Id, timezonesidkey='America/Los_Angeles',  
                              username=uname); 
               insert u; 
       } 
}


Batch Apex:
  1. Batch Apex is used to separate tasks that are going to handle more records(complex long running jobs) in background process. 
  2. To avoid hitting governor limits we use Batch Apex for handling bulk records.
  3. It can process up to 50 million records. It can also be scheduled to run at a particular time.
  4. Only 5 concurrent batch can execute simultaneously. It is difficult to track the progress of the execution.
  5. We cannot use @future annotation. As asynchronous call is not allowed from batch apex.


Example: Delete all the account having Rating 'Cold'
global class deleteAccounts implements Database.Batchable{
global Database.QueryLocator start(Database.BatchableContext BC){
string query = 'select id,name,Rating,Owner from Account';
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC,List scope){
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope){
Account a = new Account();
if(s.Rating=='Cold'){
lstAccount.add(a);
}
}
Delete lstAccount;
}

global void finish(Database.BatchableContext BC){
//Send an email to the User after your batch completes
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'dummyemail@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is completed');
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Read More »

September 29, 2019

Salesforce - Test Class Best Practice

Before we talk on best practices we should be following while writing a test class, let's discuss what a test class is and why it is needed.
Test class in Salesforce is a kind of framework which provides you a platform to supply data to your apex class and see how your apex is behaving. 
It is needed as testing is an important part of SDLC. So, before deploying your code to production environment, Salesforce requires at least 75% of your code to be covered by your test classes to make sure that your code doesn't break in any situation in Production.

We should be following below points while writing test class:


  1. Use @isTest at the Top for all the test classes.
  2. Always put assert statements for negative and positive tests.
  3. Use the @testSetup method to insert the test data into Test class that will flow all over the test class.
  4. Always use Test.startTest() and Test.stopTest() doing this it will increase the governor limit of Salesforce. We also use this to increase the governor limit.
  5. Use System.runAs() method to test the functionality in user Context.
  6. Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.
  7. Avoid Using Hard Coding Ids anywhere in test Class or any apex class.
  8. Please make sure that each class has minimum 75% coverage and also the main functionality has been covered. Target 100% code coverage.
  9. All class method must be tested for at least 20 records and keep the real scenarios in mind.
  10. Use the ORDER BY keywords to ensure that the records are returned in the expected order. 

Best Practices for Parallel Test Execution


Tests that are started from the Salesforce user interface (including the Developer Console) run in parallel. Parallel test execution can speed up test run time. Sometimes, parallel test execution results in data contention issues and UNABLE_TO_LOCK_ROW error occur.
When a deadlock occurs in tests that are running in parallel and that try to create records with duplicate index field values. A deadlock occurs when two running tests are waiting for each other to roll back data. Such a wait can happen if two tests insert records with the same unique index field values in different orders.

This can be prevented by turning off parallel test execution in the Salesforce user interface:

  1. From Setup, enter Apex Test.
  2. Click Options...
  3. In the Apex Test Execution Options dialog, select Disable Parallel Apex Testing and then click OK.
Apex test execution option


Test classes annotated with IsTest(isParallel=true) indicate that the test class can run concurrently with more than the default number of concurrent test classes. This annotation overrides default settings.
Read More »

September 15, 2019

Salesforce execution sequence


When a record is saved in salesforce with insert, update or upsert statement, salesforce performs below event in sequence behind the scene.
  1. Runs Client side validations: The browser runs javascript to check if there is any dependent picklist field is present. If yes then it prompts user to fill the value or throws error on UI.
  2. Loading/Initializing: Loads the original record from the database or initializes the record for an upsert statement.
  3. Loads the new record field values from the request and overwrites the old values: Say Account's shipping address is being changed from Pune to Mumbai, then Pune is retrieved from database and its overwritten with value Mumbai
  4. Executes all before triggers.
  5. Runs most system validation steps again: Such as verifying that all required fields have a non-null value, and runs any user-defined validation rules(Say Account's billing country can't be left blank). 
  6. Execute Duplicate rules: Duplicate rules are implemented to reduce the potential insertion of Account with the same name.
  7. Saves the record to the database, but doesn't commit yet: Soft save, not available for SOQL yet.
  8. Executes all after triggers.
  9. Executes assignment rules: Assignment rule is created on Case and Lead object. An assignment rule dictates to whom a lead or case is assigned based on criteria that is specified within Salesforce.
  10. Execute auto-response rules: An auto-response rule is a set of conditions for sending automatic email responses to lead or case submissions based on the attributes of the submitted record.
  11. Executes workflow rules: Workflow lets you automate standard internal procedures and processes to save time across your org. A workflow rule is the main container for a set of workflow instructions. These instructions can always be summed up in an if/then statement.
  12. If there are workflow field updates, updates the record again.
  13. If the record was updated with workflow field updates, fires before update triggers and after update triggers one more time (and only one more time), in addition to standard validations. Custom validation rules, duplicate rules, and escalation rules are not run again.
  14. Executes processes and flows launched via processes and flow trigger workflow actions.
  15. Executes escalation rules: are used to escalate cases automatically when they meet the criteria which are defined in rule entry. We create rule entries where criteria is defined to escalate a case.
  16. Executes entitlement rules.
  17. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
  18. Executes Criteria Based Sharing evaluation.
  19. Commits all DML operations: Here the record will be actually saved to database and the transaction will complete.
  20. Executes post logic: Once the record is saved to database, some post logic will be performed like sending mail to customers, updating a formula field etc

Read More »

September 06, 2019

Salesforce Basics

In recent years, we are hearing a buzzword 'Cloud Computing'. There has been a big surge in cloud computing Technologies. Salesforce is one of the front runners among those. In this blog, I will introduce you to Salesforce and will answer:
  • What is Salesforce?
  • Why use Salesforce?
  • Who should use the Salesforce CRM?
  • How it makes your life easy in terms of technology and marketing?

Q: What is Salesforce?

A: Before knowing about Salesforce, lets discuss why it was needed and how it evolved. Prior to Salesforce, Customer Relationship Management(CRM) solutions were hosted on local servers which were established by company itself. It usually took months even years to build the setup which was very costly. Also the results were not that fruitful.
As you all know necessity is the mother of invention, here comes a feasible and affordable CRM solution in the name of Salesforce which is offered as Software as a Service(SaaS), delivered entirely online.

Salesforce is a customer relationship management(CRM) solution that brings companies and customers together. It's one integrated CRM platform that gives all your departments — including marketing, sales, commerce, and service — a single, shared view of every customer.


Q: Why use Salesforce?

A: There are hell lot of reasons you can go for Salesforce, few are jotted below:
  • Ease of Use: This is one of the primary reasons that drive the Salesforce adoption rate. Sales Reps have better visibility into their accounts, contacts, opportunities, tasks, all from a single place. They have a complete 360-degree view of the customer, which in turn helps them to make better business decisions and close deals faster.
  • Customizability: There is always a need to provide more features than out-of-box offers. Salesforce platform provides you Apex, Visualforce  and lightning apparatus to achieve those goals.
  • Scalability: Business is done keeping future perspective open. With Salesforce you can scale up whenever needed in future.
  • Reporting: Reports are the mirror of your business. Sales Reps can create their own reports to see the Accounts they haven’t worked on for a while, Opportunities present in the pipeline, products they have sold, activities performed and tasks completed.
  • Time and cost of Implementation: Being a Cloud Platform, the implementation time for Salesforce is much lesser than standard solutions, thereby lessening the Go-Live time-frame. The feature-rich solution can be configured easily and even if any customization is required, it can be incorporated in a systematic order easily. And cost incurred in this path is also reasonably less in comparison to others.


Q. Who should use the Salesforce CRM?

A. The simple answer is everyone. Salesforce has editions for all variety of users. It offers different editions like Group, Professional, Enterprise and Performance (For Sales Cloud). An organization can select the edition they, according their aims, and the features they require.

Salesforce covers all the areas of customer relationships, ranging from marketing to service. Any organization that wants to manage their customer relationships holistically can come in and use Salesforce without losing time, and wasting money for software development or hardware infrastructure.

Q. How it makes your life easy in terms of technology and marketing?

A. Keeping customer relationship healthy and keep getting business from them is the top priority for a sales representative. Salesforce makes sales reps life easy in this path.

  •  Infrastructure perspective:

    • Don't have to worry about setting up of servers and its installation. You just have to purchase the licenses. Its like plug-n-play.
    • All the patches and latest features are readily available to you when they are released by Salesforce.
    • Most business functionality is achieved via configuration on Salesforce platform.

  • Business perspective:

    • Visibility to leads makes sales reps connect to leads faster and get the business rapidly.
    • Dynamic Reports and dashboard provide you the latest status of the business, which make decision making faster.
    • Ease to Use – It's quite informative and very easy to use, which is also a big plus for sales reps.
Read More »