Apex Method of the Day – JSON.serialize(Object)

Sometimes using JSON.serialize on a custom Apex type does not provide sufficient control over how the JSON is serialized. For example, serializing an Apex type will include null values for all fields that haven’t been set, when you might prefer to omit these properties from the JSON altogether. Or perhaps you need to use a property name in the JSON which is invalid for a class member name Apex. Fortunately JSON.serialize works on any Object, so you can serialize JSON from any structure you can assemble in Apex, for example:

String jsonString = JSON.serialize(new Map<String,Object> {
	'datetimevalue' => System.now(),
	'somelist' => new List<Object> {
		new Map<String,Object> {
			'name' => 'Mac',
			'os' => 'OS X 10.9'
		},
		new Map<String,Object> {
			'name' => 'PC',
			'os' => 'Windows'
		}
	}
});

JSON:

{
    "somelist": [
        {
            "name": "Mac",
            "os": "OS X 10.9"
        },
        {
            "name": "PC",
            "os": "Windows"
        }
    ],
    "datetimevalue": "2014-07-25T10:47:34.981Z"
}

Links:
Salesforce Stackexchange Question
JSON class

Posted in Documentation | Tagged , | Leave a comment

One controller to rule them all…

I recently wanted to create an extension controller for a custom object which I could use with both single records and a set of records. In other words, a list and detail controller extension, with actions that could be applied to one or many records.

I started out by creating my controller with two constructors, one which accepted a standard controller and a second that accepted a standard set controller so that it could be bound to Visualforce pages for either list or detail pages:

public with sharing class BumpControllerExtension {

	ApexPages.StandardSetController m_setController;
	ApexPages.StandardController m_controller;

	public BumpControllerExtension(ApexPages.StandardSetController controller) {
		m_setController = controller;
	}

	public BumpControllerExtension(ApexPages.StandardController controller) {
		m_controller = controller;
	}

	public ApexPages.PageReference myActionMethod() {

		// do some stuff...

		if(m_setController==null) {
			return m_controller.save();
		}
		else {
			return m_setController.save();
		}
	}
}

So far, so good. But before using any methods on either standard controller I need to check which controller has been assigned, which I think is a little messy, and also seems like hard work if the same method exists on both controllers – save() in this case.
Continue reading

Posted in Patterns | Tagged , , , | Leave a comment

IP Address Ranges when Logging in to Salesforce

Salesforce user security. Its great. As well as being one of the things customers value highly, its a massive advantage for application developers to be building upon a trusted platform with robust and well considered security features.

Restricting logins to specific IP addresses or ranges of addresses is a valuable user security feature, although it can be slightly confusing.

Salesforce help explains:

… Salesforce then checks whether the user’s profile has IP address restrictions. If IP address restrictions are defined for the user’s profile, any login from an undesignated IP address is denied, and any login from a specified IP address is allowed.

If profile-based IP address restrictions are not set, Salesforce checks whether the user is logging in from an IP address they have not used to access Salesforce before:

  • If the user’s login is from a browser that includes a Salesforce cookie, the login is allowed. The browser will have the Salesforce cookie if the user has previously used that browser to log in to Salesforce, and has not cleared the browser cookies.
  • If the user’s login is from an IP address in your organization’s trusted IP address list, the login is allowed.
  • If the user’s login is from neither a trusted IP address nor a browser with a Salesforce cookie, the login is blocked.

Whenever a login is blocked or returns an API login fault, Salesforce must verify the user’s identity:

For access via the user interface, the user is prompted to enter a token (also called a verification code) to confirm the user’s identity.

I have diagrammed the flow to (hopefully) make this a little easier to follow, focussing on a user logging in via a web browser (rather than API access):

IP_login_restriction_flow

A few points that I think are worth mentioning:

There are two places where an admin can specify IP addresses, or ranges of addresses for the login process. Whilst these look very similar, they purposes are distinct.

User Profile – Login IP Ranges

We can set up IP ranges (or individual addresses) on each user profile. When no IP address ranges are specified, the user’s profile does not restrict IP addresses in any way. However as soon as we specify any IP addresses as login IP ranges, then all other IP addresses become invalid for users with the profile and will result in access being denied.

Network Access – Trusted IP Ranges

In Security Settings, we can also set up trusted IP addresses for the entire org.

When a user logs in from an IP address they haven’t used to login to Salesforce, they will need to go through a verification process. This is where they are challenged and need to ask for a token to be sent to them, which they can use to gain access.

Trusted IP Ranges simply allow users to bypass the verification process when logging in from a trusted IP address.

Each trusted IP range is limited however, so 0.0.0.0 – 2.0.0.0 is acceptable, but 0.0.0.0 –  3.0.0.0 is not. Larger groups of trusted IP addresses would need to be specified my adding several ranges.

“Login IP Range” beats “Trusted IP Range”

From my flow diagram we can see that any profile login IP ranges are enforced before trusted IPs are considered. This means that “trusting” your IP address has no effect if your profile blocks it (by specifying some ranges, but not one that includes your address).

Engage Demo Mode

IP address restrictions and the verification process are generally a good thing. However, there may be times where the feature is unnecessary and perhaps frustrating – where you are giving demonstrations form a developer edition org of work in progress, or of new Salesforce features, for example.

In order to disable the verification process, we cannot add all IP addresses to a single Trusted IP Range, as the size of the range is limited. We could add many ranges, e.g. 0.0.0.0 – 0.255.255.255, 1.0.0.0 – 1.255.255.255, 2.0.0.0 – 2.255.255.255, etc.

However, there is no limit in size for to a Login IP Range, so you could specify all IP addresses: 0.0.0.0 – 255.255.255.255. In a demo org you may have have one, or at worst a handful of profiles that you will be using, so it would be easy to add an all-IP-addresses Login IP Range to each profile.

This will prevent login challenges and verification in the middle of a demo, but is not good practice in production.

 

 

Posted in Documentation | Tagged , | Leave a comment

Apex Method of the Day – String.format(String value, List<String> args)

String value = 'This message has {0} and {1}', f = 'foo', b = 'bar';
String message = String.format(value, new List<String>{f,b});
System.assertEquals('This message has foo and bar',message);

The above is an example of simple token replacement and is equivalent to:

String f = 'foo', b = 'bar';
String message = 'This message has ' + f + ' and ' + b;
System.assertEquals('This message has foo and bar',message);

Why bother? Well, for more complex strings use of String.format can be easier to write and maintain than concatenation, but a great benefit comes from its combination with Custom Labels. Messages with tokens can be stored as Custom Labels and merged with values at run-time. Custom Labels are translatable, and as different languages may use different word order, String.format becomes the sensible choice.

String.format works in a similar way to the Visualforce apex:outputText component, and the value being formatted uses the same syntax as the MessageFormat class in Java.

If you read the Java documentation you will find that single quotes have a special meaning in format strings. By enclosing text in single quotes, any special meaning of the enclosed text is ignored. For example, braces { } were used in the above example to create tokens to be replaced with values from the args parameter. You will therefore need to use single quotes if you want to include braces in your formatted text:

String value = 'Braces \'{ we want braces }\' and substitution of {0} and {1}', f = 'foo', b = 'bar';
String message = String.format(value, new List<String>{f,b});
System.assertEquals('Braces { we want braces } and substitution of foo and bar',message);

Of course Apex uses single quotes to enclose literal strings, so we have to use backslashes in order to embed single quotes in our string text.

But if single quotes have a special meaning in a format string, how can we include a single quote in our formatted text? Here’s a typical scenario:

String value = 'I do not recognise the term \'{0}\'', term = 'foo';
String message = String.format(value, new List<String>{term});
System.assertEquals('I do not recognise the term \'foo\'',message);

This doesn’t work as intended:

Assertion Failed: 
Expected: I do not recognise the term 'foo', 
Actual: I do not recognise the term {0}

Our substitution hasn’t been done.

From the Java documentation we find that we need two consecutive single quotes to be interpreted as a literal single quote:

String value = 'I do not recognise the term \'\'{0}\'\'', term = 'foo';
String message = String.format(value, new List<String>{term});
System.assertEquals('I do not recognise the term \'foo\'',message);

Links:
Apex String Methods
Visualforce apex:outputText
Java MessageFormat class

Posted in Documentation | Tagged , | Leave a comment

Constructive Forces at Work

A constructor in Apex is called when an instance of a class is created. Code-wise constructors might look like member methods, but they differ in a couple of significant ways.

First, constructors can’t be called any other time than when creating an instance of a class, and second, constructors do not return values. Ever had the build error “Invalid constructor name: foo“? We soon learn that this actually means “Doh! You forgot to provide a return type for your method”.

This does mean, as it does in Java, that Apex constructors are not members that can be inherited:

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

So, a subclass constructor can call a constructor of its superclass. Actually, constructors call superclass constructors automatically in Apex if we don’t do it explicitly. Try running this anonymous code block:

public class ClassOne {
    ClassOne() {
        system.debug('1');
    }
}
public class ClassTwo extends ClassOne {
    ClassTwo() {
        system.debug('2');
    }
}
public class ClassThree extends ClassTwo {
    ClassThree() {
        system.debug('3');
    }
}
ClassThree c = new ClassThree();

Note that class definitions in anonymous blocks are virtual by default, so we don’t need to supply the virtual modifier here.

And here’s a part of my debug log:

19:19:35.059 (59838092)|SYSTEM_CONSTRUCTOR_ENTRY|[16]|<init>()
19:19:35.059 (59944318)|SYSTEM_CONSTRUCTOR_ENTRY|[12]|<init>()
19:19:35.060 (60019420)|SYSTEM_CONSTRUCTOR_ENTRY|[7]|<init>()
19:19:35.062 (62725333)|USER_DEBUG|[3]|DEBUG|1
19:19:35.062 (62740937)|SYSTEM_CONSTRUCTOR_EXIT|[7]|<init>()
19:19:35.062 (62772600)|USER_DEBUG|[8]|DEBUG|2
19:19:35.062 (62780817)|SYSTEM_CONSTRUCTOR_EXIT|[12]|<init>()
19:19:35.062 (62807978)|USER_DEBUG|[13]|DEBUG|3
19:19:35.062 (62816118)|SYSTEM_CONSTRUCTOR_EXIT|[16]|<init>()

We have defined three classes where the second extends the first and the third extends the second. In each case we have defined a constructor, for debugging the order of execution, but we haven’t explicitly called a superclass constructor.

We find that each constructor implicitly invokes the superclass constructor before executing its own body. This works recursively until there are no more superclasses, so that the constructor method bodies are executed in order going down the inheritance chain from most-super-class to the actual class we are constructing.

We can influence the chaining behaviour to some degree by calling specific constructors with this and super.

If we have a class with several constructors, each with different arguments, we can delegate from one constructor to another of the same class using this(…), or select a particular constructor of a superclass using super(…):

public class ClassOne {
    ClassOne() {
        system.debug('1');
    }
}
public class ClassTwo extends ClassOne {
    ClassTwo() {
        system.debug('2');
    }
    ClassTwo(String value) {
        this();
        system.debug('2 ' + value);
    }
}
public class ClassThree extends ClassTwo {
    ClassThree() {
        system.debug('3');
    }
    ClassThree(String value) {
        super(value);
        system.debug('3 ' + value);
    }
}
ClassThree c = new ClassThree('foo');
19:39:29.054 (54167458)|SYSTEM_CONSTRUCTOR_ENTRY|[24]|<init>(String)
19:39:29.054 (54305037)|SYSTEM_CONSTRUCTOR_ENTRY|[20]|<init>(String)
19:39:29.054 (54384541)|SYSTEM_CONSTRUCTOR_ENTRY|[11]|<init>()
19:39:29.054 (54460886)|SYSTEM_CONSTRUCTOR_ENTRY|[7]|<init>()
19:39:29.057 (57619207)|USER_DEBUG|[3]|DEBUG|1
19:39:29.057 (57636883)|SYSTEM_CONSTRUCTOR_EXIT|[7]|<init>()
19:39:29.057 (57673115)|USER_DEBUG|[8]|DEBUG|2
19:39:29.057 (57684149)|SYSTEM_CONSTRUCTOR_EXIT|[11]|<init>()
19:39:29.057 (57743445)|USER_DEBUG|[12]|DEBUG|2 foo
19:39:29.057 (57766853)|SYSTEM_CONSTRUCTOR_EXIT|[20]|<init>(String)
19:39:29.057 (57829601)|USER_DEBUG|[21]|DEBUG|3 foo
19:39:29.057 (57848548)|SYSTEM_CONSTRUCTOR_EXIT|[24]|<init>(String)

It is important to note that in order to preserve the order of execution of the chain of constructors, super or this must be the first line of the body of a constructor.

Constructors however are optional, and so to preserve the constructor chain, the compiler will provide a default zero-argument constructor for us just as long as we don’t provide any constructors ourselves:

If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments. If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. You must create your own.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_constructors.htm

Which also means of course that if you do create a constructor in an abstract/virtual class that takes argument(s), you must then also provide a zero-argument constructor in order to extend the class, even if you don’t need one (it has an empty body). If you don’t then you will get a build error when you extend the class:

Parent class has no 0-argument constructor for implicit construction

Links

http://salesforce.stackexchange.com/questions/24275/inheriting-non-implicit-constructors-on-apex-classes

Force.com Apex Code Developer’s Guide – Using Constructors

Posted in Documentation | Tagged | Leave a comment

Dynamic Field Sets

One of the things I love about Force.com is how easy it can be to stitch together blocks of functionality provided in the platform, saving you development effort. Spending a little extra time working out how to best use platform features can also save effort downstream – when you align yourself with the platform you can usually benefit from enhancements and additional functionality very quickly as it is added by Salesforce.

I was recently asked whether we could assign Field Sets for Visualforce pages to a user’s profile (without using Field Level Security to limit access to the fields entirely). Although this is not out-of-the-box functionality, I felt sure that this should be possible with a little effort by stitching together Field Sets and Hierarchical Custom Settings.

Continue reading

Posted in Tutorials | Tagged , , , | 1 Comment

Back from the Dream side of the Force

Just back from Dreamforce ’13, which was, what’s Marc’s word for it?… oh, yes… awesome.

As per my last post, I had two sessions in the DevZone this year: Practical Introduction to Chatter Publisher Actions (with Carolina Ruiz @CarolEnLaNube), and Tests and Testability: Apex Structure and Strategy

The slides for these sessions are available to download as PDF:

DF13TestsAndTestability

DF13ChatterPublisherActionsAndSalesforce1

The session recordings are also now available:

Tests and Testability – youtube

Chatter Publisher Actions and Salesforce1 – youtube

I am planning a number of posts on Tests and Testability, in which I will reuse and expand on the DF13 material.

Posted in News | Tagged | 4 Comments