Thursday, December 22, 2011

Org ID Automatically Replaced in Sandboxes

I discovered something that made my blood run cold today: The OrganizationInfo.isProduction method I was relying on in Apex to communicate to the correct web service endpoint was returning true in my sandbox orgs.

My OrganizationInfo class is super simple, created as suggested in a comment on the IdeaExchange (Determine sandbox name vs production from apex). Shown below for reference:

public class OrganizationInfo {
    
    /**
     * The Organization ID of the production org.
     */    
    private static final Id PRODUCTION_ID =
            '00DA0000000Kb9R';
    
    /**
     * Determine whether the current org is a
     * production org or a sandbox org,
     * based on whether the Org ID matches the
     * production App org's Org ID.
     *
     * @return Whether the org is Production
     */
    public static Boolean isProduction() {
        return UserInfo.getOrganizationId()
                == PRODUCTION_ID;
    }   // public static Boolean isProduction()
    
}   // public class OrganizationInfo

The obvious question: How does something so simple fail in a sandbox org?

The surprising answer: When a sandbox is created or refreshed, Salesforce automatically does a search and replace and replaces the production org ID with the sandbox org ID. Once a sandbox is created or refreshed, a single line of code changes in the above class:

    private static final Id PRODUCTION_ID =
            '00DZ000000056dv';

This tiny, almost unnoticeable change has been screwing everything up for a long time, and its discovery also explains why we would periodically get strange data in production and also strange responses in our sandboxes.

I wish I had known about this earlier, but who would've guessed? Anyhow, the fix that I've implemented (and confirmed by creating a new sandbox) is to split the ID into 3 parts when assigning it to the constant.

    private static final Id PRODUCTION_ID =
            '00DA0' + '00000' + '0Kb9R';

Amazing... the things one discovers in the worst possible ways...