Tag Archives: Apex

Salesforce Schedulable Apex Test Class

Batch Class:

global class AccountBatch implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'SELECT Id, Name, Industry FROM Account';                
        return Database.getQueryLocator(query);     
    }
    
    global void execute(Database.BatchableContext BC, List<Account> accList){        
        for(Account acc : accList){          
            acc.Industry = 'Banking';        
        }        
        update accList;       
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
}

Schedulable Class:

global class AccountBatchScheduled implements Schedulable {
    
    global void execute(SchedulableContext sc) {
        AccountBatch objBatch = new AccountBatch(); 
        Database.executebatch(objBatch);
    }
}

Test Class:

@isTest
private class AccountBatchScheduledTest{
    
    static testmethod void schedulerTest(){
        
        String cronexpression = '0 0 0 15 3 ? *';

        Account acc = new Account();
        acc.Name = 'Test Account';
        Insert acc;
        
        Test.startTest();
        String jobId = System.schedule('ScheduleBatchApexClass',  cronexpression, new AccountBatchScheduled());
        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
        System.assertEquals(cronexpression, ct.CronExpression);
        System.assertEquals(0, ct.TimesTriggered);
        Test.stopTest();
    }
}

Salesforce Apex Design Patterns

  • Singleton: Minimizing object instantiation for improved performance and to mitigate impact of governor limits.
  • Strategy: Defining a family of algorithms, enscapsulating each one and making them interchangeable and selectable at runtime.
  • Decorator: Extending the functionality of an sObject in Apex.
  • Facade: Simplifying the execution of classes with complex interfaces (e.g. web service callouts).
  • Composite: Treating a group of objects in a similar manner to a single instance of that object.
  • Bulk State Transition: Efficiently tracking the change of a field value in a trigger and executing functionality based on this change.

Custom Label in Salesforce

Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language. Custom labels are custom text values that can be accessed from Apex classes, Visualforce pages, or Lightning components. The values can be translated into any language Salesforce supports.

We can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

Setup | App Setup | Custom Labels | Click ‘New Custom Label’ Button

Fill in the details and Click ‘Save’ button.

 

Custom Label in Visualforce page:
$Label.CustomLabel for Visualforce page.

<apex:page standardController="Account">
	
<h1>Example for Custom labels</h1>

	<apex:outputLabel value="{!$Label.Message}"/>
</apex:page>

 

Custom Label in Apex Class:
System.Label.Label_name for apex class

String msg = System.Label.Message; 

 

Custom Label in Lightning Component:
$Label.c.labelName for the default namespace.
$Label.namespace.labelName if your org has a namespace, or to access a label in a managed package.

<aura:component implements="flexipage:availableForAllPageTypes">
    
<div onclick="{!c.clickLabel}">
        <ui:outputText value="{!$Label.c.Message}" />
    </div>

</aura:component>

 

Custom Label in Javascript:
$A.get(“$Label.c.labelName”) for the default namespace.
$A.get(“$Label.namespace.labelName”) if your org has a namespace, or to access a label in a managed package.

({
    clickLabel : function(component, event, helper) {
        var label = $A.get("$Label.c.Message");
        alert(label);
    }
})

Login from Salesforce to Salesforce using Authentication Provider

We can login from many ways to Salesforce instance using Microsoft Access, GitHub, Janrain, Google, Facebook, Linked, Twitter and also from other Salesforce Org. In this article I’ll describe, how we can login from one Salesforce Org to another Salesforce Org using Authentication provider.

In this article I’m using two Salesforce Org one is “Org A” and another one is “Org B”. Here I’ll login from “Org B” with “Org A” credentials, and “Org B” will authenticate user and will act as source organization for login.

Step 1:
Enable my domain in your “Org B”. This step is important so that it will display all available Authentication provider for that Salesforce instance.

To enable my domain navigate to “Setup | Administration Setup | Domain Management | My Domain.
Enter a name for your domain after https:// and click Check Availability.
If the name is available, click the Terms and Conditions check box, then click Register Domain.

Step 2:
Here we need “Org A” User to be logged in from “Org B”. So, “Org B” should be able to identify that request is coming from “Org A”. Therefore Connected App needs to be created in “Org A”.

Create Connected App in “Org A”, Navigate to “Setup | Build | Create | Apps | Connected Apps” and click on New. Provide All information except “Callback URL”. We will comeback again on this step later to provide Callback URL.

“Callback URL” is the URL where “Authentication Provider instance” should return after providing access. Even if somehow “Consumer Key” and “Consumer Secret” is compromised, it will return to Callback URL which is your application.

Connected App also has “Consumer Key” and “Consumer Secret” which is equivalent to “username” and “password” for that App. Once you save this Connected app, it will provide “Consumer Key” and “Consumer Secret”, we need this information in next step.

Step 3:
Create Authorization Provider in “Org B”, Navigate to “Setup | Administer | Security Controls | Auth. Providers | Create New”.

Use the following settings:
Provider Type: Salesforce
Name: Salesforce Auth Provider
URL Suffix: Will auto populate as per the Name field
Consumer Key: Provide the “Org A” created connected App consumer key
Consumer Secret: Put the “Org A” created connected App consumer Secret key
Authorize Endpoint URL: https://OrgAinstance/services/oauth2/token
Token Endpoint URL: https://OrgAinstance/services/oauth2/authorize
Default Scopes: The value should be “refresh_token full”. “refresh_token” and “full” should be separated by space.
Registration Handler: Click on “Automatically create a registration handler template”, it will generate one apex class. We can modify that class as per our requirement, here the class name is “UserRegistrationHandler”.
Execute Registration As: Then Select User who should be used to execute this Apex class when user tries to login.
Icon URL: You can choose one sample icons

Here is the sample class “UserRegistrationHandler”.
This class is in “Org B”. When the “Org A” user will login with “Org A” credentials, then this class will execute. And will check, if the user is not exist then it will create a new user, otherwise it will update that user information.

Note: It is a sample class, you can modify it as per your business requirement.

/**
*   @Author         :   Biswajeet Samal
*   @Date           :   03/01/2017
*   @Description    :   This class includes the basics for an User Registration
**/

global class UserRegistrationHandler implements Auth.RegistrationHandler{

    global boolean canCreateUser(Auth.UserData data) {

        if(data != null && data.email != null && data.lastName != null && data.firstName != null){
            return true;
        }
        return false;
    }

    global User createUser(Id portalId, Auth.UserData data){

        //Check that User doesn't already exist
        if(!canCreateUser(data)) {
            if(data.email != null){
                User u = [Select Id, Username From User Where email =: data.email];
                return u;
            } 
            else {
                return null;
            }
        }
        
        //The user is authorized, so create their Salesforce User
        //Here I'm creating 'Chatter Free User' Profile User
        User u = new User();
        Profile p = [SELECT Id FROM profile WHERE name = 'Chatter Free User'];
        
        //Customize the Username as per your required format.
        //Also check that the Username doesn't already exist.
        //Possibly ensure there are enough org licenses to create a user. Must be 80 characters or less.
        u.username = 'Test' + data.username; 
        u.email = data.email;
        u.lastName = data.lastName;
        u.firstName = data.firstName;
        String alias = data.username;
        
        //Alias must be 8 characters or less
        if(alias.length() > 8) {
            alias = alias.substring(0, 8);
        }
        u.alias = alias;
        u.languagelocalekey = UserInfo.getLocale();
        u.localesidkey = UserInfo.getLocale();
        u.emailEncodingKey = 'UTF-8';
        u.timeZoneSidKey = 'America/Los_Angeles';
        u.profileId = p.Id;
        return u;
    }

    global void updateUser(Id userId, Id portalId, Auth.UserData data){
        User u = new User(id=userId);
        u.email = data.email;
        u.lastName = data.lastName;
        u.firstName = data.firstName;
        update(u);
    }
}

Step 4:
Set Callback URL in Connected App, Once you save “Auth. Provider” in “Org B”, it will provide you list of URL as shown in below image. Copy Callback URL from “Org B” and edit Connected App in “Org A” and set this URL.

Step 5:

Navigate to “Setup | Administer | Domain Management | My Domain | Authentication Configuration | Edit”.
This page will provide, list of all Authentication providers like LinkedIn, Facebook, Google, In our case Salesforce.

Now logout and navigate to Login page specific to your instance and you should be able to see all Authentication provider buttons for your instance. Pleas note that, Authentication provider button will not appear on “https://login.salesforce.com” page, it has to be Mydomain login URL.

This is sample of Login page, how it will look like.

Difference between Process Builder and Workflow in Salesforce

Process builder allows you to do the below actions:

  • Create a new record.
  • Update any related record.
  • Quick action to create a record, update a record, or log a call.
  • Launch a flow.
  • Send an email
  • Post to Chatter.
  • Submit for approval
  • Call apex methods
  • But the process builder doesn’t support outbound messages.

Workflows can only handle four types of actions:

  • Create Task.
  • Update Field.
  • Email Alert.
  • Outbound Message.