Apex RoundingMode

One of the things that always sends me searching through my old code is rounding. I can never remember the syntax and the Apex documentation on Decimal methods on the Salesforce Developer site doesn't provide any examples inthe description (Its somewhat hidden up in the Divide method description if you look for it) . So, I thought I'd put a few examples here as a reminder to myself and to share with everyone else Googling it. 

Decimal numberToRound = 12.345;
Decimal roundedUp = numberToRound.round(roundingMode.UP); //result: 13
Decimal roundedDown = numberToRound.round(roundingMode.DOWN); //result: 12
Decimal scaled = numberToRound.setscale(0); //result: 12 – no rounding specified, just removes decimal places
Decimal scaledUp = numberToRound.setscale(0, roundingMode.UP); //result: 13 – no rounding, just removes decimal places

Look at the documentation on the RoundingModes for more detail on Ceiling, Half_Down, Half_Up, etc. 




Salesforce Technical Architect Certification; Part 1 Multiple Choice Exam

Yesterday, I passed part two of the three-part Technical Architect Certification for Salesforce.com. (Step one being the self-evaluation; which really doesn't count given that its free and you can take it repeatedly until you pass.) The third and final step will be a four hour session presenting two cases in front of a live review board of technical architects. I've got a few months to prepare for that. So, in the meanwhile, I thought I'd do a bit to help anyone who might be prepping for the exam while its still fresh in my mind.

1. Find out what you don't know

When I went through the self evaluation, I wrote down the terms that I was less familiar with and made a point of researching them afterwards. This was helpful because a lot of the study resources listed below will assume a certain level of knowledge and make reference to terms without necessarily defining them for you. Though I've been an architect and working with Salesforce for several years, I didn't come from an EAI background, so I wasn't as familiar with industry jargon like Enterprise Service Bus (ESB) or Execute, Transform, & Load (ETL) as they referred to integration and middleware. Honestly, I only first heard the acronym EAI last week and I had to go look it up. 

So, if you're stronger on the functional side get familiar with Apex and Visualforce to the level where you can define an Apex abstract class and explain how it might differ from an interface. If you are a developer, make sure you know what can be better done with configuration (Declarative) vs code (Programmatic). In the majority of cases, the former will be preferable to the latter. In that same vein, understand when it is better to use synchronous (web service) vs asynchronous (outbound messaging) callouts. If you don't have a background as a network admin, understand proxies and firewalls and how they might need to be configured to successfully allow salesforce to connect to internal systems in the DMZ (also know what that term means).

Personally, I had little direct experience working with SSO, Large Data Volumes (LDV), REST API, and Heroku. So I put a little more focus on those areas.

Learn the differences between three types of SSO available to Salesforce - delegated authentication, SAML, and Oauth – and when using an appexchange partner like Ping Identity might be appropriate. The comparison matrix here was very helpful to that end.

The most important thing about LDV was knowing the line of demarcation; 2 million records or greater. Next understand what it take to import that volume of data. Also, familiarize yourself with skinny tables and know that in some cases you'll need to de-normalize data or create external id fields (which are indexed) for reporting and performance. Lastly, know when to question if importing the data is even the best approach – does it need to be used for reports or processes in Salesforce (ie workflows, escalations, etc) or can be be accessed on demand via web service callouts or mashups. 

Know the difference between Soap, Rest, and Bulk API's and which situations call for each. Also understand the methods for securing inbound API calls and how an external system might verify that an outbound message or callout came from Salesforce – certificates, 2 way SSL, ip restrictions, trusted ips, remote site settings.

2. Dive in

I was fortunate enough to have access to some proprietary webinars and study materials that I can't make publicly available. However, if you are a Salesforce partner look into getting access to the study group in the Partner Academy. Otherwise, if your Salesforce org has paid for Premier Training there are some self-paced technical architect courses available in the online catalog- https://help.salesforce.com/apex/HTTrainingCatalog.

The following is a list of publically-available material that I reviewed prior to the exam. 
















3. Exam Tips

The exam itself is 60 questions and 120 minutes long. So, you can't dwell too long on any one question. If I didn't know some of the people who wrote the questions, I would swear some of them were written by lawyers. (I kid because I love.) In all seriousness, there are some questions where you may need to just pass and move on. If you read a question more than two times and find yourself going for a third, just flag it for review, select a random answer, and move to the next. Don't sacrifice five questions you do know for one question that you might. My strategy was to do a first quick pass through the exam and tackle only the easy low hanging fruit. Then I did a second pass on those I had flagged for review (a little less than half) with a better sense of how much time I could afford each. 

The questions follow your typical standardized testing format, in that, of the answers given, one is egregiously incorrect, another is incorrect because of some slight twist in phrasing and of the choices remaining one is better than the other. There were only a handful of questions where the correct answer jumped out at me. In the cases where it didn't, I identified the incorrect answers first and then evaluated those that remained. From what I recall, about the majority of questions were evenly split between selecting a single answer and two. Only a handful required selecting three. You don't get credit for partially correct answers so do give those a bit more time.


Good luck.


Added May 16, 2012 – Continued in Salesforce Technical Architect Certification; Part 2 – Review Board

Determining Salesforce Server Pod and if Sandbox via Apex

Recently, I’ve developed some apex classes that were doing callouts to external endpoints like CastIron and Worldpay. I was developing those in a sandbox and from that sandbox called to test endpoints. However, when that code was migrated to production, we obviously wanted those to point to the production endpoints. At first, I used Custom Settings to hold the endpoint value, but I had to change that each time I refreshed. I wanted to store both the test and production endpoints in the custom settings and have the code determine which to use based on if it was being called in a Sandbox or not. Unfortunately, there isn’t a IsSandbox() method in Apex. So, I figured out my own.

I started off using the X-Salesforce-Forwarded-To request header listed in the pagereference documentation because it gave me a consistent value for users accessing Salesforce via the standard interface, Partner Portal, and Sites. However, because you’re using ApexPages.currentPage(), this only works if the code is called from a page controller or extension. In my tests, I tried using URL.getSalesforceBaseUrl(), which can be called from regular classes, but it was inconsistent what was received. For example, I tried calling GetHost() and GetAuthority() from the system log and got cs12.salesforce.com. But with with internal and portal users, a visualforce page returned c.cs12.visual.force.com. Conversely, when using sites I received SiteName.SandboxName.cs12.force.com. So, my approach was determine which method to use based on where the call was coming from in order to get consistent results. 

Parsing out the domains gave me the exact pod that I was on (ex NA1 or CS12) and from that I could determine if that pod was a sandbox or not from whether it started with a “c”. (You can see the full list of available Salesforce pods at http://trust.salesforce.com/trust/status/)

Note: I haven’t tested this with a Site with a Custom Web Address or URLRewriter classes. If you do, please add a comment with your results.

Here’s my code;


public String currentPod {
String server;
if (ApexPages.currentPage() != null){ //called from VF page
server = ApexPages.currentPage().getHeaders().get('X-Salesforce-Forwarded-To');
} else { //called via standard class
server = URL.getSalesforceBaseUrl().getHost();
if ( server != null && server.length() > 0){
server = server.substring(0 ,server.indexOf('.'));
return server ;
public Boolean isSandbox {
String pod = currentPod();
if (pod != null && pod.length() > 0 && pod.toUpperCase().startsWith('C')){
return true;
return false;

Get your Salesforce project stats using Apex

I mentioned recently that I was working an a rather large project and posted some stats on how many classes, custom objects, etc were involved. Of course, I didn’t count those by hand. I wrote a little script that I run via Execute Anonymous either in Eclipse or in the System Log. Thought I’d share that out.

In the code below I filter out any managed packages because I just wanted stats on stuff that I had done. Feel free to modify the queries to your specific needs.


Integer triggerCount = 0;
Integer codeLines = 0;
Integer classCount = 0;
Integer componentCount = 0;
Integer pageCount = 0;
Integer customObjectCount = 0;
for (ApexTrigger t : [Select a.NamespacePrefix, a.Name, a.LengthWithoutComments From ApexTrigger a where NamespacePrefix = null]){
codeLines += t.LengthWithoutComments;
for (ApexClass a : [Select a.NamespacePrefix, a.Name, a.LengthWithoutComments From ApexClass a where NamespacePrefix = null]){
codeLines += a.LengthWithoutComments;
for (ApexComponent c : [Select a.NamespacePrefix, a.Id From ApexComponent a
From ApexComponent a where NamespacePrefix = null]){
for (ApexPage p : [Select a.NamespacePrefix, a.Id From ApexPage a
From ApexPage a where NamespacePrefix = null]){
Map gd = Schema.getGlobalDescribe();
for (Schema.SObjectType s : gd.values()){
Schema.DescribeSObjectResult r =s.getDescribe();
if (r.isCustom()){
system.debug('---------Project Stats---------')
system.debug( 'triggerCount = ' + triggerCount);
system.debug( 'codeLines = ' + codeLines);
system.debug( 'classCount = ' + classCount);
system.debug( 'componentCount = ' + componentCount);
system.debug( 'pageCount = ' + pageCount);
system.debug( 'customObjectCount = ' + customObjectCount);

Quicker Salesforce Setup with Greasemonkey

I’m currently the technical architect on a huge Salesforce project in the UK. How huge? 108 custom objects, 338 Apex classes, 22 components, 59 triggers, 152 VisualForce pages and growing.

You can imagine how frequently you’d be updating custom objects, checking their layouts, field security etc. You click setup, create, custom objects, scroll up and down the list till you find it, click on the object, scroll up and down to find what you wanted. Exhausting. Thanks to Tim Dupont over at Reside for turning me onto a much better way.

He uses a GreaseMonkey script that inserts Custom Objects as a top level node on the App Setup tree. That combined with the new quick find feature, makes getting directly to what you want to edit quick and easy. Script can be found at http://userscripts.org/scripts/show/95361 I wish it also worked for classes and pages and such, but I’m usually doing that in Eclipse anyway.


Additionally, I found a suggestion by TehNrd for another script so that you only have to mouseover your name to see the setup menu rather than click. Get that one at http://userscripts.org/scripts/show/87406

Installing Force.com Migration Tool (Ant) on Mac OsX

I was trying to run ANT to migrate code between two Salesforce orgs today and realized I hadn't configured the Force.com Migration Tool properly for my new Mac. I kept getting the error; [antlib:com.salesforce] Could not load definitions from resource com/salesforce/antlib.xml. It could not be found.

I already had the latest version of Eclipse installed, which handles the Ant installation for you. You can confirm this by typing ANT-version in Terminal. So, it was just a question of getting the migration tool in the Ant lib directory. (This took me a bit of searching hence this quick post).

  1. Download the Force.com Migration Tool (instructions here).
  2. Unzip the file
  3. Open a terminal window in the directory of the unzipped file (See my last post for a quick way to do this)
  4. Type: sudo sh
  5. Enter your password
  6. Type: cp ant-salesforce.jar /usr/share/ant/lib/ant-salesforce.jar

Now you're good to go. Check out Jeff Douglas' blog post on the hows and whys of this tool.

Visualforce & Apex Syntax Highlighter for Typepad

** Update: Aug 22nd, 2015 – I’ve recently moved this site to WordPress.com which includes native support for the SyntaxHighlighter plugin, but not the ability to add additional brushes. As a result, the samples below may not display exactly as they would in Typepad. **

In a recent post and really in a lot of my posts, I’m presenting code samples. Typepad lacks a nice ‘Insert Code’ button in its WYSIWYG editor, so I’ve been using indents and italics to offset code from the rest of the text. Not ideal since its not easily read, doesn’t wrap well, and is hard to copy and paste.

A quick Google of the Interweb located a nice tutorial on adding Syntax Highlighter to Typepad. However, in looking at the list of default ‘brushes’ available I saw the usual suspects (ie Javascript, CSS, Perl) but not Apex or VisualForce.

But I’ve seen this on the Saleforce Developer Wiki, so I poked around in View Source and Voilà! Looks like Salesforce has a custom brush and style for Syntax Highlighter.

I don’t have the Pro ver$ion of Typepad and couldn’t add the JS and CSS directly to a custom template. So, I followed the steps of the tutorial above to add a custom component with the necessary HTML. Here’s a step by step with a few more details specific to the VF/Apex theme.

Download the Syntax Highlighter. Then in the Typepad Library, create a folder called syntaxhighlighter and two subfolders; scripts and styles.


Upload Script Files -There are a bunch of JS files in the Syntax Highlighter download; each of the type of codes you want to display (ie Javascript, Perl, CSS). At a minimum you need shCore.js and one other. Upload that to the scripts directory along with shBrushVisualForce.js and any others you desire.



Upload Style Files – Again there are a bunch of CSS files here each for a different theme. I like the default theme so I only added shCore.css, shThemeDefault.css, and the custom theme shThemeApexVF.css.

In Typepad, navigate to your blog (if you have several you’ll have to repeat this process for each). Click the Design tab at top, and then the Content tab on the left.

Syntax 3

Select the Embed your own HTML module and click the Add button.

Name your component Syntax Highlighter or something like that. The name won’t appear on your site. Copy and paste the following, replacing http://www.YOURWEBSITE.com with your website’s name. (If I have to explain this further, you probably shouldn’t be posting code on your site.)

<!-- Include required JS files -->
<script src="http://www.YOURWEBSITE.com/syntaxhighlighter/scripts/shCore.js" type="text/javascript"></script>
<script src="http://www.YOURWEBSITE.com/syntaxhighlighter/scripts/shBrushVisualForce.js" type="text/javascript"></script>
<!-- Include *at least* the core style and default theme -->
<link href="http://www.YOURWEBSITE.com/syntaxhighlighter/styles/shCore.css" rel="stylesheet" type="text/css">
<link href="http://www.YOURWEBSITE.com/syntaxhighlighter/styles/shThemeDefault.css" rel="stylesheet" type="text/css">
<link href="http://www.YOURWEBSITE.com/syntaxhighlighter/styles/shThemeApexVf.css" rel="stylesheet" type="text/css">
<!-- Important options, and finally the main call -->
<script type="text/javascript">
 SyntaxHighlighter.config.tagName = "code" // use <code> tags
 SyntaxHighlighter.config.stripBrs = true // disregard trailing 

Click Save Changes at the bottom and you’re done.

Now to test your work, start a new post.

Click the HTML tab on the WYSIWG. And then cut and past the following.

<code class="brush: VisualForce">
<apex:page standardcontroller="Account">
  <apex:outputfield value="{!Account.Name}"></apex:outputfield>
  <apex:outputfield value="{!Account.OwnerId}"></apex:outputfield>

Click Preview and you should see a nicely formatted code like below.

<apex:page standardcontroller="Account">
  <apex:outputfield value="{!Account.Name}"></apex:outputfield>
  <apex:outputfield value="{!Account.OwnerId}"></apex:outputfield>

I’ve noted a few odd behaviors. First off, Typepad is inserting <![CDATA[ into the code when I flip from HTML to Rich Text view after pasting in some code with the javascript brush class.

Secondly, the Highlighter doesn’t seem to like self closed tags and inserts the closing tag, though incorrectly. This happens even with the Plain text brush. For example;

<apex:page StandardController=”Account”>
<apex:outputLabel value=”{!$ObjectType.Opportunity.fields.Amount.label}” for=”Amount”/>
<apex:outputField value=”{!Account.Name}”/>

gets replaced with …

<apex:page standardcontroller="Account">
  <apex:outputlabel value="{!$ObjectType.Account.fields.Name.label}" for="AcctName">
  <apex:outputfield value="{!Account.Name}" id="AcctName">

Also, the code doesn’t always appear in the Rich Text editor though it is still there and visible in HTML view.

So while not ideal, but I can live with it these idiosyncrasies for now as I get more familiar with the tool. Just be sure to adjust your post workflow to paste code in HTML mode last (and not flipping back to Rich Text) and previewing the code to check for any odd replacements.

Hope you find this helpful.