Sunday 15 December 2013

How to start using force.com CLI


Here is a small instruction to start using force.com CLI for windows. Download force.com CLI executable from https://force-cli.heroku.com/.


After downloaded the executable file. Open the force.exe program from the command line.
Lets say if you have downloaded into D drive, open the force.exe from command prompt.


Open command prompt


  • type cmd in run
  • type cd d:\
  • then enter force.exe


Now you have loaded force.com CLI in command prompt.It displays all the available commands in the command line.


Login to salesforce to start using it on your salesforce instance.


Type force login


It will open login.salesforce.com in the browser. If you want to connect to our sandbox instance, then after opening the browser window replace the login.salesforce.com to test.salesforce.com. Do not remove/change the remaining strings in the url.


Once you have logged in successfully you can start using other commands from the command line.


The command i found very exciting is the export command. It will export all your metadata from your salesforce instance just by one line of code.


force export


Hope you may enjoy using force.com CLI..!!

Monday 25 November 2013

Caution while rendering html link on Visualforce PDF’s


As we all knows that rendering engine doesn’t support javascript generated elements. The following logic also will fail to redirect the user.


<apex:image url="{!$Resource.PDFImage}" onclick="window.open('www.google.com');" width="550" height="50"/>



The better approach here is the following line of code which works perfectly in this scenario.


<apex:page renderAs="pdf" >
<apex:form >
<apex:outputLink value="https://learnsfdc.blogspot.com">Click Here</apex:outputLink>
</apex:form>
</apex:page>
**Caution: Use https instead of http while referencing the link

Also as a best practice use images from static resources while rendering pdf

Monday 18 November 2013

Create test data with createddate less than SystemToday in apex test class


Have you ever been come up with a case where you have to create test data with created date less than today. Is that possible??

In winter’13 salesforce introduced a static method on test class, loadData() method which can load the data from static resource. This method takes two parameters

1.Sobject token – to identify to which object the static data should be mapped.
2.Static resource name- From which salesforce load data, it can be a csv file with field names are file headers and respective cells having values.

Lets say I have a following piece of code which I need to cover from a test class.
public class TestLoad
{

public void TestAccounts()
{
    List<Account> a  = [select name from account where createdDate <:system.today()];
    if(a.size()>0)
    {
        for(Account ac: a)
        {
            //Process some logic
        }
    }
}
}

I can use the following code to cover the complete line of code.

@isTest
private class TestLoad_TC
{

    static testMethod Void TestLoad_TC()
    {
        Test.startTest();
        List<sObject> ls = Test.loadData(Account.sObjectType,'testAccounts');
        TestLoad insta1 = new TestLoad();
        insta1.TestLoad2();
        Test.stopTest();
    }
}

Here Test.loadData(Account.sObjectType,'testAccounts'), which loads the data from static resource.

The csv file headers should maintain the object field api name for the method to map the data from file to object.

Sunday 13 October 2013

How to manage discrete objects DML operation wisely



This may be useful for someone who is trying to make an efficient code on force.com platform. We all know that there is a limit on DML operation on force.com in a transaction, just 150. We may want to write much DML operation on different objects. Let’s say if you have accounts, contacts and you want to update /insert these objects in the same context, how we can save DML operations if the number of records in combined list cannot cross 10,000. There is a solution with generic Sobjects in sales force. 

So we have list of accounts, contacts.

List Account_list =   new List();
List Contact_list = new List();
/*
Some logic to populate account, contact data and finally you want to perform DML operation on account and contact.
Let’s say an update.
*/
List Update_list = new List();
Update_list.add(Account_list);
Update_list.add(Contact_list);
Update Update_list; /* This will save one DML operation*/

Hope this can help someone who is close to DML limit.

Sunday 1 September 2013

Why we can’t write test class inside an apex class.


Starting from summer’13 sales force announced that the test class should be written outside of an apex class. You cannot save apex code with version 28.0 or later if you have written test method inside an apex class.


The reason behind the scene is:

While executing an apex class/ trigger sales force load the apex code into cache (a high speed memory) to make better performance. If you have written test class inside an apex class those test methods are also loaded into the cache memory and they stay in the cache till execution completes. There is no need to load these test code while executing apex class for any business logic.

The sales force.com is a shared environment and if every apex class loads some test code into the cache memory there will be a lot of space underutilized in the system, thus causing others to wait. So sales force now won’t allow developers to write test class inside an apex class for apex code saved using API version 28 or later. But the existing code can be saved with earlier API version.

Wednesday 21 August 2013

Predictive search on a field in standard page with home page components


I had a requirement to add a predictive search (auto complete) on a field in standard page. The exact requirement was like whenever the user types some characters on a field then automatically a suggestion drop down should come and that should list all the values currently in the system for that field.

The requirement can be easily fulfilled by home page component, little java script and jQuery.

I am not going to discuss how can we add home page component to a standard page, all the documentation is available from sales force.

I have used the following code in my home page component

<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>
<script>
var url = document.URL;
if(url.indexOf('006')!=-1)    
{        
        var sid = document.cookie.match(' sid=([^;]*)')[1];        
        sforce.debug.trace=true;        
        sforce.connection.sessionId = sid;        
        var stages = sforce.apex.execute("opportunitySearch", "getFieldValues", {});        
        var staheArray = stages.toString().split("+");        
        $ = jQuery.noConflict();       
        $(function()             
        {                
            var availableTags = staheArray;               
            $( "#00N90000006ikQJ" ).autocomplete({source: availableTags});           
        }        );    
}
</script>

I have created the below apex class for the above code to work.
global class opportunitySearch{ 
   webService static String getFieldValues()
   {
       String pickValues='';
       for( Schema.PicklistEntry f : Opportunity.StageName.getDescribe().getPicklistValues())
       {
           pickValues = pickValues +f.getValue()+'+';
       }         
       return pickValues ;
   }
}



EXPLANATION

Since sales force allows us to execute java script code from home page component we can use JavaScript or jQuery to implement some functionality in a standard page through home page component. Here I need to fetch the data from back end and populated it on the page I should be able to execute some query/apex code to do that. In the above example I fetch all the opportunity stage values from a pick list and populated on another field on the standard page.

To execute the apex class from java script I cannot use the java scrip remoting since it is not supported in the home page component. So I used sales force ajax toolkit to establish the connection between home page component and apex class.


The below lines of code is required for the Ajax tool kit to work.


<script src="/soap/ajax/15.0/connection.js" type="text/javascript"/>

<script src="/soap/ajax/15.0/apex.js" type="text/javascript"/>
 



Then I took the sales force session id from cookie through java script , the below line of code does that

document.cookie.match(' sid=([^;]*)')[1];


As we got the seesion id we need to set it on the sales force connection. Once we set the session id for sfoce we can execute the apex method from a class using the below piece of code

sforce.apex.execute(“Give apex class name here”,”Give apex methos here “,{“give apex method parameters here”});
The apex class should be declared as global and we need to have a webservice method also be there in the class for java script to execute. In the apex class I have got all the picklist values and I made it as a string separated with + sign. So the method returns all the picklist values separated with + symbol.
So in the java script I filter each status value with reference to the + symbol and I moved them into an array (stageArray).

From now I am using the jQuery to do the autocomplete job through autocomplete () function on a particular element by using the element id.