Recently, I discovered a feature of Salesforce that I’d somehow missed — Named Credentials. When I ‘discovered’ them this week it was quite a lightbulb moment. They are conceptually simple, but that simplicity hides their power.

What is a Named Credential?

At an object level, you can think of them as a combination of Remote Site Settings and, well, credentials. These credentials can be as simple as username/password. But you can also use oAuth2. This facilitates creating Named Credentials based oAuth2 authentication between your org and external systems. It’s easy to overlook, so I want to draw your attention to this: Because Salesforce has an oAuth2 authentication option, Named Credentials enable authentication to a second Salesforce Org!
There are a few other features of the declarative side of Named Credentials. For instance, you can use custom HTTP Certificates. Strong Encryption for the win! Additionally, you can enable the use of merge fields in the http header and body. 

What do you do with a Named Credential?

Good question, glad you asked! What good is a declarative URL, and Credential object? It’s not as if we have declarative tools for making callouts. Or do we? As with most declaratively created objects, Named Credentials have a ‘name’ property. We can use that name property to dramatically simplify our Apex callout code. Specifying a Named Credential by it’s name when setting a http callout’s endpoint causes the callout to use the Named Credential’s URL and Authentication. That means we can go from this:
HttpRequest req = new HttpRequest();
req.setEndpoint('https://www.codefriar.com/bestBlogPostEver');
req.setMethod('GET');
String username = 'DoYouEvenSecurity?';
String password = 'DontHardcodeCredentials';
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
to this:
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:codefriar/bestBlogPostEver');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
view raw gistfile1.txt hosted with ❤ by GitHub

Why should I use a Named Credential?

Wait, those are essentially identical! On the face of it, the code changes are minimal enough that you may be wondering why you should switch? There are at least two good reasons to start using Named Credentials. First, our code samples here are vague, and generic, to better illustrate whats going on without getting bogged down in details. That said, you know not to hardcode usernames and passwords. If you’ve got usernames and passwords hardcoded, you have bigger issues. Our sample code is simply missing all the security best practices. There is no querying for encrypted credentials. Most importantly, there’s no code to Authenticate with oAuth. Simply put, our example code ignores the complexity found in real production callouts. With all that in mind, the first reason you should use Named credentials is simple. It offloads the storage of credentials and authentication to a declaratively controlled process.
This leads us to the second reason. A simple change set deployment with a few components takes at least 20 minutes to prepare and upload. Add test and deployment time… well lets just say any hard coded credentials or URL’s become very tedious to change. Remember, credentials aren’t the only thing you may have to change. Unless you’ve made the URL queryable, you’ll likely have to deploy to change it. With Named Credentials, you can update without deploying. Furthermore, updating the Named Credential updates all callouts using it! As a bonus, if you’re using oAuth 2 with your named credential, and your oAuth provider returns a refresh token, that Named Credential will continue to work until the refresh token is revoked — even if you have changed the password.(more on this later)

Give me an example!

Here’s the scenario. You’re the Salesforce lead for a large enterprise named, Acme Corp. In a meeting earlier today, you learned Acme has purchased Beta Corp. Beta Corp’s Salesforce team will continue to run their org. Acme’s leadership, however, wants to surface some of Beta’s data in Acme’s org. Here’s where Named Credentials come into play. Using a Named credential allows you to write Apex code to make API calls into Beta’s Org. Here’s the follow-the-bouncing-ball steps to make this work.
  1. Create a connected app with oAuth, and set the default scope to ‘refresh_token full‘. As you become more familiar with how these work, you may want to adjust that default scope. You’ll need to specify a callback URL. For now, put in “https://login.salesforce.com.” We’ll be editing this here in a bit.
  2. Create an Auth Provider. (Setup -> Security Controls -> Auth Providers). When prompted, choose ‘Salesforce’ as the provider type. Give it a name, etc. and populate the oAuth consumer key and secret from step 1. Leave the rest of the details blank — this will use Salesforce Defaults. Once you’ve clicked save, you’ll see at the bottom of the page a callback URL. Copy that URL.
  3. Go back to your connected app, and edit it. Paste your callback URL from step 2 into the Callback URL field.
  4. Create your Named Credential. For identity type, select Named Principle. Note: You may want to use per-user, but that’s an exercise for the reader. For the Authentication Protocol, select ‘oAuth 2.0’. After selecting oAuth as the authentication protocol, a new field will appear. Populate the authentication provider field with the Authentication Provider created in step 2. When you’re connecting two salesforce orgs, you need to make sure that your Named Credential URL uses Instance URL. I.E.: https://na35.salesforce.com, or the full url your my-domain. I.E.: https://awesomesauce.my.salesforce.com
  5. Write Apex code to use the named credential. (see above)
  6. … Profit?what it should look like when you're ready to authenticate

Where do I do this?

For our Acme corp. use case, all four steps above would happen in the Acme Corp. Let me repeat that. All four steps above would happen in the Acme Corp org. When you save the Named Credential (step 3 above) your taken to a standard Salesforce login screen. This is the only bit that involves the other org at all. You’ll need a login to Beta corp’s org here. Note: Your Beta corp login defines the data visibility of your Named Credential.

We bought Gamma Corp!

Congrats on your company’s success! Guess what! You don’t need to redo all these steps to pull in Gamma Corp’s data. All you’ll need to do is create a new Named Credential pointing at Gamma Corp’s org. You’re able to re-use the connected app and Auth Provider.

Maintaining Named Credentials

My company has strict password policies that force you to change them every so often. Acme corp has the same type of policy. Thankfully, Named Credentials using oAuth / Salesforce Auth Provider rely on refresh tokens. These tokens are valid until revoked. This means, even if your password changes, the integration will continue to work. (Until you revoke the refresh token). This makes Named Credentials using oAuth 2 largely maintenance free! Like I said, Use you some Named Credentials for great good!
 
 
 
 
 

The Problem

A few weeks ago my wife, a Salesforce admin, asked me if it was possible to create a related list that filtered out inactive contacts. I explained that it’s entirely possible to do something similar, but only with Apex and Visualforce. It got me to thinking that it’s possible to write code that, well, writes the code needed to build related lists with filters. A few weeks later, I’m releasing Custom Related Lists.

No coding required.

Custom Related Lists is an unmanaged package that enables Declarative Developers and Admins to create related list Visualforce pages. You can embed these Visualforce pages on standard and custom detail page layouts using the page layout editor. They mimic the functionality of native related lists with a few additions. With Custom Related Lists, users can select and create criteria to filter records displayed in the list. Now users can create a related list of Contacts on the Account detail page that filter out inactive contacts, or contacts of a given record type. Additionally, Custom Related Lists is not bound to the 10 field limit. Custom Related Lists is capable of displaying all the fields of a child object in the list, but users should be mindful of the user experience implications that carries with it.

How it works.

This is the technical bit, and if you’re just interested in using Custom Related Lists, you might want to skip this section. Fundamentally, Custom Related Lists (CRL) (ab)uses Visualforce as a template system to abstract out the boilerplate bits of Apex and Visualforce. It consists of three Visualforce template files:

  • CRL_MetaGenCtrl – the Controller template
  • CRL_MetaGenPage – Visualforce page template
  • CRL_MetaGenTests – Apex tests for the controller

Each of these files uses the CRL_MetaGeneratorCtrl controller, which is responsible for providing the non-boilerplate bits of code. The new Related_List__c record page has been overridden to give a nice Visualforce wizard. The user selects the “master” object whose detail pages this list will display, and the “detail” object whose records will be displayed on the list. Once selected, the user can select the fields to display, as well as defining criteria filters. The wizard is intentionally dynamic; selecting the “master” object automatically determines which objects relate to it and populates the detail selection list with related objects. Once the user has specified the details, the page controller first saves the record, and generates the controller, test, and Visualforce pages needed. Generated from the templates I mentioned above, using a little-known pageReference method – getContents(). getContents renders the given Visualforce page into a string as if it were requested by a browser. This allows us to use Visualforce as a templating system. Tied to a custom controller, the templates mentioned above are rendered in Apex through getContents(), and result in Apex code with the user-selected options merged in. For example, to be included on a detail page, the Visualforce page that displays the list must extend the standard controller of the selected object. The controller has a method to generate the startPageTag which is simply written to the final Visualforce page with standard merge syntax: {!startPageTag}

Putting it in place

After the custom controller extension, test, and Visualforce page are rendered to strings, the application puts the code in place. Apex code is placed with the Tooling API and the Visualforce page in place with a standard Rest call. (I have no idea, why Visualforce can be created with a rest call, but we need the Tooling API for Apex.) I want to give a shout out to Andrew Fawcett and James Loghry for their excellent Tooling API Apex library. (Please note, that the version of the library packages with Custom Related Lists is truncated to include only enough of it to insert Apex classes.) Because of how Custom Related Lists uses the Tooling API. It’s important to note that generating the code will work in Sandboxes and Developer orgs, but is not supported in Production orgs as these require full test runs for deployment. The tooling API requires a custom remote site setting to function. This is automatically generated using the Javascript metadata API wrapper JSForce whenever you load the app. If autogeneration of the remote site setting fails for some reason, users are given instructions on creating it.

Dynamicity and Data Portability

Custom Related Lists is designed to be run for creation in a Sandbox, and to use in a Production environment. However, it’s also designed to be highly dynamic. It would be a pain to re-generate the code and change set every time we wanted to adjust what fields are displayed. To prevent that need, the generated code references a Custom Related List object record on page load. This allows admins to change the criteria and fields displayed without having to re-generate the code and deploy it. However, this also means that users would have to re-create the record in the Production org. To prevent this need, the generated code contains a JSON encoded version of the initial Related_Lists__c record. After deployment to Production, on the first display of the related list, the code will de-serialize the JSON and create the needed record. It is highly recommend that you leave sharing settings for Related_List__c records as public read.

Using Custom Related Lists

Installing Custom Related lists is slighting more complex than a standard package as it must be installed in both your Production and Sandbox orgs. Once you’ve installed it in both orgs using these links…

Once installed, the process is straightforward. First, open the Custom Related Lists app from the app selection menu.app selection This will load the apps info page which will attempt to securely create a remote site setting on your behalf. If you’re an administrator of the org, this should succeed, and you’ll see a green success menu like this.remote site setting success

 

If it fails, follow the instructions to manually create the needed remote site setting. Once your remote site setting is settled, you can navigate to the Custom Related List tab. crl tabThis is a standard list view for your Custom Related Lists objects.

This is a standard list view for your Custom Related Lists objects. To facilitate ease of use, I’ve overwritten the New button to utilize a custom Visualforce page that looks like this:

wizzard

Lets go through each of the input fields here and talk about what they do.

  1. Step 1: The name you provide here in Step 1 is used as the name of your Visualforce page that you’ll end up placing on a page layout. It’s good to be descriptive, but you only have 40 characters, so a good example would be something like “Active Contacts for this Account.” Short but descriptive.
  2. Step 2: This is where the fun starts. Whatever object you choose here determines everything else available to you. You want to choose the object on whose detail page layout you want to display this list. If you want to display, for instance, Active Contacts on this Account, you’d choose Account here. Custom Related Lists determines the options available to you in Step 3.
  3. Step 3: Choose the relationship you want to display. In the background, it asks the system to describe all objects that are related to your choice in Step 2, and shows you the Labels for those relationships. If you have a situation where you have multiple relationships, say a Master/Detail relationship and a Lookup relationship to the same object you must pay careful attention to choose the one you’re looking for. As an Administrator or Developer, you need to ensure you’re naming your relationships such that you can distinguish them! In our example of active contacts on this account, we’d choose Contact in Step 3.
  4. Step 4: Once you’ve selected the relationship to display, the app will load all of the relevant fields that are available for display. You can select fields on the left hand side and move them to the right, which will select them for display in your list. While standard related lists are limited to 10 fields, custom related lists are not.
  5. Step 5 is probably the most powerful and crucial step here. Unfortunately,itcan be the most confusing. Let’s start with some terminology.Criteria are the options you’re setting to filter which recordswill be displayed in your list. Constraintsare made up of a selected field, an ‘operand’ which defines the comparison method used, a Value field where you specify the valueto be compared, and afinalpicklist that lets youdetermine if this criteriashould be evaluated with AND or OR.If you’ve ever created a custom list view, thisshould be familiar. The wizard starts you off with a single criteria line, but you can add more by clicking on the Add New Constraint button. In our example of Active Contacts on Account you might select “Active” for the field name, set the operandpicklist to ‘=’ and set the value to ‘true’ (note, no quotesare needed). This would filter your list’s contents so that it only displays Contacts whose Active__c field is equal to true. Other operands available to you include ‘!=’ or not equal, as well as <, >, <= and >= or greater than, less than, less than or equal to, and greater or equal torespectively. Some example criteria to get your imagination going:
    1. RecordTypeId, =, your RecordTypeId here — would result in a related list only displaying related records of a selected record type.
    2. Email, !=, null -- Null is a special word, and in this case allows you to filter your list to exclude contacts with no email listed.
    3. CreatedDate, >=, 2005-06-15 — show only records thatwere created after June 15th, 2005.Note that you can use any of the APEX Date Literals for the value, and that you are responsible for providing the proper date format string! See here for more details!
    4. I mentioned before that you could create multiple criteria lines by clicking the Add New Constraint button. How those constraints are interpreted in relation to one another is dependent on your selection of AND or OR. For instance, you could use AND to ensure that both: RecordTypeID = your RecordTypeId, as well as lastModifiedDate >= LAST_90_DAYS criteria are met, ensuring that your list would only display records with the matching Record Type Id that were also modified in the last 90 days. If you select OR for those constraints, records with the selected Record Type Id OR who were modified in the last 90 days would be displayed.
    5. It is important to note here that you MUST have at least one constraint for Custom Related Lists to properly work. If you do not have criteria to add, use a standard related list.
  6. After clicking the Create New Custom Related List button and the page reloads, you’ll see the Generate Controller and Page button. Once you click the button, Custom Related Lists will generate the controller, the test class, and the Visualforce page.
  7. At this point, you’ve got everything you need, but only in your Sandbox org. There are three files you’ll need to include in your change set, and their filenames are listed on the final page. Deploy your change set, and then edit your page layout to include your Visualforce page and you’re set!

Important Considerations and Caveats.

This package makes several assumptions, and while they’re valid in the vast majority of cases, they’re not always going to work. While the package works hard to ensure that the fields listed for inclusion in the related list are queryable and available for use, not all of them actually are. For instance, say you’re creating a related list of notes to a given Account. The system will report that “Name” is available, but upon running it… not so much. Let’s call it a platform quirk. The good news is that most of the fields I’ve found that are affected by such quirks are not the kind of fields you’d typically want to put in such a list. The really good news, is that the related lists are fully dynamic. When the page loads, it pulls its configuration details from the Related_List__C object. If you run into an issue with a field not being available you can edit the fields on the object and reload. No code regeneration needed.

I hope y’all find this as useful, as I had a ton of fun building it. In the future I want to fix the edit screen to use the same wizard, and capture as many edge cases as possible. In the meantime, you can find the code on Github, and I’ll gladly accept pull requests and issues for feature requests. If Custom Related Lists makes it into your org, and saves you time and energy, feel free to hit that tip button on the left.

A while back I stumbled across a situation where I needed to do a visualforce mail merge, but I didn’t want to send the email. Unfortunately, there’s no built in way to do that. Salesforce’s Visualforce merge code doesn’t give you a “getter” for the merge result. Instead, the normal workflow looks like this.

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[]{'theDoctor@who.com'};
    mail.setToAddresses(toAddresses);
    mail.setUseSignature(this.useSig);
    mail.setSaveAsActivity(this.saveActivity);
    mail.setSenderDisplayName(this.senderDisplayName);
    mail.setTargetObjectId(targetObjectId);
    mail.setTemplateId(templateId);
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

In fact, there’s not even a .merge() method exposed in Apex. The merging happens as part of Messaging.sendEmail();

However, after some research I discovered that PJC over on Stackexchange had figured out that a DB savepoint could be (ab)used to grab the template contents after merging. This is Neat(c).

Fast forward a few months, (LifeWithRyan)[http://www.sudovi.com/] and I are talking on IRC about this same problem. We agreed to both blog our solutions. His is here: (When an Email Template just isn’t enough)[http://www.sudovi.com/when-an-email-template-just-isnt-enough/] I decided to wrap the method I found up in a reusable class: MailUtils.cls. Mailutils offers a single static method. getMergedTemplateForObjectWithoutSending(Id targetObjectId, Id templateId, Boolean useSig, Boolean saveActivity, String senderDisplayName) That takes the work out of this. It returns a Map, with the following keys:
textBody: Merged text body
htmlBody: Merged html version
subject: Subject line of the email

Here’s MailUtils.cls in its full ‘glory’:

public class mailUtils {
  public class mailUtilsException extends exception {}

  public Boolean useSig {get; private set;}
  public Boolean saveActivity {get; private set;}
  public String senderDisplayName {get; private set;}

  public mailUtils(Boolean useSig, Boolean saveActivity, String senderDisplayName){
    this.useSig = usesig;
    this.saveActivity = saveActivity;
    this.senderDisplayName = senderDisplayName;
  }

  // Derived from: 
  // http://salesforce.stackexchange.com/questions/13/using-apex-to-assemble-html-letterhead-emails/8745#8745
  public Messaging.SingleEmailMessage MergeTemplateWithoutSending(Id targetObjectId, Id templateId) {
    Messaging.reserveSingleEmailCapacity(1);
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    // Intentionally set a bogus email address.
    String[] toAddresses = new String[]{'invalid@emailaddr.es'};
    mail.setToAddresses(toAddresses);
    mail.setUseSignature(this.useSig);
    mail.setSaveAsActivity(this.saveActivity);
    mail.setSenderDisplayName(this.senderDisplayName);
    mail.setTargetObjectId(targetObjectId);
    mail.setTemplateId(templateId);

    // create a save point
    Savepoint sp = Database.setSavepoint();
    // Force the merge of the template.
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    // Force a rollback, and cancel mail send.
    Database.rollback(sp);

    // Return the mail object
    // You can access the merged template, subject, etc. via:
    // String mailTextBody = mail.getPlainTextBody();
    // String mailHtmlBody = mail.getHTMLBody();
    // String mailSubject = mail.getSubject();
    return mail;

  }

  public static Map<String,String> getMergedTemplateForObjectWithoutSending(Id targetObjectId, Id templateId, Boolean useSig, Boolean saveActivity, String senderDisplayName) {
    Map<String,String> returnValue = new Map<String,String>();
    mailUtils mu = new mailUtils(useSig, saveActivity, senderDisplayName);
    Messaging.SingleEmailMessage mail = mu.MergeTemplateWithoutSending(targetObjectId, templateId);
    returnValue.put('textBody', mail.getPlainTextBody());
    returnValue.put('htmlBody', mail.getHTMLBody());
    returnValue.put('subject', mail.getSubject());
    return returnValue;
  }

}