March 22, 2010

Fast save and refresh on Eclipse IDE developers spend lot of coding time waiting for file SAVE operation to finish. This is specially panic for developers working on huge projects having many classes, pages, objects and components.

I recently figured out a way to boost-up the save and refresh(from server) speed on Eclipse IDE. The secret to go faster is to checkout only selective metadata components in a single eclipse project. By default on creating a “New Project” in eclipse, “classes, triggers, pages, components, and static resources” are downloaded. I never need static resources locally in my eclipse workspace so why download them :-)

So the key is, if you know that you are only going to work with triggers then only checkout “triggers” while creating project. This will reduce the time significantly to refresh the project and even SAVE will be faster too. I am not 100% sure why SAVE is faster, but it really seems to be with in fraction of seconds.

I will explain the approach to go faster with IDE for two kind of developers:

  1. Developers who works on SFDC “point and click” customization via SFDC Web interface and uses IDE to write Triggers and Apex Classes only.
  2. Hardcore Developers” who touch almost every piece for example they write triggers and work on Apex/Visualforce also.

Trigger developers (“Point and Click Type”)

As said earlier, these developers just use IDE to write triggers and classes and do most of the customization via web interface. So we don’t need to checkout the default meta-data components i.e. “classes, triggers, pages, components, and static resources”. Instead we can limit to triggers and classes only. The way to do so is described using screen-shots below.

  1. Create a project as usual with required login details and project name etc. Hit “Next” button as usual when done.
  2. On the next screen instead of default selection “Apex and Visualforce(…)”, select second one i.e. “Selected metadata components” and hit “Choose” button next to it. image
  3. You will see a progress like this and let it complete. The IDE is preparing a list of metadata components.                          image
  4. In next view you will be presented a list of metadata components to select from. By default every thing comes unselected. Just select “classes” and “triggers” as shown below and hit “OK” button (red circles are indicating the selection):image
  5. That is all you need to do. You will get a new project with only two source components i.e. classes and triggers. The refresh and save should be relatively faster now as compared to the default project settings. Enjoy !!!!image

Hardcore developers !!!

I said Hardcore because you are the ones who are doing more than just point and click customizations on platform. You are the ones who create classes, visualforce pages/components and write complex triggers too. And work on big projects having lot of these components.

Though there is not a big difference is approach, the only key is to create a TRIGGER+CLASS project as above. Plus, you need to create a similar PAGES+COMPONENTS project for all the UI stuff. Creating the PAGES+COMPONENTS project is pretty similar to what we did above, we only need to pick “Pages” and “Components” instead of “classes” and “triggers” in Step 4, please check the screenshot below


So when done you should see two projects as shown below. I created project’s Named as <Customer>  <Components> for ex. “Dell Classes + Triggers

Still if your project is huge, you are having lots of classes, pages and components in projects and you are always work on selected ones. I suggest selecting those as shown below.

In above screenshot I just selected the 5 classes I only work upon, though my Dell’s project has 100s of other classes. Similarly I can download selective pages and components. So in this kind of IDE setup, you will for sure see significant boost in “refresh from server” and “save” speeds.

The only issue with this approach comes, if you need to search some code references in all classes/pages/components/triggers, as we have downloaded even super selected metadata now, we might miss some of the classes/pages/components/triggers etc. The solution to this problem can be to checkout all components in one single project and use it for such searching reasons :)

March 21, 2010

Fast Apex XML DOM updated with 3 new Node APIs

Today I was done with coding the 3 important missing API’s in Fast Apex XML DOM’s TODO list. The latest code is checked into Google Code SVN. Following are the newly added API’s to TG_XmlNode.cls

  • appendChild()     Adds a new child node to the end of the list of children of a node
  • cloneNode()      Clones a node 
  • getElementsByTagNameNS() Returns element for node’s local name and namespace

    Regarding TODO’s, moving forward my prime motive is to write quality docs to best use this API. Even I am planning to add docs for the Spring 10 Apex DOM classes, as the salesforce documentation is not having good samples and clear descriptions of the APIs.

    For more details on Fast Apex XML DOM’s TODO check this page. Its updated for these recent changes.

  • References:

    March 17, 2010

    Secure yui combo service (Over HTTPS)

    YUI Dependency Configurator is a great tool for getting a single unified JS or CSS instead of several css/js files. Only problem with that is it doesn't works over "HTTPS". Browser's like Internet Explorer fail to load a web page delivered over HTTPS containing JS/CSS delivered over un-secure(HTTP) URLs.

    The good news is that YUI team left a great possibility to change the combo base for service. “Combo base”  is basically YUI combo service base dir. Ex: “”.

    New Secure YUI Combo Service

    So I decided to use this possibility and I created a  Secure YUI Combo Service. This service is a secure wrapper over the existing YUI combo service i.e. for every combo service request it delegates the call to original YUI combo service and returns the response back.

    Following are some highlights of this service:

    1. It uses the high speed internet provided by Google, its hosted over “Google App Engine”.
    2. Its Open source on “New BSD License” and is hosted Google Code, here.
    3. Its support 3 HTTP METHODS i.e. GET OPTIONS HEAD. It also returns the same response headers as of Original YUI Combo Service. So browsers might make use of intelligent caching.
    4. The same service works with both YUI 2 & 3.

    Service Environment

    • Service Combo Endpoint :
    • Service Implementation : Its a J2EE Servlet.
    • Service Hosting : Hosted @ Google App Engine.
    • Service Dependencies: Apart from being a Servlet, its pure Core Java Code. So no dependencies on any jar or library, not even Apache Http Client.

    Developers - Getting Started Guide

    All the details regarding setup and testing this service over HTTPS are available in this here.

    Note for developers developers creating visualforce pages using YUI v2/3 face the same problem in Internet explorer i.e. servers deliver content over HTTPS and YUI combo service is not available yet on HTTPS. Rest all browsers are pretty nice with unsecure YUI Combo Service. So this service can be useful for all visualforce developers using YUI. Internet Explorer is a huge pain but we can’t avoid it :-)


    March 16, 2010

    Secure YUI Combo Usage Guide

    This post explains how to transit from unsecure (HTTP) based YUI combo service to Secured(HTTPS) based Combo Service. Making this transit to this secure YUI Combo service is pretty simple. This process requires you to just do 2-3 string replacements in your existing yui application, these replacements are:

    1. Load YUI minimal JavaScript? file via this secure service.
      <-- Change following script include -->
      <script src=""></script> 
      <-- replace it with this one -->
      <script src=""></script> 
    2. Change the configuration options for YUI Loader, to specify “comboBase” attribute pointing to this service.
      <script type="text/javascript"> 
      YUI({combine: true, timeout: 10000, comboBase : ''}).use("overlay", function(Y) {
      // ... your same post YUI modules load code
      // ... will go here
    3. Load any additional YUI CSS via this service.
      <link type="text/css" rel="stylesheet" href="" /> 

    Live Code Samples

    Some of YUI-3 live samples are copied and updated to use this secure service. Here are the links to these samples


    The secure YUI Combo Service URL ( is hosted over Google App Engine. It uses the free quota of app engine, so this is not production ready for you, its just for demo !

    So feel free to test if it works for you using this service, Google app engine has decent limits on free quota. So I am sure I can at least demo it from there :-)

    Production Usage: All the code for this service is available on this googlecode project. To use it in production environment, check out the code for this Java web-app and feel free to host it on your own app engine instance or existing java servers. The code is purely Core Java Implementation + Servlets. 

    In case of queries regarding hosting or deploying this code to your App Engine or Java Server instance please let me know.

    March 11, 2010 Spring 10 IDE not available till now ? IDE was supporting upto Eclipse Ganymede(3.4) only. Spring 10 announced enhancement to IDE with plug-in for Eclipse Galileo. That was an exciting news to me, because I have to use two eclipse versions right now, Ganymede for and Galileo for rest of Java stuff. Once this Galileo plug-in for is out, I can seamlessly move to single eclipse version.

    But I am surprised to see the delay in releasing this new IDE for general use. The website says it will be available by 15th Feb.

    Its 11 March today. Almost a month late, release team where are you stuck ??  Spring is about to end, summer has already started, please hurry up guys !

    March 9, 2010

    Apex Debugging with Custom Settings

    Developers add Apex debugging during development time to figure out complex issues. But that debugging code is usually commented or deleted from Apex Classes when preparing for release or production deployments. We usually remove it to save script statements and processing etc, but that is not really required, Apex is pretty fast on execution, its visualforce that takes time on most of the occasions.

    If we keep the debug statements as it is in Apex Code, we can ask customer to goto “Setup > Monitoring > Debug Logs” and create a log record for the user. That log file will be generated when you reproduce the issue next time and the same can be sent to developers to get a digg into the issue. The only issue with this approach is debug log limits and un-necessary debugging, sometimes developers end up in adding too many debug statements, so the logs are no more meaningful.  Though SFDC Spring-10 release came with nice “debug filters” to give you better control on what gets written into the logs. But still there are many pieces connected sometimes for ex. Apex Controllers, Triggers, Email Handlers etc.

    So for even more control over logging after Spring-10 debug filters, we can use Custom Settings. The idea is to create a Custom Setting to control “What to debug ?”.  We will start with Custom Setting’s details, followed by Apex Code that uses it.

    The Debug Custom Setting

    Lets say we create a custom setting named “DebugSettings” to control “What to debug”. This custom setting can be of type “LIST” or “HIERARCHY”, this truly depends on nature of project. Keeping LIST might open debugging for all users in ORG, but on the benefit is its handy to change, with HIERARCHY custom settings, one might need to create an Org Wide value or setup an user/profile based value to get the job done. 

    This custom setting can have following fields (All are of Type: CheckBox, Default-Value: FALSE), we have kept default value as false so that on packaging the code all debugging is set to false. So on a production issue you can ask customer to selectively turn on the debugging for required fields only.

    • AccountTrigger: If set to true, debugging will be done for AccountTrigger apex code.
    • MyHelloWorldController: Is set to true, debugging will be done for some visualforce controller named “MyHelloWorldController”.
    • StatusInboundEmailHandler: If set to true, debugging will be done for Inbound Email service handler code.
    • ….
    • …..
    • ….. Similarly one can create custom setting fields for controlling debugging in other apex class/code/triggers/email services etc.

    The Apex Code

    Using custom settings is pretty easy, but its quite possible to end up in Null Pointer Exceptions. So please refer this article(, to ensure you use custom settings in more safer manner. For quick reference here is the code you should try adding before accessing custom setting fields.

    if (DebugSettings__c.getInstance() == null) {
            // Assuming DebugSettings is a LIST type custom setting
            upsert new DebugSettings__c (SetupOwnerId = Userinfo.getOrganizationId());          

    Here is the sample code that shows how to do controlled debugging using custom settings.

    // Before insert account trigger
    trigger handleAccountChange on Account (before insert)
      // .....
      // Your trigger logic 
      // .....
      // Code inside Account Trigger
      if (DebugSettings__c.getInstance().AccountTrigger__c) {
        System.debug('Updating Accounts : ' +;
      // .....
      // Your trigger logic 
      // .....

    In similar fashion one can adding debugging code to Controller, by adding a check for visual force controller: MyHelloWorldController

    // Before insert account trigger
    public class MyHelloWorldController
      // .....
      // Your Controller logic 
      // .....
      // Code inside Account Trigger
      if (DebugSettings__c.getInstance().MyHelloWorldController__c) {
        System.debug('Processing Request for Parameters : ' + ApexPages.currentPage().getParameters());
      // .....
      // Your Controller logic 
      // .....

    So on issue in production just create a debug log for the user via “Setup > Monitoring > Debug Logs >  New” and create/update/manage the record for “DebugSettings” custom setting for user/profile/org with required trigger/controller field value as “CHECKED”. Once this is done just execute the flow with the issue and get back to “Setup > Monitoring > Debug Logs” to download the log file. That’s it :-)

    March 8, 2010

    Custom Settings Null Pointer Exception quick fix !

    Salesforce custom settings are nice in development env. But you get Null Pointer Exception in orgs where we deploy the same code, this is because Custom Settings need at least a single record to give a valid Sobject handle for CustomSetting__c.getInstance() call.  Here is the sample scenario that covers this issue and shows solution.

    Custom Setting

    Screen cast show a Custom setting named “MyCustomSetting__c” created.

    Custom Setting’s – Custom field

    A single custom field named “Config_Field_1__c” is defined for the custom setting above. Please note that its value is defaulted to ‘Hello World’.

    Code accessing Custom Setting

    Here is the sample code that tries to read the value of the custom setting defined above.

    System.debug('MY CUSTOM SETTING VALUE : '  + MyCustomSetting__c.getInstance().Config_Field_1__c);

    Upon execution it will throw Null Pointer exception if there is no value defined at organization, matching profile or user level. The fix to this issue is simple you can add this single line of code before accessing the custom setting value.

    if (MyCustomSetting__c.getInstance() == null) 
      upsert new MyCustomSetting__c (SetupOwnerId=UserInfo.getOrganizationId());

    If the custom setting type is “LIST” you need to change the above one liner a little. This is because for “LIST” type custom settings Name is a mandatory attribute. Here is the code snippet.

    if (MyCustomSetting__c.getInstance() == null) 
      upsert new MyCustomSetting__c (Name = ‘MyCustSettingName’, SetupOwnerId=UserInfo.getOrganizationId());

    This code just creates an organization wide value for your custom setting, if that doesn’t already exists. So now accessing this code prints “Hello World” on console.

    Important Notes

    • Success of the above approach depends on the way you configured your Custom Setting’s Field. Its highly recommended  you create custom setting’s fields with some intelligent default values.
    • Create a Singleton class called CustomSettingsHelper to encapsulate all custom setting’s access logic in one place. This will also give you a chance to put  this single liner code in single place, so that you don’t need to make call to this one liner before accessing any custom setting field. Here is a sample
      public class CustomSettingsHelper {
          The SINGLETON handle to the instance
          private static CustomSettingsHelper self;
          public static CustomSettingsHelper self() {
            if (self != null) return self;
            // To create org wide defaults in new org automatically. This
            // will prevent NPE's in future.
            if (MyCustomSetting__c.getInstance() == null) {
              upsert new MyCustomSetting__c (SetupOwnerId = Userinfo.getOrganizationId());          
            self = new CustomSettingsHelper();
            return self;
          // No body needs to construct it, a single reference will suffice. 
          private CustomSettingsHelper() {      
          // This method can be used to access the custom settings
          public String getConfigField1() {
              return MyCustomSetting__c.getInstance().Config_Field_1__c;
          // Client Code that shows how to access the custom setting
          public static testmethod void testCustomSetting() {
            System.assertEquals('Hello World', CustomSettingsHelper.self().getConfigField1());

    Apex Implementing Singleton design pattern

    Singleton is pretty popular and one of the most simple design patterns. On many occasions we want an Apex class to have a single instance only. Fortunately its pretty easy and possible with Apex. Though there can be different strategies to implement singleton in Apex (inspired from my Java days learning). Before that following are the prerequisite to make a class Singleton.

    • There can be a static public method  in class that returns the “Single” instance. Popular names to it are “self()” and “getInstance()” OR one can declare a public static property with only public get accessor  and private set accessor. We will show this in a while.
    • Constructor should have access modifier “private”. This is a must because, it will restrict other apex classes from creating the instance directly.

    As I said there can be many ways to implement Singleton,

    Simple Apex Singleton Strategy

    This strategy is for simple Apex Singleton strategy. I said its SIMPLE because in this implementation we are assuming there will be no DML inside the constructor or static block. Here is the implementation

    public class ApexSimpleSingleton {
        Note: this is the static handle to the single class reference.
        Its set accessor is made private to dis-allow any modifications to the reference 
      public static ApexSimpleSingleton self {get; private set;}
      static {
        // Static block used for transparent Singleton setup. the "self" static variable
        // will be ready as soon as class will be loaded in memory.
        self = new ApexSimpleSingleton();  
      // NOTE: the constructor is marked "PRIVATE"
      // so that no Apex code outside this class can create 
      // the instance
      private ApexSimpleSingleton() {
        // Do all the non DML initalization here
      // ..
      // ....
      // Rest of the code can be instance level methods that
      // provide access through the single handle
      public void sayHello() {
        System.debug('Hello World');
      // TEST METHOD
      public static testmethod void testSingleton() {
        //Will print "Hello World" on console.
    Advanced Apex Singleton Strategy

    The limitation of Simple Apex singleton strategy is its not meant to be used in case Singleton initialization requires some DML code to execute. For that scenario we need to setup the class little differently. Here is the sample

      public class ApexAdvancedSingleton {
      //Note: this is the static handle to the single class reference.
      //Its completely hidden to outside world. PRIVATE access modifier used   
      private static ApexAdvancedSingleton self;
      // NOTE: the constructor is marked PRIVATE
      // so that no Apex code outside this class can create the instance
      private ApexAdvancedSingleton() {
        // Do all the non DML initalization here
        This static method will be the only way to get the Single 
        instance of this class.
      public static ApexAdvancedSingleton getInstance() {
        // "self" is NOT NULL, that means we already did 
        // required initalization, so just return.
        if (self != null) return self;
          // Create the single instance now. 
          self = new ApexAdvancedSingleton();
          // All the DML Stuff to do the required one time setup. For example
          // you can use this code to create Org Wide custom settings 
          // if they don't exist.
          // ........................
          // ................................
          // ........................
          return self;
      // ..
      // ....
      // Rest of the code can be instance level methods that
      // provide access through the single handle
      public void sayHello() {
        System.debug('Hello World');
      // TEST METHOD
      public static testmethod void testSingleton() {
        //Will print "Hello World" on console.

    Lots of inline code comments to make this more readable and self understandable. Apex testmethods are added at end in each Singleton sample, this also shows how to use Singleton in client Apex Code.

    Still if you feel some gap or have some queries, please feel free .. :)

    March 2, 2010

    Fast Apex Xml Dom on “” CodeShare Now !

    Apex wrapper classes aka “Fast Apex XML Dom” has reached a point that I can share with all on Codeshare. Now Apex test classes have more than 95% code coverage(All Legal, no fake lines added :))). So today I polished the Apex classes with more docs and other unused stuff cleanup, also checked into Google Code SVN the final stuff. Now you can see the project on this code share link

    Still there are some small TODO’s. These are mainly a good HTML Apex Documentation and implementation of few more missing API’s in TG_XMLNode.cls. Here is the list.


    Fast Apex XML Dom Quick Started Guide !

    This post explains how to quickly start using the new wrapper Apex API. Developers coding previously on either Ron Hess’s XmlDOM or standard w3c xmldom will feel almost no difference and no learning curve in using this API. As that is the goal of giving this wrapper to be similar to what is existing for too long. This quick start guide provides a few samples only. We will be coming with HTML version of Apex Docs (similar to java docs) soon.

    Here is the snippet for quick start

    // Used example XML from
    String sampleXml = '<bookstore>'   
        + '<book xmlns:c="" category="CHILDREN">'
            + '<!-- Test Comment 1 -->'
    	+ '<c:title c:lang="en">Harry Potter</c:title>' 
    	+ '<c:author>J K. Rowling</c:author>' 
    	+ '<c:year>2005</c:year>'
    	+ '<!-- Test Comment 2 -->' 
    	+ '<c:price>29.99</c:price>' 
        + '</book>' 
        + '<book xmlns:x="" category="WEB">' 
    	+ '<x:title x:lang="en">Learning XML</x:title>' 
    	+ '<x:author>Erik T. Ray</x:author>' 
    	+ '<x:year>2003</x:year>' 
    	+ '<x:price>39.95</x:price>' 
        + '</book>' 
        + '</bookstore>';
    TG_XmlDom dom = new TG_XmlDom(sampleXml);
    TG_XmlNode root = dom.root;
    List<TG_XmlNode> books = root.getElementsByTagName('book');
    System.assertEquals(2, books.size());
    // Check get attribute
    System.assertEquals('CHILDREN', books[0].getAttribute('category'));
    System.assertEquals('WEB', books[1].getAttribute('category'));
    // Will return the first book element only
    TG_XmlNode book = root.getElementByTagName('book');
    // Getting node name is handy attribute 
    System.assertEquals('book', book.nodeName);
    // Easily get the text out of any TG_XmlNode using textContent, you can use the same property to replace the 
    // text too 
    System.assertEquals('Harry Potter J K. Rowling 2005 29.99', book.textContent);
    // To get c:title node inside the first book
    TG_XmlNode title = book.getElementByTagName('title');
    //Node value is available for getting textNode contents
    System.assertEquals('Harry Potter', title.nodeValue);
    // toXmlString is available on each node for better debugging assistance
    System.assertEquals('<c:title c:lang=\'en\'>Harry Potter</c:title>', title.toXmlString());
    // Last child of book node is price
    TG_XmlNode lc = book.lastChild;
    System.assertEquals('price', lc.nodeName);



    Fast Apex XML DOM TODO’s

    Though Apex Dom class wrappers like TG_XmlDOM and TG_XMLNode are almost complete. But still there are some todo’s most of them are for developer ease and rest are some pending API additions.

    • Give cool apex docs with rich samples for each API, for now Apex test cases is best place to refer API usage.  It includes
      • Add HTTP API samples with TG_XmlDom and TG_XMLNode.
      • Add API samples for common protocols like GDATA.
    • Include COST factor against each API exposed so that developers are aware which operation should be cached locally for saving script statements.
    • Implement and add testMethods for each of the following, As spring 10 API doesn't have direct methods for doing so many of the following methods might involve recursions etc to clone, compare and append/replace/insert child
      • appendChild()     Adds a new child node to the end of the list of children of a node
      • cloneNode()      Clones a node
      • getElementsByTagNameNS() Returns element for node’s local name and namespace
      • compareDocumentPosition()  Compares the document position of two nodes
      • insertBefore()     Inserts a new child node before an existing child node
      • isEqualNode()     Checks if two nodes are equal
      • isSameNode()     Checks if two nodes are the same node
      • replaceChild()     Replaces a child node