Tag Archives: Apex

The rise of the Force.com Platform


“The Force.com Platform is growing.”

For anyone in enterprise development this is an obvious statement, what might not be so obvious is why it’s growing. Or how the heck it’s growing at such a frenetic pace. There are some great, recent articles out there that postulate on this point. “Great vision” they say, or “Great execution”. Of course these things are true, salesforce.com is unique in its sales, marketing, vision and execution putting it leagues ahead of others, but I think that there is a greater factor that eclipses all other points.

If a developer doesn’t care for your platform and platform tools then you won’t have anyone to deliver, a dead-end that many companies have found the hard way. But with the Force.com Platform – for the first time in the history of the world (I’m taking liberties) – enterprise software development is cool. And not just a little bit cool either, we’re talking jQuery-Ruby-zomgHowCuteIsThatCat cool.

But don’t take my word for it. Go out there and ask the community, or even better just look at the Apex page on github.

Apex on Github

Apex on Github

69th position might not seem all that good but let’s see where ABAP (SAP-proprietary language) is featured in the list, hmmm. Oh it’s not, what a surprise. The exact ranking is not that important though (it’s was in 70th position 1 week ago so it’s climbing folks!), what is important is that a very young, proprietary programming language has seen wide enough adoption to gain its own category on github at all, and that the open source community is building with it!

Developers drive the state of the Internet, they’re the people who see new trends emerging ahead of others and are typically the early adopters that determine whether a technology makes it to the business-viable stage. The developers of the enterprise world have given the Force.com Platform their blessing, a rare and powerful thing, and salesforce.com is now reaping the incredible benefits.

If you’d like get a great overview of the platform capabilities the VP of Dev Relations will be in London next week and he’s talking about the platform at a free public event that you’re all invited to!

Tagged , , ,

Force.com: Top Testing Tips Session at Dreamforce 2012


After an 11-hour flight from London the Tquila team has arrived in San Francisco for DFX! I hope to see many of you around town, and if your schedule isn’t already full it would be great to see you at an awesome session I’m delivering on Tuesday, September 18th: 4:00 PM – 5:00 PM at Moscone Center West, 2024.

Ami Assayag and I will be talking about “Top Testing Tips” on the Force.com Platform. We believe that our talk will help you take your Apex code testing to the next level with sample code and open source libraries that make these advanced topics easy. You’ll learn to save time with SmartFactory, which automatically creates complex test data for tests isolated from your regular data, and how to test web callouts cleanly and completely using interfaces and mocks. Finally we’ll talk about how to make sure all your team’s tests run regularly with native Force.com automation that takes a fraction of the time of full continuous integration.

You can register for the session here, and feel free to grab me after the talk if you have any questions or just want to say hi.

Tagged , ,

Grokking Force.com – Apex


This is a cross post from my blog here.

Over the past few years, as a Force.com developer, I have come across a few interesting features and gotchas on the Force.com platform that are either not documented, or is documented but developers don’t know about it. This post describes some of the quirks and some unknown facts of the Apex language that you might or might not have seen. Let’s dive in!

Map accepts null as a key

According to the Apex docs:

A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, while values can be primitive, sObject, collection type or an Apex object.

And right at the bottom of the page, it also notes:

A map key can hold the null value

So the following code is a perfectly legitimate apex code:

Map<Id, String> testMap = new Map<Id, String>();
testMap.put(null, 'foobar');
System.debug('the value of the null key is: '+testMap.get(null));
//outputs: The value of the null key is: foobar

Allowing null as a key to a map is a design flaw IMHO, therefore, it is a good idea to check for null before adding the key to a map variable. This information is also useful if you are wondering, why your map is returning null values?!?, when it’s not supposed to, especially, when you instatiate a map with a SOQL result where the values returned can be null unless you explicity check for null values in the where clause.

Unit Tests increment your Objects unique Id

This is not covered in the documentation, or atleast I haven’t found it in the Apex docs. When you run unit tests that insert/create records for a particular object(standard or otherwise), it increments the value of the Name field(of type Auto Number) outside of the test context.

Let’s say you have a custom object “Invoice Statement” (Invoice_Statement__c) that has a Name field called “Invoice Number”, and is of type “Auto Number”. The format of the field is: INV-{0000}, and let’s assume that the latest record number is INV-2058.

If you insert 10 records in the test class as follows:

// Let's assume that this runs inside of a test method
List<Invoice_Statement__c> invStatementList = new List<Invoice_Statement__c>();
for(Integer i = 0; i < 10; i++) {
  invStatementList.add(new Invoice_Statement__c(company='acme ltd');
}
insert invStatementList;

Now, when you insert a new Invoice Statement record outside of the test method via a trigger, or batch, or the User Interface, the next inserted record will have the id INV-2069. So don’t rely on the unique name field if you have strict rules around the auto-increment feature in your application. Instead add a custom field which is auto-incremented in a workflow or trigger to have more granular control over how the value is incremented.

Divide (/) operator gotcha

What do you think should be the output of this statment?

 system.debug('7 divided by 2 is: '+7/2);

If you think it should be 7 divided by 2 is: 3.5, then you are wrong. The actual output is - 7 divided by 2 is: 3. If the operands of the divide(/) operator are both integers, the result is an integer.

If you want a decimal output then one of the operands must be a decimal, so the following code:

 system.debug('7 divided by 2 is: '+7.0/2);

will output 3.5. I have spent many hours trying to figure out what’s wrong with my code when I realized that x/y (x and y being integers) wasn’t returning an accurate decimal value. So make sure when you use the divide operator atleast one of the operands is a decimal.

Improve SOQL and SOSL performance by adding NULLability check

This is actually highlighted in the Apex docs, but I have seen many experienced devs(including myself) not following this simple, but very effective suggestion to improve SOQL and SOSL query performance.

You can improve the performance of your code by filtering out null values in your SOQL and SOSL queries.

List<String> invNumList = {'001', '002', '003'};
List<Invoice_Statement__c> invStatList = [Select Id, invNumber from Invoice_Statement__c
                                          where invNumber in : invNumList
                                          and invNumber != null];

That extra check for nullability improves the performance because it avoids searching records that contain null values.

I hope these tips are useful to some of you! I plan to write more of these in the future. Let me know if you’ve come across other interesting Apex code gotchas in the comments.

Tagged , ,

Recipe to add AJAX, dynamic ratings in Salesforce using jQuery.


We all like to see our clients rejoice when we create great user experiences (UX) – JavaScript has helped us a lot in achieving this. By considering a scenario in Apex and Visualforce development, I’d like to show you how to add rating (1-5 scale) using jQuery with custom logic to save the relevant ratings in a separate object, and load it dynamically!

Utensils required

  1. Salesforce Environment.
  2. jQuery library.
  3. 2 icons to show the rating.

Ingredients

  1. One parent object (standard or custom, I am using “Account” object).
  2. One child custom object (I have created custom object called “Rating”).
  3. Two Apex Classes (one for the controller and another for test class).
  4. One Inline visualforce page.
  5. Two Static Resources

Demo: click here to taste! Continue reading

Tagged , , , , , , ,

Export to Excel functionality using the Wizard technique


Recently, we were working on a requirement wherein the client wanted an “Export to Excel” button on a Visualforce page which displays the data in a tabular format. Clicking this button enables them to store the tabular data locally as an excel file. Admittedly, there are several ways to implement this functionality. We will walkthrough an implementation technique that I like to call the “Wizard technique”.

Let’s create a sample Visualforce page(AccountDataTable.page) with a list of Account records displayed in a <apex:pageBlockTable> component.

<apex:page controller="AccountDataController" tabStyle="Account">

  <apex:pageBlock title="Account Data Table">

    <apex:pageBlockTable value="{!accounts}" var="account">
      <apex:column value="{!account.id}"/>
      <apex:column value="{!account.name}"/>
      <apex:column value="{!account.description}"/>
      <apex:column value="{!account.SLA__c}"/>
      <apex:column value="{!account.Active__c}"/>
    </apex:pageBlockTable>

  </apex:pageBlock>
</apex:page>

Related controller code(AccountDataController.cls)

public with sharing class AccountDataController {

  //constructor
  public AccountDataController() {
  }

  //list of accounts
  public List<Account> accounts {
    get {
      if(accounts != null) {
        return accounts;
      } else {
        accounts = [Select Id, name, Active__c, SLA__c, Description from Account limit 10];
        return accounts;
      }
    }
    set;
  }
}
Account Data Table

Account Table

Now, let’s create *another* Visualforce page with the contentType attribute set to “application/vnd.ms-excel#AccountTable.xls”. This Visualforce page is linked to the AccountDataController.cls controller that we have used in the AccountDataTable.page.


<apex:page controller="AccountDataController" contentType="application/vnd.ms-excel#AccountTable.xls" showHeader="false" standardStylesheets="false">

  <apex:pageBlock >
    <apex:dataTable value="{!accounts}" var="account">
      <apex:column value="{!account.id}"/>
      <apex:column value="{!account.name}"/>
      <apex:column value="{!account.description}"/>
      <apex:column value="{!account.SLA__c}"/>
      <apex:column value="{!account.Active__c}"/>
   </apex:dataTable>
 </apex:pageBlock>

</apex:page>

There are 2 things to note in this Visualforce page. First, I’m using <apex:dataTable> instead of <apex:pageBlockTable>. The reason being that the generated excel file includes some javascript code at the top along with the data. Replacing <apex:pageBlockTable> with the <apex:dataTable> resolved this issue(not sure why), and removed the javascript code from the excel file. Second thing to note is the showHeader and standardStyleSheets attribute in the <apex:page> component is set to false. The contentType attribute is responsible for transforming this page into an excel file.

We are now ready to add the “Export to Excel” button to the AccountData.page as follows:

<apex:page controller="AccountDataController" tabStyle="Account">

  <apex:form >
    <apex:pageBlock title="Account Data Table">
      <apex:pageBlockButtons >
        <apex:commandButton action="{! exportToExcel }" value="Export To Excel"/>
      </apex:pageBlockButtons>
      <apex:pageBlockTable value="{!accounts}" var="account">
        <apex:column value="{!account.id}"/>
        <apex:column value="{!account.name}"/>
        <apex:column value="{!account.description}"/>
        <apex:column value="{!account.SLA__c}"/>
        <apex:column value="{!account.Active__c}"/>
      </apex:pageBlockTable>

    </apex:pageBlock>
  </apex:form>
</apex:page>

Add the following method to the controller.

//export to excel - returns a page reference to the AccountDataExcel page
 public PageReference exportToExcel() {
   return Page.AccountDataExcel;
 }

Export To Excel button

And voila! When you click the button, your browser will download the data in an excel file. I call this method the Wizard technique because it mirrors the pattern(more than one Visualforce page linked to the same controller) used to create a wizard based form on the Force.com platform.

- @anup

Tagged , , ,
Follow

Get every new post delivered to your Inbox.

Join 49 other followers