February 25, 2010

Fast Apex Xml Dom API Project Started !

Apex Spring 10 Dom classes (XmlNode, Document) were reviewed a few days back. I wrote following two blog posts To fill the gaps mentioned, I have started writing a “Xml Dom” wrapper around Spring 10 classes. This wrapper Xml Dom is named “Apex Fast Xml DOM” and is hosted on Google code (link). The sole motive of “Apex Fast Xml DOM” is to

  1. Reduce the heavy script limit usage using Spring 10 Apex DOM Classes internally.
  2. Provide a simple and easy to use API, that we are habitual of. No need to learn any new syntax. The APIs exposed will be similar to what some of you guys are already using i.e. Ron Hess XMLDOM.cls OR the standard DOM API’s listed here at w3cschools.com.

I would love to get your ideas around how API can be made more faster and cleaner. If you are interested to join as committer, please let me know.

For more details on this project please check the official Google Code WIKI page here.


February 18, 2010

Visualforce Page to Component JavaScript client side communication

On many occasions we might need to access some HTML DOM element inside a component from page using JavaScript. Example scenarios can be page fetching value of text field inside a component using JavaScript.

Though best is using native visualforce tags and server side communication as described here : http://wiki.developerforce.com/index.php/Controller_Component_Communication. As going client side requires careful usage of DOM element ids. So any minor change to html structure can easily break your code.

The Concept

In order to access anything on visualforce page you need to make sure element Id’s are assigned to each DOM element. That includes page, component, form, input fields etc

Once your DOM element ID’s are in place you can access any visualforce page element either using $Component global variable OR by manually forming correct id chains as per your element’s location in DOM. Using $Component is better practice, because when it is used inside a parent DOM element you don’t need to include parent’s ID to refer a child element.

To learn more about $Component variable go here. For those who want to do this manually, I would suggest using firebug add-on of Firefox, its great way to introspect in HTML DOM.

Code Sample

Communication will be illustrated using

  1. A Visualforce page named “PageCompCommunication.page”.
  2. A Component named “mycomp.component”.
  3. Apex controller class for component named “MyCompController”.

I will start with component and will finally illustrate the visualforce page.


This is the component that’s meant to be nested inside a visualforce page. This component simply has an apex:form and a text field inside it. Please not in code sample below that every DOM element in component is having an ID.

<apex:component id="comp_id" controller="MyCompController">
	<h1>Component Text :</h1>
	<apex:form id="pageform_id">
		<apex:inputtext id="comptextinput" value="{!compInputText}" />

This controller is just to bind the component’s text field. Its pretty simple apex code just having an attribute for the component’s input text field.

public class MyCompController {
  public String compInputText {get;set;}

  public MyCompController() {
    this.compInputText = 'Component Text Field Text';

This page encapsulates the component and has little javascript code to access the text field inside the component.  Following is the code for that page. Please note that using $Component saves us from prefixing the parent DOM element ID, so to access the same component text field is little simplified if we use this Global variable.

<apex:page id="page_id">

	<apex:sectionHeader title="Page to Component Test" />
	<!-- Clicking this will display the component's text field value -->
	<p><a href="#" onclick="javascript:showComponentInputValue()">Show
	Component Text Field Value </a></p>
		function showComponentInputValue() {
			// on can use 
			// document.getElementById('page_id:mycomp_id:comp_id:pageform_id:comptextinput') 
			// but that will require you to prefix it with "page_id"
			// Using $Component inside parent doesn't 
			// reqires you to know the parent element id

	<hr />
	<c:mycomp id="mycomp_id" />
	<hr />


Here is the screenshot that shows the alert getting displayed with component’s text field value, when the hyperlink is clicked.

To allow single test method execution from an Apex test class : SFDC Idea

Because of the troubles faced in debugging a single testMethod failure out of many in an Apex class, I posted this as an idea on SFDC Idea Exchange.

Eclipse Java/Junit plug-in has this support. For non java guys, Junit is an unit testing framework for Java and Eclipse has a great support to run single testMethods. So it could be really great to have this Java-Junit Style support in Apex too.  Here is an screenshot from sample eclipse java project, that shows the scenario where we have 3 test cases and we want to debug only one out of them



Here is the link to that idea https://sites.secure.force.com/ideaexchange/ideaView?c=09a30000000D9xt&id=087300000007YDCAA2

Guys if you agree with me, please promote it !

February 10, 2010

Apex script statements reduction, Tips & Tricks + How To write apex code that adds less to script statement governor limit ?


The ones who are working on big salesforce projects run out of script statements in many apex executions. This post tries to cover some tips tricks to reduce the apex script statement without much changing the code. Some common hits and myths around “What is really a script statement” are revealed.

What is an Apex script statement ?

Its any coded instruction that performs an action. In Apex, statements must end with a semicolon and can be one of the following types:

  • Assignment, such as assigning a value to a variable
  • Conditional (if-else)
  • Loops
  • Do-while
  • While
  • For
  • Locking
  • Data Manipulation Language (DML)
  • Transaction Control
  • Method Invoking
  • Exception Handling

for ex.

if (true) {
} else {
//NOTE: Above code is just 1 script statement, NOT 2 !
//Though there are two expressions executed here, one is IF condition and second is debug.

What gets counted into Apex script statements ?

I have seen many developers making there apex code ugly just to reduce the number of script statements. I respect this thought, as the end goal is to never cross or add significantly to the apex script statements governor limits. In this effort we sometimes do some reductions that are not really counted into script limits. Following are the code snippets and there equivalents that  use same script statements.

The UGLY IF ELSE block

// UGLY Script statement 
if (true) System.debug('true');
else System.debug('false');

// Equivalent more readable form, both on execution count 1 script statement
if (true) {
} else {

The ugly variable declaration.

// UGLY declaration of variables
String str1, str2, str3, str4;

// You might thing this will count as 1 script statement, its actually "4".
// Because short hand notation is expanded by many languages. So why do this :)

So there are few examples where developers can make there life really easy by writing well expanded and indented code. The thumb rule of apex is Any thing ending with semi-colon is script statement !”,  so here are the quick notes about what’s not a script statement

  • Any Apex Standard class methods that you invoke, doesn’t matters how complex its internally is. It will never get counter to your script limits.
  • Any curly braces { }, newlines and tabs you add are not script statements. Add them to make your code more readable.
  • Any conditional evaluations/expressions for ex. if (<conditional expression>) are not counted into script statement.

How to reduce Apex Script Statements ?

There are ways to do so. Following are some code snippets that explain this:

Collections like Map, Set, List

All these collections offer a shorthand way to initialize the collection at the time of declaration. This is really helpful if you are going to insert simple data, as that statement is just counted as 1 script statement. Check the example below.

// Way 1 to declare and populate a Map 
Map < integer , string > My_Map = new Map < integer, string >();
My_Map.put(1 , 'a');
My_Map.put(2 , 'b');
My_Map.put(3 , 'c');
//NOTE: It uses 4 script statements, so 1 script statement per key/value pair.

// Way 2 to declare and populate a Map
Map < integer, string > My_Map = new Map < integer, string > {1 => 'a', 2 => 'b', 3 => 'c'};
//NOTE: It uses 1 script statement, that involves map declaration, instantiation and population. :)

// Similarly one can create Set and List in following manner, this type on instantiation is counted as single script statement. 
Set <string> aSet = new Set <string>{'a', 'b', 'c'};
List<string> aList = new List<string>{'a', 'b', 'c'};
Combining multiple operations into one.

One can do so by wrapping an assignment statement, inside a condition or another assignment statement OR by calling a required API within a statement context. Though this mostly makes code fairly hard to understand, but reduces the number of script statements. Following code snippet illustrates that

// Creating anonymous Set inside List constructor scope, it counts as 1 script statement
List<string> aList = new List<string>(new Set<string>{'d', 'e', 'f'}) ;

// In the above example the set is created in a simple manner but we can go as complex as we want by invoking other methods.

Though there can be many more examples to above, but I really don’t appreciate doing this, as it really makes code hard to read.  A few more script statements are acceptable here :)

Who should care about reducing apex script statement ?

If you are writing simple customization for force.com/sfdc, then you really don’t need to bother about this. But this requires some consideration when you are a developer in following scenarios:

  • You are developing a library or utility Apex API that’s will be used by many others. Here any reduction in script statement is pretty useful, for ex. if you are writing something to parse a complex Xml structure, you might quickly add a lot to script statement in such API’s and this will leave less room for client code.
  • Developing for a large force.com customization or project. Here chances are there that many developers will be contributing to same Apex code flow, so keeping room for others will make you scale well.



February 8, 2010

Apex virtual abstract inheritance versus java inheritance !

Apex is said to be inspired from java. But if we compare the polymorphic behavior specially inheritance, apex inheritance is reciprocal of java inheritance. The difference can be stated in following one line

In Java we declare what methods can’t be overridden by the child classes VS Apex declares which methods can be overridden !

For example  in Java we use “final” keyword to stop overriding by child classes, this applies to both classes and methods. But in apex to make a class/method inheritable we have to declare it either “virtual” or “abstract”. So in Java one declares “What you can’t extend”, and in Apex you declare “What you can extend”.

Cons of Apex’s “what you can extend” philosophy 

  • Many times design evolve during coding. You create a bunch of classes and later extend/inherit them to provide more specialization. This is quite easy if you are developing on your own, but if you are integrating with other’s api via managed packages, then you need to ask a new package release to extend some features. This can happen easily in case if we are distributing utility api’s or framework api’s written in apex as managed packages, developers might use many of those Api’s directly but extension/specialization might be required for some in many cases.
  • Classes should be open to specialization by default, if we want to restrict something from getting specialized we should restrict that only.
  • Apart from “What you can extend”, apex also requires you to add “override” keyword before the method you are specializing. That’s again kind of strange, the compiler or run time binding should be smart enough to detect that.

Here is a code sample below that explain the pain in doing a little Object oriented stuff in apex. Java developers know how simple this code will be in JAVA. This example illustrates a simple specialization of “ElectricDevice” class with “Fan”. Notice the use of “virtual” and “override

Apex Code inheritance Sample

public class Polymorphic {
 // PowerSupply class,
 // some stuff to setup and initialize a powersupply
 public class PowerSupply {}

 // Class must be virtual or abstract 
 // without this one can't extend it 
 public virtual class ElectricDevice {
  // Child implementations never need to change this.
  public void plugToPowerSupply(PowerSupply power) { 
   // Code to plugin to powersupply
  // Default device stuff to turn it ON. 
  //Child implementations can change it
  public virtual void turnOn() {} 
  // Child implementations use this do there specifics,
  // after Turn ON.
  public virtual void postTurnOn(){}
  // Default device stuff to turn it OFF. 
  //Child implementations can change it
  public virtual void turnOff() {}   
 public class Fan extends ElectricDevice {
  // overriden turnOn only
  public override void turnOn() {} 
  public override void postTurnOn() {
   // Code to start rotation of fan   

Java Code inheritance sample

This sample is to show, how simple the same code could be in Java. We just used "final" with plugToPowerSupply(), all other stuff is open to inheritance :)

public class Polymorphic {
 // PowerSupply class,
 // some stuff to setup and initialize a powersupply
 public class PowerSupply {}
 // No virtual or abstract 
 public class ElectricDevice {
  // Child implementations never need to change this.
                // NOTE: only "final" added here.
  public final void plugToPowerSupply(PowerSupply power) { 
   // Code to plugin to powersupply
  // Default device stuff to turn it ON. 
  //Child implementations can change it
  public void turnOn() {} 
  // Child implementations use this do there specifics,
  // after Turn ON.
  public void postTurnOn(){}
  // Default device stuff to turn it OFF. 
  //Child implementations can change it
  public void turnOff() {}   
 public class Fan extends ElectricDevice {
  // overriden turnOn only
  public void turnOn() {} 
  public void postTurnOn() {
   // Code to start rotation of fan   

Though Apex is a great language and is adding cool new features. But I wish the can really use java style inheritance.

February 4, 2010

Apex Dom Document XmlNode bad design story


While doing some coding using the new Apex DOM classes I felt so frustrated regarding BAD BAD class design, that I decided to write a post covering my experiences. For checking the good parts of API please check my previous post.

Why DOM Document & XMLNode sucks ?

Both of the new classes Document and XMLNode miss pretty common and popular DOM methods for ex.

  • getElementsByTagName(String nodeName) : Why this is missing, is it tough for Salesforce developers to expose ??
  • getElementsByPath (String path) : Ok, this is missing too. Its tolerable :)
  • addChild(XmlNode node) : Why can’t I add a First Class XmlNode inside an XMLNode.
  • toXmlString() : One has to call DOM.Document.toXMLString(), this prints the whole XML. But I don’t want that big pollution in my logs.

Only relief is that XMLNode gives “getElementByTagName()” as “getChildElement()”. getElementsByPath() is not much used by everyone, but “getElementsByTagName()” is really a must have. So developers might write wrappers to use XmlNode.getChildren or XmlNode.getChildElement to get the missing api’s. But again, every wrapper is apex and every line apex line you write will add to script limits. But the fact that hurts me most is missing “addChild(XMLNODE)”, I guess this method is pretty powerful and helps a lot on many occasions, developers who deal with XML parsing know this very well :). Imagine a situation when you have a pretty complex child node that you get from an web service call and its supposed to go inside a big xml parent node. I would say salesforce API team should at least consult existing XmlDom class for its intuitive design and ease to use.

Apart from that the API and its docs both are confusing. There are two methods in Dom.XmlNode

  • String getAttribute(String key, String keyNamespace)
  • String getAttributeValue(String key, String keyNamespace)

Apex docs for both of these is same : “Returns the attribute value for the given key and keyNamespace.” So why the hell there are two APIs that do same thing, receive same arguments and return same type. Here is the link for Apex docs. For quick look here is the screenshot.


Now I felt the real pain, when I started porting a XMLDom based apex code to Dom.Document/XmlNode. I will not say anything, will just add code snippets for both, you can feel the pain. The example code below is for parsing a Google Gdata feed.

    // USING XMLDOM.cls
    public Integer getTotalResults(XMLDom.Element feed) {
        Integer intVal = null;
        String  intValStr = feed.getValue('openSearch:totalResults');
        if (intValStr != null) {
            intVal = Integer.valueOf(intValStr);    
        return intVal;
    // Using DOM.XmlNode
    public Integer getTotalResults(Dom.XmlNode feed ) {
        Integer intVal = null;
        // NOTE:
        // 1. I have to check if getChildElement is null 
        // 2. I have include namespace, it doesn't works without that.
        String  intValStr = feed.getChildElement('openSearch:totalResults','http://www.w3.org/2005/Atom').getText();
        if (intValStr != null) {
            intVal = Integer.valueOf(intValStr);    
        return intVal;

Though most of you already know the design of XmlDom.cls I am still sharing that below.


I still love the simple design of XmlDom.cls, and wish salesforce can create a replica of that instead reinventing the wheel and giving “Document and XmlNode”. This will help to

  • Reduce the efforts(Code change) required in migrating to the new DOM classes.
  • Reduce the “Learning curve” to almost zero.
  • Reduce the  requirement to fix the API holes, by writing wrapper classes.

In starting I was pretty excited about this new Spring 10 API, but the excitement ended soon when I started using it. Its really a pain to use and worst design Apex API for me.

February 3, 2010

Apex DOM classes Document XMLNode reviewed - Spring 10 Release !


I was going through the code sample and apex docs for new Spring 10 Apex DOM Classes. I feel these new classes are really a great missing piece for apex developers  that work on integrations via web services(XML) for ex gdata api’s. Though the API is a huge benefit for apex developers , but the design of the API could be much better for ex. the pretty popular “getElementsByTagName” method is not available. So in this post I will try to explore the good and the bad/missing part of this new API.


Apex Dom Classes, the good part !

The only major advantage I see from this API is “It by passes governor limits for script execution”. I didn’t mentioned XML DOM parsing/creation here, because we have XMLDom.cls available for free. This class is pretty well designed and does all the required stuff for traversing and creating a XML document.

But the problem with XMLDom is that its a normal apex class, just like the classes we create. So any operation it does counts against the governor limits and execution cost. The major two issues with XMLDom.cls are :

  1. Governor limits: It consumes a lot from “Total number of executed script statements” limit.
  2. XmlDom methods like parseXMLReader, getElementsByTagName(), toXmlString are pretty time consuming and costly.
  3. It pollutes the debug logs :))  


Good Part 1 : Governor Limits advantages over XMLDom.cls

If you are parsing a big XML using XMLDom its pretty much possible that  you will end up in getting or close to limit : “Total number of executed script statements”.  For maintaining big  XML node hierarchy XMLDom has to create a big nested Node structure, that involves creating too many XmlDom.Element instances. Together with this operations like parseXmlReader, getElementsByTagName and toXmlString(which is called just for debugging), adds a lot to the script execution limit count. If you check your debug logs for a big XML, they will be flooded with information from these XMLDom methods. So if someone is lucky enough to get a web service XML response while fighting the 100KB response limit, this XML parsing will make him fail for sure.

Here is snippet of debug logs for a pretty common XML response when working with GDATA feeds.

20100203083559.140:Class.XMLDom: line 117, column 24:     returning from end of method public Element(String) in 1 ms
20100203083559.140:Class.XMLDom.parseXmlReader: line 63, column 21:     returning from end of method public Element(String) in 0 ms
20100203083559.140:Class.XMLDom.parseXmlReader: line 77, column 5:     returning from end of method public void appendChild(XMLDom.Element) in 0 ms
....... Trimmed similar 200 lines of Class.XMLDom.parseXmlReader 

20100203083559.140:Class.XMLDom.Element.getElementsByTagName: line 194, column 3: SelectLoop:LIST:XMLDom.Element
20100203083559.140:Class.XMLDom.Element.getElementsByTagName: line 194, column 3:     Number of iterations: 0
20100203083559.140:Class.XMLDom.Element.getElementsByTagName: line 195, column 16:     returning LIST:XMLDom.Element from method public LIST:XMLDom.Element getElementsByTagName(String) in 0 ms
20100203083559.140:Class.XMLDom.Element.getElementsByTagName: line 194, column 3: SelectLoop:LIST:XMLDom.Element

....... Trimmed similar 600 lines of Class.XMLDom.Element.getElementsByTagName 

20100203083559.140:Class.XMLDom.Element.toXmlString: line 225, column 3: SelectLoop:SET:String
20100203083559.140:Class.XMLDom.Element.toXmlString: line 225, column 3:     Number of iterations: 1
20100203083559.140:Class.XMLDom.Element.toXmlString: line 230, column 3: SelectLoop:LIST:XMLDom.Element

....... Trimmed similar 250 lines of Class.XMLDom.Element.toXmlString

toXmlString() is the only guy we can avoid debugging, but getElementsByTagName and parseXmlReader are unavoidable. So for sure the new Apex Document and XMLNode classes will help a lot here.

Good Part 2 : Native Document and XMLNode will be faster then Apex XMLDom.cls

This again comes from apex profiling. If we check the debug logs to figure out the "10 most expensive method invocations”. You will for sure find these two

  • Class.XMLDom: parseXmlReader() : executed 133 times in 1202 ms
  • Class.XMLDom: getElementsByTagName() : executed 407 times in 1183 ms

These result I got when trying to publish to Google sites using apex controller. So I am saying this as a good part of new API because “The new API is no more Apex class, it must be something native like a Java code. So it will execute faster than the Apex.”


Apex Dom Classes, the BAD part !

Bad part was too much to be in this post, it deserves its  own post. So moving it out of this. Check the BAD part here (http://www.tgerm.com/2010/02/apex-dom-document-xmlnode-bad-design.html).

But I will end the post, by giving my sincere thanks to salesforce team to come out with this API. at least it will give us more bandwidth from governor limits :)

February 1, 2010

Visualforce Salesforce jquery Ajax how to ?

Edits - Nov 2011

This post was written long back in Feb 2010, since then force.com platform is drastically upgraded/changed. The illustration indicated in the post below can be achieved very easily using new platform features like Javascript Remoting.

So if you are planning to use JSON with jquery/javascript, more fun way to achieve the same is remoting, this post is a good guide to start with remoting & jquery :




This post is for those who want to make AJAX calls in visualforce using 3rd party JavaScript frameworks like jquery, yui , dojo etc. Though most the times the built in visual force Ajax works pretty well and you don’t need to make your hands dirty by doing this. But but but, there are couple of occasions when its required for ex.

  • You are working on a complex DOM structure i.e. there is nesting of HTML elements in a manner not easy to deal with Visual force tags.
  • You want to update the DOM client side, this requires some Ajax calls to query server side data.
  • Visualforce Ajax gives you a way to do this by calling “rerender”, but you want more control on request and response data.


Following is the high level design of custom Http request response in salesforce


So this design comprises of following elements

  1. A dedicated Visualforce page for receiving inbound Ajax http requests. Lets call this page “AjaxResponder
  2. This page can return either “JSON” or “XML” response.
  3. For doing all server side logic an Apex Controller is required that will do the SOQL/SOQL queries. Lets call this “AjaxRespController
  4. A client page to test and do all the Ajax calls. Lets call this “AjaxClient

Implementation (Apex Visualforce code)

We will start with the Server Side code first i.e. AjaxResponder(Visualforce Page) and AjaxRespController (Apex Controller). At last you can find code for the Ajax client page.


Simple visualforce page. Please note that you need to add following apex:page headers. This is because we don’t want any other HTML markup from salesforce in Ajax response.

  • showHeader = false
  • standardstylesheets = false
  • sidebar = false

Apart from this you need to set the content type for JSON response, so add the header contentType="application/x-JavaScript; charset=utf-8". For printing JSON text in visualforce page, just create a string attribute in your controller, for this demo I created “result”, and add this to VF code like this {!result}.

<apex:page controller="AjaxRespController"  action="{!doSearch}"
contentType="application/x-JavaScript; charset=utf-8" showHeader="false" standardStylesheets="false" sidebar="false">

AjaxRespController (Apex Controller):

Controller will check the Ajax request parameters and will do the SOQL query stuff. In the code snippet below doSearch() method is called on Ajax call. We have used JsonObject, this is a class adopted from json.org by Ron Hess. You can get it from here. Apart from this there is a getter method called “getResult” it returns the JSON response back to visualforce.

public class AjaxRespController {
    public JsonObject json {get;set;}
    /** invoked on an Ajax request */    
    public void doSearch() {
        Map<string,string> params = ApexPages.currentPage().getParameters();
        json = new JsonObject();
        // Do SOQL query to see if there are any records !
        List<Contact> records = getRecords(params.get('q'));
        if (!records.isEmpty()) {
            // Jsonify the results !
            List<JSONObject.value> values = new List<JSONObject.value>(); 
            for (Contact c : records) {
                JSONObject cjson = new JSONObject();
                cjson.putOpt('name', new JSONObject.value(c.Name));
                cjson.putOpt('email', new JSONObject.value(c.email));
                values.add(new JSONObject.value(cjson));
            json.putOpt('contacts', new JSONObject.value(values));
    // Does the SOQL query, using Ajax request data
    public List<Contact> getRecords(String contactName) {
        List<Contact> records = new List<Contact>();
        if (contactName != null && contactName.trim().length() > 0){
            // Protect from SOQL injection            
            String contactNameToFilter = '%' + contactName  + '%';
            records = [select id, name, email from contact where Name like :contactNameToFilter];
        return records;      

    // Returns the JSON result string
    public String getResult() {
        return json.ValuetoString();

Ajax Client (Visual force):

This page is one that presents the user interface to query the results via custom Ajax. The code below is simple markup to do Ajax calls and show JSON response. Please note here in code that to make Ajax calls work, you need to pass an extra param "core.apexpages.devmode.url" with value '1'. This is required because without this param the visualforce page is opened in an iframe and you get the iframe code wrapped in other crappy html.

<apex:page showHeader="true" standardStylesheets="true" >

        type="text/JavaScript" />
    <script type="text/JavaScript">
    function search() {
                "Making a Jquery Ajax Request to '{!$Page.AjaxResponder}'");

        // Make the Ajax Request
        $.getJSON("{!$Page.AjaxResponder}", {
            "core.apexpages.devmode.url" :'1',
            "q" :$('#query').val()
        }, function(data) {

        $("#status").html("Ajax Request Completed !");

    <apex:sectionHeader title="Ajax Client Demo" />

    <apex:pageblock >
            <apex:pageBlockSection title="Query Console">
                <form id="qform">Query String <input type="text" id="query" />
                <input type="button" onclick="search()" value="Search Contacts " /></form>

            <apex:pageBlockSection title="Ajax Console">
                <pre id="status" style="font-size: 16px" />
                <h1> JSON Response </h1> 
                <div id="response" style="font-size: 16px;width: 300px;font-family: monospace; font-stretch: expanded" />


Here is this UI in action


You can copy all the code snippet above and run it directly on your salesforce org. Just replace “[NODE]” in following URL by yours.