Monday, September 12, 2016

Overview of Salesforce database :
·         Salesforce works on Multi-tenant architecture, i.e many organizations (Tenants) are using same infrastructure.
·         Salesforce database doesn’t save data in traditional way. Data of all tenants are in common table.
·         It saves Metadata Information in hundreds of table.
·         Run-time engine, generates organization specific query to get information about their organizations and fetch data from common table.
·         Database tables are partitioned by Organization ID and generates virtual table specific to Org.
·         Due to Multi-tenant architecture ,traditional Query optimization query and technique will not work in this case.
·         To consider multitenant statistics, the platform has its own SOQL query optimizer that determines optimal SQL to satisfy a specific tenant's request.





Overview of Force.com query optimizer :
·         The Force.com query optimizer is an engine that sits between your SOQL and the database itself.
·         Because of salesforce.com’s multitenancy, the optimizer gathers its own statistics instead of relying on the underlying database statistics.
·         Using both these statistics and pre-queries, the optimizer generates the most optimized SQL to fetch your data.
·         It looks at each filter in your WHERE clause to determine which index, should drive your query.

How does Force.com query optimizer works:
·         Determines the best index from which to drive the query, if possible, based on filters in the query
·         Determines the best table to drive the query from if no good index is available
·         Determines how to order the remaining tables to minimize cost
·         Injects custom foreign key value tables as needed to create efficient join paths
·         Influences the execution plan for the remaining joins, including sharing joins, to minimize database input/output (I/O)
·         Updates statistics

Query Plan Tool :
·         There is no such tool available to optimize final generated SQL but Salesforce released Query Plan Tool to analyze how query is performing.
·         Query Plan tool in the Developer Console can help speed up SOQL queries done over large volumes.
·         Use the Query Plan tool to optimize and speed up queries done over large volumes.

How to enable the Query Plan Tool in the Developer Console?
Go to:
Developer Console>>Help > >Preferences and set "Enable Query Plan" to true


Why use this tool?
·         Use this tool to check the Query Plan for any SOQL queries that execute slowly or queries which are run on large volume data .
·         It will provide you with insight on the different plans
·         It provide the cost of SOQL using the index compared to a full table scan. If the cost for the table scan is lower than the index, and the query is timing out.
·         In such a scenario, you will need to perform further analysis on using other filters to improve selectivity

How To determine if a filter is selective?
1.       If the filter is on a standard field, it'll have an index if it is a primary key, a foreign key and an audit field
2.       Custom fields will have an index if they have been marked as Unique or External Id
3.       If the filter doesn't have an index, it won't be considered for optimization
4.       If the filter has an index, determine how many records it would return:
Ø  For a standard index, the threshold is 30 percent of the first million targeted records and 15 percent of all records after that first million.
i.e. the selectivity threshold for a standard index maxes out at 1  million total targeted records, which you could reach only if you had more than 5.6 million total records.

Ø  For a custom index, the selectivity threshold is 10 percent of the first million targeted records and 5 percent all records after that first million.
i.e. the selectivity threshold for a custom index maxes out at 333,333 targeted records, which you could reach only if you had more than 5.6 million records.

5.       If the filter exceeds the threshold, it won't be considered for optimization.
6.       If the filter doesn't exceed the threshold, this filter is selective, and the query optimizer will consider it for optimization.

View Query plan :
·         To use the Query Plan tool you simply enter a query in the Query Editor and press the "Query Plan" button which returns a Query Plan for the SOQL provided.



·         The Query Plan tool will show a list of available plans that our Query Optimizer can utilize for the query provided and will be arranged by cost ascending.





·         Each Plan will contain information on Cardinality, Operation Type, Cost, sObject Type etc.
·         The plan with the lowest cost is the plan that is used for driving the query execution.

Terminology used to display in query plan:
1.       Cardinality : The estimated number of records that the leading operation type would return.

2.        Fields : The indexed field(s) used by the query. If the leading operation type is Index, the fields value is Index. Otherwise, the fields value is null.

3.       LeadingOperationType : The primary operation type that Salesforce will use to optimize the query
a. Index - The query will use an index on the query object.
b. Other - The query will use optimizations internal to Salesforce.
c. Sharing - The query will use an index based on the sharing rules associated with the user who is executing the query. If there are sharing rules that limit which records that user can access, Salesforce can use those rules to optimize the query.
d. TableScan - The query will scan all records for the query object.

4.        Notes : An array of one or more feedback notes.

5.       RelativeCost : The cost of the query compared to the Force.com query optimizer’s selectivity threshold. Values above 1 mean that the query won’t be selective.

6.       sobjectCardinality : The approximate record count for the query object.

7.       sobjectType: The name of the query object.

How is the Cost determined?
·         Each plan has its own Cost value. The cost value is derived from the latest gathered database (DB) statistics on the table and values.
·         The plan with the lowest cost will be the plan used.
·         If the Cost is above 1, it means that the query won’t be selective.


Improve the performance of SOQL queries
When querying large objects special design considerations must be taken into consideration.
1. Make SOQL query selective
2. Improve performance with Custom indexes using Selective SOQL Queries

1. Make SOQL query selective:
·         The performance of a SOQL will depend on the presence of a selective filter
·         If a SOQL query contains at least 1 selective filter, the query is said to be selective.
·         If the SOQL query doesn't contain a selective filter, the query is said to be non-selective and will require a full table scan.
·         A filters can be simple or composite
o   Simple filters - single field expression in where clause or multiple expressions with 'AND' operator
o   composite filter - result of joining 2 or more field expressions via the "OR" operator is a .
·         A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold.
·         The performance of the SOQL query improves when two or more filters used in the WHERE clause meet the threshold related conditions.

2. Improve performance with Custom indexes using Selective SOQL Queries
·         Salesforce support can add Custom Indexes upon request for customers
·         When creating a case with Support, be sure to include the SOQL query which has the field to be indexed as a filter in the WHERE clause. Also be sure to include bind values if any.





Sunday, September 4, 2016

Salesforce: Points to consider while data migration




Step 1:-  Working on Source
  • Define the scope of migration i.e. which objects and fields needs be migrated. For ex. not all objects, field and records needs to be in target system. for ex. we may need data of only past 2 years 
  • Check the ER of source data and find master detail / parent child relationships 
  • For auditing purpose we should take full backup but it should be different from migration backup
  • Take the down time and sure no one can modify data while we are performing migration.
Step 2:- Working on staging DB
  • Perform all data clean up in staging DB
  • If any calculations/data massaging needs to be done, then that should also be done in staging. It will remove the load on target system when you load data in bulk.
  • Use VLOOKUP to maintain referential integrity
  • Security of data 
  • Duration of backup process - data may chnaged while running backup process. 
Step 3:- Test data load in Full Copy Sandbox
  • We should test data load in sandbox environment.  
  • Disable all unnecessary activities i.e. triggers, validation rules, workflow, assignment rules   
  • Make sure minimum to sharing calculations are happening
  • Decide which API suites you best i.e SOAP, Bulk with serial mode, Bulk with parallel mode
  • Arrange data in a way to reduce locking at target system
  • We will need to create external id fields in target system to preserve the relation ships.
  • Prepare check list / To do list based on challenges you face that you can use for actual data migration in production. 
Step 4:- Actual data load
  • We will get lot of learning while testing in sandbox. We need to apply all that in production follow the check list. 
  • Run reports and queries to check the statistic make sure they match 
  • Do some sample checks 
  • Enable triggers, validation rules, workflow, assignment rules
  • Update sharing model to meet your business needs and recalculate sharing 
  • After migration run both system in parallel. Don’t immediately discard source system. Keep a limited access to source system 

Thursday, June 2, 2016

How to find IP of salesforce org

Scenario:  Let’s assume that we need to integrate salesforce with other 3rd party applications. This application have tight security policy like salesforce.
Due to this you need to while list all IP from where the request can be made to 3rd party API.  

Solution: Salesforce publish a list IP owed by them and which will be used for calling any 3rd party API.
The complete list of IP is published at : https://help.salesforce.com/apex/HTViewSolution?id=000003652

Problem: When salesforce acquire new IP or increase the IP range some of the Integration fail. To debug this issue you have 2 ways.

1)Check the if there are any updates on the above link and cross verify the IP ranges with your network team
Or
2) find out IP of your new salesforce org.

How: There are simple steps you can follow to find the IP of your salesforce Org.

1)      Go to http://mockbin.org/ and click create bin
2)      On next screen also just click create bin without entering any details.
3)      Copy The URL from any of code snippet shown for ex. http://mockbin.org/bin/84995797-d5fe-472d-bbf2-0b7ccf95170c?foo=bar&foo=baz
4)      Login to org for which you want to find the IP
5)      Go to setup and quick search ‘Remote Site setting’
6)      Add http://mockbin.org in trusted site
7)      Run following code from your developer console
8)      Then go back to . http://mockbin.org/bin/84995797-d5fe-472d-bbf2-0b7ccf95170c and click view history
9)      It will show all the requests along with IP from where the request was made.

Http h = new Http();
HttpRequest req = new HttpRequest();

//Don’t forget to replace the URL copied in step 3
req.setEndpoint('http://mockbin.org/bin/cbc071cf-851d-4b1f-8abf-3b14859bcfb6?foo=bar&foo=baz'); 

req.setMethod('GET');
HttpResponse res = h.send(req);

system.debug('>>' + res.getBody() );

Tuesday, November 17, 2015

Two related list on one standard object - legitimate hack

We have account and contact look up relationship available in SFDC by default. On account standard page layout there is list of all contacts of that account are displayed .

One fine day client come up with requirement saying that he needs to separate contacts related list on account page layout. When contacts do not call field is checked it should appear in first related list otherwise it should appear in DND contact list(do not disturber).

We have multipal ways to achieve this:

1) Inline visual force page: We can develop VF page with standard controller and query all contacts and show them in separate lists.

Pros:
1) Meet the exact business requirement

Cons:
1) Not very flexible. If we want to change the criteria we will need to change the code.
2) Height of inline VF page is fix and if too many contacts are there then scroll-bar will appear on detail page


2) Add sorting: We can sort on do not call column and provide quick workaround.

Pros:
1) No coding required
2) very quick to implement

Cons:
1) Does not match exact requirement and its just workaround.


2) Two lookup hack: Third and best approach (in most of cases) is to add another lookup field on contact object which will refer account object. On this field add lookup filter. Do the same for standard account lookup filed.
After that last step is to update account page layout and add DND contact related list.

When you do that you will be able to show two contacts related list on account as bellow.




Pros:
1) No coding required
2) very quick to implement

Cons:
1) One extra lookup is required.

Wednesday, September 16, 2015

How to override Managed package functionality


SFDC documentation team have great job on describing what is Managed package, how to use it, what are limitation of it etc. The one area which is not very clear is how to override the functionality in Managed package. To some extend it also gives a perception to new developer that we cannot override functionality. This is not 100% true. If the package is designed to accept customization then it should allow developers to extend or override the functionality in Managed package.
Let’s see what are the ways to extend or override the functionally.  

1)      Override the Buttons & Links action: IF package developer creates a buttons and links using setup UI then those button and actions can be override by just selecting new action. For example you have new Clone button in your manage package and it is pointing to MyPKG__Clone page.  Then you can just edit it’s action and point it to MyClonePage (your own VF page).



Limitation: If bottom is created using VF tags then it can’t override using this method.

2)      Override the page layout: IF package developer creates a VF page using <Apex:Detial> tag then it uses standard page layouts as per profile. So you can use standard edit layout screen from Setup->Your object->page layout screen then click edit. This will allow developers to add new fields sections etc. to VF page.

3)      Use Global Components: You can use Global Components from managed package in your VF page and add new functionality around the Global Components.

4)      Use Global interfaces / Classes / Extension: You can use global interfaces / Classes / Extension and their global properties in any installed org. Global keyword make your code accessible from any apex code. Let’s take look as one of such example.

a.       Create controller extension class:
Global class myControllerExtension {
    private final Account acct;
   
    global myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }


    global String getGreeting() {
        return 'Hello ' + acct.name + ' (' + acct.id + ')' +' <br/> This text is from myControllerExtension';
    }
}
b.      Create VF page that use standard controller and extension we created above:
<apex:page standardController="Account" extensions="myControllerExtension">
    {!greeting} <p/>
    <apex:form >
        <apex:inputField value="{!account.name}"/> <p/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>
c.       Write test class
@isTest
Public class TestmyControllerExtension {
    public static testMethod void testMyControllerExtension() {
        Test.startTest();
        Account a = new Account();
        a.name  = 'Cybage';
        Insert a;
        PageReference pageRef = Page.GlobalTest;
        Test.setCurrentPage(pageRef);
        // Add parameters to page URL
        ApexPages.currentPage().getParameters().put('Id', a.Id);
        ApexPages.StandardController stdacc = new ApexPages.StandardController(a);
        myControllerExtension obj = new myControllerExtension(stdAcc);
        String msg = obj.getGreeting();
        System.assertEquals('Hello ' + a.name + ' (' + a.id + ')' +' <br/> This text is from myControllerExtension', msg );
        Test.stopTest();
    }
}
d.      Create manage package
e.      Log into other org and install the package created above
f.        Create your own VF page and use extension from package
<apex:page standardController="Account" extensions="AtulDev.myControllerExtension">
  {!greeting} <p/>
    <apex:form >
        <apex:inputField value="{!account.name}"/> <p/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>
g.       Create new extension to override the method from installed extension
h.       
Public class myControllerExtension_1 {
    private final Account acct;
    Public myControllerExtension_1(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }
    Public String getGreeting() {
        return 'Hello ' + acct.name + ' (' + acct.id + ')' +' <br/> This text is from override by New Extention';
    }
}
i.         Create VF page that used override extension:
<apex:page standardController="Account" extensions="myControllerExtension_1, AtulDev.myControllerExtension">
  {!greeting} <p/>
    <apex:form >
        <apex:inputField value="{!account.name}"/> <p/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>  


Conclusion: The general perception is that we cannot override anything that is written in mange package. This is not 100% true. 

Friday, September 11, 2015

Comparison between Workflow, Process Flow, Visual flow



Feature
Workflow
Process Flow
Visual Flow / Visual Workflow
Description
Workflow allow users to set up criteria and actions
Process Flow automates your business processes by providing a powerful and user-friendly graphical representation of your process as you build it.

Visual Workflow enables you to create flows, which are triggered by users rather than events

UI
Runs in Background and take the action for ex field update
Runs in Background take the action for ex. Post chatter feed
Allows user to interact from UI and take input from user.

Initiated By
Triggered by events. For ex. Record save
Triggered by events. For ex. Record save
Triggered by users rather than events.
For ex. Survey button click on lead object.

Supported Actions
·   Create a task
·   Create an email alert
·   Field Update New
·   Outbound Message
·   New Flow Trigger
·   Create a record
·   Update fields on any related record—not just the record or its parent.
·   Launch a flow—as an immediate or a scheduled action.
·   Send an email
·   Post to Chatter
·   Submit for approval
·   Call apex methods
·   The process builder doesn’t support outbound message

·   Lookup any object
·   Create Flow variables
·   Do CURD on any object


Scope
Limited to object in context and its master
Process Flow is not tied to any object

Visual Flow is not tied to any object

Interface
Point and click, multi-screen
Drag drop, Single Screen, easy to change & visualize
Drag drop, Single Screen, easy to change & visualize

Scheduling
Immediate and scheduled actions

Immediate and scheduled actions
Only Immediate actions
Use case
Send a web service callout to Inventory management system to update stock when  opportunity close successfully

Send a chatter feed to group of users when high value opportunity stage is changes  
Wizard for self-help portal if it does not resolve issue then log a case with all the details.