Saturday, July 1, 2017

Quick Tips: Salesforce environment strategy: Single Org vs Multiple Org

Much has been written and presented around Salesforce single organisation and multi-organisation strategies. But, still the question is asked quite frequently. There are really good articles and blogs and I'm hereby trying to compile the information and add my views to it, to provide a summary.

Single Org. Approach

In a single org. approach, an organisation maintains one single Salesforce org. all their required operations (planned to be executed via Salesforce) are executed via same org.

Ideal for: Small and Medium Businesses


  1. Less environment maintenance overhead
  2. Uniform processes - a very good opportunity for organisations which want to implement uniform processes/ functionalities across all units
  3. Easier user provisioning - once a user is setup, they have access to required functionalities


  1. Complicated processes as organisation grows larger and include various operations/ geographies
  2. Increased application conflicts - with same processes being used across different departments/ geographies, one change for a specific unit can impact other unit
  3. Performance issues - with same objects being used across different units, the data volume per object can substantially increase. This leads to special design consideration during design and development phase and also possibly performance degradation or limitations

Multi Org. Approach

Ideal for: Larger organisations with multi-country operations or multiple segregated business units

Note:- It's not that large organisations should not use single organisation, but it's viability varies based on application usage & complexity, data volume and performance expectations.


  1. Flexibility to have unit specific operations within specific environment
  2. Higher Performance - Only unit specific data to be persisted in their Salesforce environment. Leading to better performing functionality
  3. Tailored Solution - Provides ability for each instance to have it's own tailor made solutions, to fulfil desired functionalities with less overhead. In an organisation having multiple segregated business units of Line of businesses, it can help segregate required functionalities/ data based on intended audience.


  1. Reporting - reporting can be complex if data from all (or multiple) organisations is required
  2. Process disparity - without proper control on design and architecture, the applications/ functionalities within each environment can become more and more disparate, leading to operations challenges
  3. Complex user provisioning - a user may be required to be setup in multiple organisations based on needs
  4. Licensing - If a user is required to access more than one organisation, they'll need to have dedicated user account in each org (unless a specific mechanism is built to expose data to them in some way). This leads to additional licensing costs
  5. Complex application maintenance - with some common functionalities across all organisations, it can be complex to roll-out changes in these functionalities across all organisations

Wednesday, June 7, 2017

Lightning : Share common code across multiple components

With more and more complex components being built into lightning, it becomes quite important to understand how we can improve our codebase and ensure that we use best practices.

When it comes to building lightning components, they are expected to be pretty much self-contained. It works well when creating standalone components serving specific business function. But, often in enterprise arena we build components having some of common functionality. For e.g. need to validate email or address or a specific business rule validation.

A direct approach is to copy and paste the method within helper files of lightning component. But, it is definitely not an advisable approach. So, we have a problem to solve.

Lightning provides capability to load external javascript files (static resources) and use it's code. In this article i'll give a quick and simple glimpse of this capability

Step 1 - Create a javascript helper file

Create a javascript file to contain required shared code for e.g.

[CODE 1]

window.CommonHelper = (function(){
    var helper =  {
        roundCurrencyValue : function(value){
            return ( Math.round(value * 100) / 100);
    return helper;

Step 2 - Upload javascript helper file as static resource

Upload the file as a static resource, to be used in subsequent steps. For this post, let's name the static resource as CommonHelper.

Step 3 - Embed javascript helper file within lightning component

Embed this common reusable javascript within your lightning components by using ltng:require component.
[CODE 2]
<ltng:require scripts="{!$Resource.CommonHelper}"/>

Step 4 - Use helper file methods

That's it. Now you can use your code/ methods within your lightning component's javascript code. for example
[CODE 3]

Tuesday, March 14, 2017

Sneak Peek: What is Visualforce Viewstate? and how to keep it lean

Note: The main content for this blog post was shared by my friend and colleague Shriram Kabra.

There are loads of blogs and articles around managing viewstate in Visualforce pages. As you would know, viewstate is primarily a serialized form of controller state between postbacks. It is very helpful to retain controller's state between client's browser and server.

How viewstate works?

Every time user opens a visualforce page, Salesforce executes related controller(s). As per controller logic, data is retrieved/ created within memory. This data can also be considered as controller state. If you monitor the lifecycle of Salesforce object (object of controller), it ends as soon as it responds to browser and loses its state. Technically, all subsequent requests for it are fresh page loads. In order for visualforce to retain this state between all postbacks, it needs to store this state somewhere. This is where Viewstate comes handy. While rendering visualforce page, engine serializes controller state to string and sends it within page's html content as viewstate (can view it when viewing source of a rendered visualforce page).

In all subsequent postbacks (for e.g. if user clicks on a button which invokes controller method), page sends viewstate back to Salesforce, which is deserialized to recreate state of controller since last postback. This helps in overall processing.

Issues while using Viewstate
Viewstate is quite helpful, as it auto-magically maintains state of controller and avoid developer to write more code to achieve it. But, it comes with its own cost.

Firstly, viewstate adds to the overall data to be downloaded, hence increases data to be downloaded to browser. Heavy viewstate leads to latency in page load or any subsequent user operations.

Secondly, Salesforce restricts viewstate size to a maximum of 135KB. Any page having viewstate greater than that will show a Salesforce thrown error "Maximum view state size limit (135KB) exceeded".

Standard solutions to reduce Viewstate footprint
There are some widely known solutions to manage viewstate, as mentioned below
  1. Avoid using Forms: Well, it's simply killing the chicken, so there are no eggs. With no forms in visualforce page (and components), there is no state to be maintained. So try to reduce it as much as possible. For example, if the page just displays information, there is no need for input fields (and thus a form)
  2. Minimize controller level properties: retain only important data within controller and avoid creating controller properties as much as possible. Use method level variables, which will be automatically disposed when request cycles ends, hence, will not be included within controller viewstate
  3. Use transient properties: controller level properties which are not required to be retained within postbacks, can be marked as transient. By using transient keyword, Salesforce skips those properties for viewstate generation
  4. Use Javascript Remoting: javascript remoting methods are stateless and as a result no data is saved within viewstate
  5. Minimize data: reduce data volume to be retained at controller level. For e.g. if there are some records which are to be fetched only for display purposes, fetch them every time they are required, instead of retaining their data within controller
  6. Avoid components using controller: if a visualforce component uses it's own controller, it's viewstate is also tied up with the viewstate of main page, further increasing the load. So, it is advisable to watch for components using their own controller

Internal Viewstate - The hidden viewstate

Now, as we have covered basics around viewstate, it's considerations and known solutions, we come to problem extension. Even after employing aforementioned techniques, we can often see that page's viewstate is still not very small, even if you have very few controller properties.

What is Internal viewstate?
While using Visualforce controllers and UI tags, Salesforce maintains internal data. This data is stored within Internal viewstate is not available for developers to view/ manipulate. It can increase in size depending on various factors such as:

  1. Controllers/ forms being used in page (including controllers of components being used)
  2. Visualforce tags being used
  3. Any apex repeat tags being used 

Solutions to reduce Internal ViewState:
  1. Use lesser Visualforce components and use more standard HTML components
  2. Use Javascript Remoting to manage data being sent back and forth for each operation
Reference links:

Tuesday, January 24, 2017

Sneak Peek: Visualforce with Javascript Promises

Visualforce with Javascript Promises

While working with Visualforce pages along with javascript remoting functionalities, we often create a lot of callback methods. On top of it, multiple invocations in a chained approach is more chaotic, often hardcoded and leaves code quite unreadable. 

Following is an example code while using Javascript remoting within Visualforce page:- 

function invoke_remoteService1(){
    console.log(' Invoking remote service 1');

function remoteService1_ResponseHandler(response, event){
    console.log(' Response from remote service 1 = ' + response);
    if(response != null){
        console.log(' Invoking remote service 2');

function remoteService2_ResponseHandler (response, event){
    console.log(' Response from remote service 2 = ' + response);

Similarly, callback methods keep on adding, making code readability and modularity an ever increasing challenge. As you can imagine, if we now want to add another button which calls same services in reverse order, we'll have to either write similar code twice or perform major code refactoring.

The solution is Javascript Promises.

What are Promises?

In simple words, a Promise promises to help chain (or bind) multiple asynchronous method invocations in same way as we chain synchronous method invocationsNO, it does not make your asynchronous calls as synchronous, it just helps you to structure your code in efficient way. Promises are a code design construct which help in structuring code in a better way, when dealing with asynchronous methods.

So, for example, we have synchronous methods (everything handled locally)

function validateCustomer(){ 
    //validation code

function insertCustomer(){
    //insert customer 

function createCustomer(){ 

    if(validateCustomer() == false){ 
        //insert customer
        var customer = insertCustomer(); 
        if(customer != null){ 
            console.log('customer inserted successfully'); 

Previous code is very readable and modular, as we can bind it in different order if we wish to, without impacting existing functionality. It'll be great if we can bind our asynchronous methods in the same way. This is where Promises help.

Promises are extremely helpful while creating single page applications. As we rely more on javascript remoting calls, leading to more callback methods. This need is universal and not limited to Salesforce or visualforce, hence Promises have been added to ECMA6 (refer documentation at 

Note:- As of this time, IE doesn't support Promises in any version (refer documentation link shared previously)

Important points about Promises
  1. Once Promise concludes in success or failure, it'll remain in that state forever
  2. Outcome (or result) of promise can be used multiple times

How to implement promises?

Javascript Promises are now natively supported within all major browsers (except IE) means easier implementation with no external library to be loaded.

Promises can be implemented in two steps:- 
  1. Create promises – preferably create a promise each for each asynchronous method 
  2. Chain promises – now chain various promises together based on business requirement 

So, we can refactor our first code block as:

var testService1_Promise = new Promise( function (resolve, reject){
    console.log('Invoking remote web service 1');
    Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.testWebServiceController.remoteService1}', function(response, event){
        if(event.statusCode == '200'){

var testService2_Promise = new Promise( function (resolve, reject){
    console.log('Invoking remote web service 2');
    Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.testWebServiceController.remoteService2}', function(response, event){
        if(event.statusCode == '200'){

function getRemoteAccount() {
    //bind first service response with second web service
        function (response){
            //handle response from remote web service 1
            console.log('response received = ' + response);
            //return promise for remote web service 2
            return testService2_Promise;
        function (err){  
            console.log('---- error occurred = ' + err);
        function (response){
            //handle response from remote web service 2
            console.log('response received = ' + response);
        function (err){  
            console.log('---- error occurred = ' + err);
    ).catch( function(err){
        console.log('----error occurred = ' + err);

Note:- we have added catch block at the end. Promises allow us to define a catch handler to handle any unhandled exceptions.

Stateful Promises 
Previous code works, but has some issues, because:- 
  1. As you will notice, promises created above are objects. You will also notice that the asynchronous method (remote method invocation) is called while creating the object itself and at all subsequent usage, the promise will continue to pass same values 
  2. Promises are immutable. That is, each time you create a promise, it persists it's state as is 
  3. Off course, the code above is not very reusable and each time you have to do similar activities (probably in different order) you'll have to create those promises again 

So, a better way is to separate these steps 
  1. Create separate function for creating promises 
  2. Create separate function to bind promises. Create promises dynamically within these functions 

For e.g. previous code can be refactored as:- 

function getRemoteService1Promise(){
    return new Promise( function (resolve, reject){
        Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.testWebServiceController.remoteService1}', function(response, event){
function getRemoteService2Promise (){
    return new Promise( function (resolve, reject){
        Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.testWebServiceController.remoteService2}', function(response, event){
function getRemoteAccount() {
    var RemoteService1Promise = getRemoteService1Promise();    
        function (response){
            console.log('response received = ' + response);
            return getRemoteService2Promise();
        function (err){  
            console.log('---- error details 1 = ' + err);
        function (response){
            console.log('response received = ' + response);
        function (err){  
            console.log('---- error details 2 = ' + err);
    ).catch( function(err){
        console.log('---- exception details 3 = ' + err);

Parallel vs Serial method invocation

Do notice, in previous code, instance of second promise is created when successful response is received for first asynchronous call. This means that second asynchronous method is invoked only when first one succeeds. In other words, it performs a serial-mode chaining of asynchronous events.

However, if both the asynchronous methods are exclusive and can be invoked in parallel, we can modify our code to create promises for both asynchronous methods together. This way we can achieve parallel method invocation for asynchronous methods.

Benefits of using Promises

  1. First and foremost, the code is reusable and separates asynchronous method invocation and their sequence / post-processing. So, you can choose to bind it in any way needed by business requirements
  2. Code is very readable
  3. Better exception handling


Monday, January 2, 2017

Quick Tips: All about sending emails from Salesforce (with advanced features)

Emails are still a very essential part of our day to day communication. Be it an internal communication within the organization, or across organizations or between customers and organization, emails are one of the key communication mechanism (let's not debate on pros and cons here). Quite obviously, Salesforce provides various options to send emails to internal and external recipients. In this post I'm trying to cover all the essential points (briefly) involved in sending emails from Salesforce.

Defining Email Templates

First and most important aspect regarding emails is ability to create email templates within Salesforce. This is without doubt one of the most used aspect related to sending emails. Email templates help administrator create pre-defined email templates within Salesforce. This helps in providing business approved and verified templates to system and users. As a result, all outgoing communications are consistent. Also, any correction/ improvement incorporated is automatically available to all it's users. Furthermore, email templates have ability to embed merge fields (values which can be substituted by attributes of given record), for example, automatically populating customer's name and order number on outgoing email.

Salesforce allows creation of three types of email templates:-
  1. Text:- most basic of the options. As name states, it just contains plain text email content. 
  2. Custom (without letterhead):- allows administrators to create email templates using HTML to define beautiful and elegant email templates
  3. HTML (with letterhead):- this is similar to previous option. Administrators can define a letterhead (letterhead defines common email header and footer contents) and compose email template using rich text editor
  4. Visualforce:- most advanced version of email templates. This is created by developers using Visualforce to address most complex email template requirements (for example, generating different UI based on data attributes). It provides developers full control over the email template UI. It also enables developers to dynamically generate attachments (PDF, CSV etc.) along with the email. For e.g. if you want to automatically generate Invoice PDF and send to customer, Visualforce email templates can be really handy
More details email templates will be covered in separate post.

How to Send Emails?

Thankfully, Salesforce provides many ways to send emails from Salesforce and yes, one of them is via code. Interestingly, there are so many configuration based options for sending email that code is really required for specific requirements.

Send Email Manually

Most certainly, the first option is to be able to use an email template; if required, make modification; and then send the email. Emails can be sent from pretty much any standard/ custom object for which "Activities" is enabled.
Usage Scenario: Need to send ad-hoc email to customers

Send Email via Workflow/ Lightning Process builder 

Workflows and Lightning process builder processes are the swiss army knife of automation within Salesforce platform. Certainly, these can be setup to send emails using email templates.
Usage Scenario: Send an email to customer on their birthday or marriage anniversary; workflows/ process builders can be setup to automatically send emails for this scenario.

For more details on Email actions refer Email Alert actions.

Send Email via Flow

Flows provide developers capability to automate processes by create custom user interface along with custom business rules without code. It's definitely a very helpful approach as it helps in creation and maintenance of custom UI. As a possible flow action, developers can send email from a Flow.

For more details on sending emails from Flow read Flow Send Email element.

Send Email via Approval Process

Similar to previous option, Approval processes within Salesforce allows users to send email notification on different approval steps.
Usage Scenario: Send email to each approver upon assignment for approval or want to notify submitting user about acceptance/ rejection of the approval request.

Send Email via Case Escalation Rule

Case escalation rules help organizations escalate cases exceeding Service Level Agreement (SLA). Upon escalation, administrators can configure escalation rules to notify specific users.
Usage Scenario: Notify Customer Service Director upon escalation while assigning escalated case to supervisor.

Send Email for Report/ Dashboard

Sales and customer service managers mostly want to look at weekly/ monthly dashboards for their business needs. Often the expectation is to get the details automatically, without having to login into Salesforce. This can be achieved by scheduling reports/ dashboards (refresh dashboard and email) to be sent via emails.
Usage Scenario: Send Sales pipeline stats to Leadership on weekly basis

Send Email via Apex Code

Last and mighty, Salesforce allows developers to programmatically send emails to customers/ users or any external email ids as well. Being a programmatic approach, this provides maximum control to developers. Developers can control the recipients, email content, attachment etc.
Usage Scenario: Create a custom screen to pull data based on custom filters and email data to customers

There are more feature specific email settings, wherein Salesforce sends email to designated recipients (mostly internal) for example, assignment rules, contract expiration notifications, chatter etc.

Advanced features

Send Email using common mailbox a.k.a. Organization wide addresses

As a general customer service practice, organizations prefer to use common mailboxes to communicate with clients, for example, or To achieve this, Salesforce allows creation of Organization wide email addresses, which can be used to send emails from Salesforce using common organization mailboxes.

For more details on creating Organization wide email addresses read Organization-Wide Addresses: Let Users Send Email from Salesforce Using a Common From Address

Send default content within footer of outgoing emails (Organization-Wide Email Footer)

Many organizations prefer to include some legal/ copyright content within all emails going out of organization (using official mailboxes). Generally, this is setup within email servers. However, when sending emails via Salesforce, email server settings do not apply.

In order to get the same features, Salesforce provides feature known as Email Footer (more than one can be created). This allows administrators to specify the common legal content within email footers and use them for outgoing emails. More than one organization wide email footer can be created.

Send email using external mail server (Email Relaying)

In this world full of spam emails, lot of organizations block incoming emails from unknown sources (including Salesforce). There can be situations where customers complain that they are not receiving emails (being sent from Salesforce). This is generally due to the fact that emails are being blocked by their mail server. Customer's mail server may have been setup to accept emails from your organization, but might be blocking emails from Salesforce. In such scenario, the solution is to setup Salesforce to send emails from your mail server, also known as, Email Relaying.
Email Relaying allows Salesforce to route all outgoing emails via your email server. This helps ensure:
  1. higher email deliverability and reduce email bounces
  2. keep backup copy of outgoing emails for legal/ compliance reasons
  3. incorporate additional content check
  4. run third-party email softwares (content filtering/ anti-virus) on outgoing emails

[Lightning Experience Only] With Summer '16, you can also setup your Salesforce org. to allow users to use external email providers (currently Gmail and MS Office 365 are supported). So, once enabled, users can provision Salesforce by logging in with their third party account (Gmail or MS Office 365) to be able to send emails from their external account.

Sign Outgoing emails with certificates (DMARC compliance)

With ever rising security issues on internet, it is becoming more and more difficult to rely on emails. For matters concerning privacy and confidential information, emails have become a very risky tool. It is equally problematic for email senders as they are equally unaware whether the emails sent by them are being trusted.

Thankfully, there are some standards to secure outgoing emails and ensure that recipients can validate the authenticity of emails. A few notable standards are:
Salesforce allows administrators to setup DKIM keys for outgoing emails. This process also allows outgoing emails to be DKIM and DMARC compliant.

To know more about setting DKIM keys read Create a DKIM key

Important points to remember

  1. Email limits restrict sending emails to 5,000 external email addresses (does not include lead/ contact/ person accounts/ users and emails sent manually) per day (refer Email limits)
  2. Daily limit for emails sent through email alerts is 1,000 per standard Salesforce license per org (except free Developer Edition and trial orgs)
  3. Overall org daily limit for sending emails is 2,000,000. This limit applies to emails sent through email alerts in workflow rules, approval processes, flows, processes, or the REST API.
  4. Unlimited emails can be sent to internal users
  5. Maximum number of recipients is limited to 
    1. TO - 100
    2. CC - 25
    3. BCC - 25

Thursday, December 22, 2016

Quick Tips: Some things about Salesforce Validation rules you may not know

What are validation rules?

While creating any application, one of the most crucial building block is clean and good data. We do get ability to define required fields on field and page layout level, but there can be complex scenarios where the business rule needs multiple fields to ascertain data quality. 

Salesforce provides a very helpful feature called "Validation rule" to ensure administrators/ developers can create custom validation rules on Salesforce objects. These validation rules help ensure that any record being created or updated qualifies to defined business rules. If not, then developers/ administrators can display required error message.

Validation rule constitutes of:-
  • Formula - formula to evaluate business rule. If formula evaluates to TRUE, validation error is thrown, else it's considered as validation success
  • Error message - error message to be displayed on validation failure
  • Location - Enables admin/ developer to define location to display validation error. In standard page layouts, it'll allow user to show error either at page top or beneath the selected field

Validation rules are invoked anytime a record is created/ updated via any process I.e. manually from UI, API etc.

When to use validation rules?

Validation rules are most useful to implement required business rules without using any code. All validation rules are configurable and can be modified/ disabled by admin/ developers whenever needed.

There can be many scenarios where business rules are to be defined, so that user gets appropriate data validation error messages. For example

  • A user cannot create a contact without email address where the contact's preferred contact method is Email
  • A user cannot assign case back to Queue

To know more about how to create validation rules refer help article 
Define Validation Rules
Examples of Validation Rules

When validation rules may not be applicable?

However, there can be scenarios wherein the business rule needs multiple records or child records to assess data validation. In such scenario, Apex triggers will be best avenue to implement business rules.

Scenarios where Validation rules are skipped

  1. If validation rules exist for activities and you create an activity during lead conversion, the lead converts but a task isn’t created
  2. Campaign hierarchies ignore validation rules
  3. If records are mass assigned via Mass Transfer tool, Change owner and Accept buttons
  4. During lead conversion validation rules are skipped if validation and triggers for lead conversion are not enabled
  5. When changing ownership on Accounts, Opportunity Validation Rules are also ignored when selecting to transfer Closed Opportunities and Opportunities not owned by the existing Account Owner
  6. If workflow rules and process scheduled actions modify the record, validation rules are skipped


  1. Because updates to records based on workflow rules and also on process scheduled actions don’t trigger validation rules, workflow rules and some processes can invalidate previously valid fields
  2. Salesforce runs validation rules before creating a record via web to lead or web to case, if the any rule fails, the record is not created
  3. Validation rules apply to all fields of the record, irrespective of any page layout; that is, 

For more details refer:-

Popular Posts