Friday, November 27, 2015

Rejecting the Salesforce CKEditor and substituting your own.

My biggest pain point with the Salesforce developer forums is the CKEditor. In particular, how it interferes with the browsers native spell checker. My spelling skills aren't always the best, but are good enough when propped up by the red squiggles. The problem is compounded by not being able to edit existing posts. Your spelling mistakes can now haunt you forever unless you are willing to delete a post.

There is also the general problem with WYSIWYG editors in that the underlying formatting can get unwieldy. Copying and pasting content from multiple sources is a quagmire of mismatched HTML. It's what you can't see that is important to the formatting.

Also, good luck to you if you've written an answer that is a contender for a Nobel Prize in Literature only to lose it all due to an expired session. Maybe you'll get lucky and can browse back to recover it. More likely it is lost forever and you'll just knock out a one or two line reply instead. Now devoid of formatting, images and hyperlinks. Because why bother doing it all again?

Status Quo

Right now I've got a few techniques for dealing with the CKEditor used in the success forum.

  • Write everything somewhere else where a spellchecker is available and then copy and paste it over at the last minute. Adding in any links, images, and formatting just before submission.
  • Use the browsers developer tools to manipulate the HTML source that the CKEditor is working from.
  • Before submitting an answer, copy the content out just in case there is a session issue and the form doesn't submit correctly. You'll likely lose formatting, links, etc..., but you'll keep your prose.

The Hackening

I did a little spelunking into the page source and network traffic. You can see that the CKEditor is currently configured with a request to, It's this config that toggles various functions in the editor.

Of particular interest here is the a.toolbar_ServiceCommunity array. This configures the toolbar buttons that are available.

    a.toolbar_ServiceCommunity = [
        ["Undo", "Redo"],
        ["Bold", "Italic", "Underline",
        ["Link", "sfdcImage", "sfdcCodeBlock"],
        ["JustifyLeft", "JustifyCenter", "JustifyRight"],
        ["BulletedList", "NumberedList", "Indent", "Outdent"]

Now that we know how the CKEditor is being configured we can start hacking at it. Lets see if we can get the native source view going.

Injecting your own configuration

This option is perhaps a bit heavy handed. The basic idea is to use a custom Chrome extension to intercept the HTTP requests to and redirect the browser to config content that I control.

Parts of the extension


Configures capturing web requests from


Listens for requests to and redirects them to the static resource config.

See chrome.webRequest


The replacement for the standard Salesforce config.

The main problem with redirecting the browser to pull content alternative content is that it won't easily accept something from another domain.

This can be overcome by hosting the replacement configuration as a static resource in an org of your choosing. I used by developer edition org, as I often have an active session there.

Load the config.js Javascript into an Org of your choice as a static resource. I'd encourage you to modify your own version rather that taking the version I've got here. Who knows what sort of evil Javascript could be hidden away in there. Better to modify something you have full control over.

The Result

With the extension loaded into Chrome as an active unpacked chrome://extensions it will switch out the CKEditor config to the one I control.

I can now jump natively into the HTML source that CKEditor is working from. The built in Chrome spell checked comes back to like, and I can edit things like blockquotes into the source.

The Future

I mostly post to the various StackExchange sites where they have a well tuned markdown editor. There is a Markdown plugin for CKEditor, it would be great to integrate this.

The Chrome extension is probably a bit heavy handed, it should be possible to run Javascript directly in the page once the CKEditor is loaded to reconfigure it on the fly. Maybe with something as simple as a bookmarklet. See Change CKEditor toolbar dynamically

There are indications that you can reenable the native browser spell checker using config.disableNativeSpellChecker = false;. I couldn't get this to work.

See Also:

Wednesday, October 21, 2015

Salesforce Debug logs with the Winter '16 Developer Console

I'm in the process of updating the FuseIT SFDC Explorer to use the Winter '16 (v35.0) APIs. One of the first things I've encountered are a number of changes with how debug logging works. These are somewhat documented in the Release Notes on Debugging.

In terms of actually integrating with Salesforce at the API level, TraceFlag no longer has a scopeId field to optionally represent the user being debugged. Instead it has a logType and DebugLevelId field. It's the latter that is particularly interesting.

Say you have two developers working in an Org. Ideally they would both be developing in separate orgs and then migrating changes into a common org, so let's say they are testing the integration of their changes.

  • Developer A starts the Developer Console.
  • A DebugLevel is created for Dev A with the DeveloperName 'SFDC_DevConsole'. Lets call it 7dl70000000000A, or DLA for short.
  • A TraceFlag is created for Dev A that references DLA. The TracedEntityId is the Developer A's User Id.
  • Developer B starts the Developer Console in the same org in their own session
  • You can't have two DebugLevel records with the same DeveloperName, so the Developer Console uses the existing DLA record. (See where I'm going with this?)
  • A TraceFlag is created for Dev B that references DLA. The TracedEntityId is Developer B's User Id.

So, what have we got? Both developers will see their logs in the Developer Console. However, they are sharing the same DebugLevel definition by default!

If either developer makes changes to the common SFDC_DevConsole debug levels it will affect the other developers logging for any future logs. If one developer deletes/removes the common DebugLevel it will cascade delete any associated TraceFlags. Hours of fun!

What can you do about this? You can add new DebugLevel records via the developer console. The one you have selected when you press Done will be sent back to the TraceFlag.

Thursday, October 8, 2015

Salesforce code quality test cases for Apex via static code analysis

Lets assume for a moment that your code coverage isn't a perfect 100% and there are some areas of your Apex that aren't exercised as part of the automated deployment test cases. If your suspension of disbelief goes that far, lets also assume that sometimes you add temporary code to aid in debugging those murky places. Something like:

System.assert(false, 'TEMP this assertion was only for debugging and will stop the execution so you can check the debug log etc...');

The general idea is that you can use this assertion to halt execution during manual testing. At which point it would be easy to inspect the debug log state or write out some useful state information in the assertion message. It's certainly not the most advanced debugging technique, but it is effective.

The main problem with the approach is what happens if you forget to take out that line. And then package the code base for deployment. Don't do that. It's not a good look.

Remember, the line in question may or may not be covered by the existing test cases. If it isn't it will sail right into the production managed package and then spring out and surprise a user at the most inopportune moment.

What if you could stop the package from proceeding based on the content of the Apex classes?

We need the poor man's static code analysis tool! And we need it to run as part of the packaging process.

Luckily, we already have Apex test cases that run as part of the packaging process. And we have the ApexClass sObject exposed to Apex which includes the Body of the classes within the current namespace. We just need some apex code that will scan through the Body of the apex classes and assert that they don't contain the problem string. Then add said test class to the package components. Something like:

private class SampleCodeQualityTests {
 @isTest static void ensureThereAreNoTempAssertions() {
  string searchFor = '\'TEMP';

                // Exclude this class from the check. May also need to exclude based on namespace
  for(ApexClass ac : [Select Id, Name, Body From ApexClass where Name != 'SampleCodeQualityTests']) {
   integer index = ac.Body.indexOf(searchFor);
   if(index == -1) { continue; }

   integer lineNumber = lineNumberForIndex(ac.Body, index);
   string problemLine = extractLineByIndex(ac.body, index);
   System.assertEquals(-1, index, 'Apex class ' + ac.Name + '(' + ac.Id + ') contains the text ' + searchFor + ' at index ' + index + ' lineNumber:' + lineNumber + 
    '\n' + problemLine);
   //System.assert(!ac.Body.contains(searchFor), 'Apex class ' + ac.Name + '(' + ac.Id + ') contains the text ' + searchFor);

 private static integer lineNumberForIndex(string body, integer targetIndex) {
  integer lineNumber = body.substring(0, targetIndex).countMatches('\n') + 1;
  return lineNumber;

 private static string extractLineByIndex(string body, integer targetIndex) {
  integer startOfLine = body.lastIndexOf('\n', targetIndex);
  integer endOfLine = body.indexOf('\n', targetIndex);

  string lineOfInterest = body.substring(startOfLine + 1, endOfLine);
  return lineOfInterest;

Think of this more as a proof of concept. There are some obvious problems with it. For example, it isn't really parsing the Apex body. Just doing a dumb string search for a string that starts with TEMP. No consideration is being made for the context. It might be in comment. There are likely other issues around new line detection as well.

Still, it demonstrates the idea. Using Apex test cases to do static code analysis as part of the packaging and deployment steps.

Now if we could get to the SymbolTable in a testing context (i.e. no callout) there could be all sorts of interesting checks1:

  • Does each test method make at least one assertion?
  • Does each assertion include a message to the user?
  • Excessive lines of code in one Apex Class
  • Using System.debug statements - too many of these can be detrimental to performance.
  • Empty exception handling catch blocks
  • Unused local variables
  • Methods that aren't referenced by other code

Maybe having meaningless whitespace at the end of a code line or using somestring != null && somestring != '' rather than String.isEmpty(somestring) shouldn't be grounds to block packaging. You'll need to decide where the line gets drawn.

The other part of this type of testing is that it could form the basis of an automated org health check. Is the coverage percentage too low on a large class? Test fails. Trigger not bulkified? Test fails. An Apex class with 4000 lines of code that is padding for test coverage? Test fails!

You could easily drop them into an existing org to get a feel for the state of things before embarking on an modifications.

See also:

1. may or may not be actually possible with the SymbolTable alone.

Monday, September 28, 2015

Microsoft Ignite 2015 Round Up / Summary

I've summarised some of the most interesting/important parts of my TechEd 2015 NZ notes in this post.

The top five sessions for the conference based on session feedback:

  1. The Secret to Telling Awesome Stories from Microsoft's Chief Storyteller
  2. The Microsoft DevOps Vision
  3. Aligning Architecture to Organisation
  4. Public Speaking Skills for Quiet People
  5. Torment Your Colleagues with the 'Roslyn' .NET Compiler Platform

My top sessions, in no particular order

Great Artists Steal: Build better software by applying patterns and ideas from different languages

Orion Edwards - @borland

  • Ruby
  • C# Scoping lambda for locks and transactions, building up and then committing.
  • Consider the parameter naming. Try and form a phrase. C# named parameters.
  • Swift
  • if let - unwarps null references in if/else.
  • C# - Create Optional generic type. Implicitly converts from null. Unwrap to take lamba to handle existing and null cases. Not great for input parameters.
  • Also, HtmlEncoded, Atomic, Tainted, Either
  • C++ - Zero Cost Abstraction
  • Can be used with struct in C# as well.
  • System.DateTime is an example. Useful for multiple data types in combination. When unit of measure is important.
  • If you can get a Haskell program to compile, it is probably free of bugs.
  • Grand Central Dispatch - from Apple
  • Queues are lightweight threads. You "dispatch" lambda functions to them.
  • Like Dispatcher in C#
  • Serial Queue. Jobs won't run in parallel.
  • Go
  • goroutines and channels
  • Channel with send and receive.

Torment Your Colleagues with "Roslyn" .NET Compiler Platform

Ivan Towlson

"The Duke Nukem Forever of compilers"
  • C# and Visual Basic compilers
  • Syntax trees for code
  • Semantic model
  • Visual Studio editor integration.
  • Roslyn Overview on dotnet github.
  • Syntax Visualizer - browse the entire tree.

The Secret to Telling Awesome Stories from Microsoft's Chief Storyteller

The Internet of Hackable Things

Kirk Jackson @kirkj - Felix Shi @comradpara

Project Premonition: Mosquito seeking drones and Microsoft Azure

So You Want to Present at Ignite

Chris Jackson

  • 60 seconds to get their attention. Then got to land the point.
  • How to be effective as an influencer.
  • Preparing your submission - earning the right to be heard.
  • Build your reputation. Humans make the decision on who gets the cut. Who is the person, are they credible.
  • Be authenticate.
  • Volunteer to speak. Start a blog if writing is your thing.
  • Less likely to pick the total unknown.
  • Understand the goal of the track. What is the story they are trying to tell.
  • Sell yourself to the track lead.
  • Preparing for your talk.
  • Presentation design and presentation aids.
  • What do the track owners looks for.
  • What is on the screen should only be there to pull people back on track.
  • Keep the number of words on the slide to a minimum.
  • Max 5 words on 5 lines.
  • Make it real with demos.
  • You already know the material. You don't remember what it is like to not know.
  • The first 60 seconds. If it sounds awkward and unrehearsed with it's unrehearsed.
  • Practice the first 60 seconds the most.
  • What is shipping and what are the trends.
  • Inspire, don't teach. Take an action at the end of 60 minutes. One to three things tops.
  • Tell Stories. List of facts do little to inspire us.
  • How do I make this real.
  • Pillars and organization. How do you support the primary objective of the talk. Is it driving the outcome you want.
  • Stick your landing. Try to avoid ending on Q&A
  • Get speaker training. Someone who will tell you stuff you need to hear.

The Cinematic Cloud - Pixar Studios

Developing Cross Platform Mobile Apps with XAML and MVVM

See Also:

Thursday, September 24, 2015

Salesforce Winter `16 breaking SOAP Partner API changes

Just encountered this connecting to a Winter `16 Sandbox Org (v35.0) via the SOAP Partner API from Summer `15 (v34.0).

I've cross posted to the Salesforce StackExchange and raised support case 12544039

System.InvalidOperationException: There is an error in XML document (1, 2239646). ---> System.InvalidOperationException: Instance validation error: 'urn:SearchLayoutFieldsDisplayed' is not a valid value for soapType.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read2427_soapType(String s)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read2428_Field(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read2458_DescribeSObjectResult(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read2692_describeSObjectsResponse()
   at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer193.Deserialize(XmlSerializationReader reader)
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   at FuseIT.G4S.SalesforceConnector.SalesforcePartner.SforceService.describeSObjects(String[] sObjectType)

I suspect the problem is the new soapType's that were added in API version 35.0 for Winter `16.

As they didn't exist in v34.0 of the API, if they come back in the SOAP response the .NET XML Serialization won't know how to handle them.

The following API call against v34.0 of the Partner API shows the problem.



<soapenv:Envelope xmlns:soapenv="" xmlns:urn="">

Response Snippet

<soapenv:Envelope xmlns:soapenv="" xmlns="" xmlns:xsd="" xmlns:xsi="">
            <type>API REQUESTS</type>
               <label>Fields Displayed</label>
               <!-- ^^^ PROBLEM IS HERE for v34.0 - this isn't a valid soapType until v35.0 -->
            <label>Search Layout</label>
            <labelPlural>Search Layouts</labelPlural>
            <urlDetail xsi:nil="true"/>
            <urlEdit xsi:nil="true"/>
            <urlNew xsi:nil="true"/>

Ideally Salesforce shouldn't be sending elements from the v35.0 back to the v34.0 API. It's likely that SearchLayoutField, SearchLayoutButtonsDisplayed, SearchLayoutButton and RecordTypesSupported would cause similar issues with existing integrations.

Bonus namespace alterations

Be aware that some elements have changed namespace between v34.0 and v35.0. E.g. In v34.0 the soapType enumerations location and address were in the urn namespace (""). In v35.0 They are now in the tns namespace (xmlns:tns=""). Make sure the API URL you are calling matches up with the WSDL version the classes were generated from.

Tuesday, September 22, 2015

Dreamforce 2015 Round-up / Summary

This was my second year attending Salesforce's annual Dreamforce conference in San Francisco. My first was last year.

Again, I focused mostly on the developer side of things which are around the Moscone West building - Home of the Dev Zone

Dev Zone


Using Oculus Rift and Virtual Reality to Visualize Data on Salesforce

Introducing the Welkin Suite IDE for Salesforce

A Salesforce IDE built upon Visual Studio Code.

Custom Folder Structure - The ability to create sub folders within the project to organize components looks to be really useful.

Plus support for code comments.

Apex Enterprise Patterns: Building Strong Foundations

Patterns for:

  • Separation of Concerns + Factory Pattern
  • Service Layer
  • Domain Layer
  • Selector Layer

Parker Harris's True to the Core: What's Next for Our Core Products

  • It will be possible to disable Person Accounts in the future.

Get Ready for a New Kind of Customer Success with Marc Benioff & Special Guests

175,000+ conference attendees. 25,000 of which are developers.

Demo of Thunder, the IoT cloud integrated with the Azure Event Hub for Office 365

Build Reliable Asynchronous Code with Queueable Apex

Apex Interactive Debugger

Fireside Chat with Satya Nadella and Jessi Hempel

A nice perk of becoming a Salesforce MVP this year was reserved setting access to some of the keynotes. In my case I got front row seating to the Satya Nadella keynote. Right in line behind Tony Prophet, who some of you may remember from last years main keynote.

Salesforce Developer Keynote

Introduction To Apex Asynchronous Callout Framework, aka, Continuation

Apex Testing Tips and Tricks - Community Campfire

Generically Call External Classes from Managed Packages

Using Type.forName to get the Type for a classname configured in a custom setting that the managed package can instantiate using .newInstance().

Understanding the Salesforce Architecture: How We Do the Magic We Do

Meet the Developers

Marc Benioff & Parker Harris Q&A

Sessions to catch up on


<table style="width:194px;"><tr><td align="center" style="height:194px;background:url( no-repeat left"><a href=""><img src="" width="160" height="160" style="margin:1px 0 0 4px;"></a></td></tr><tr><td style="text-align:center;font-family:arial,sans-serif;font-size:11px"><a href="" style="color:#4D4D4D;font-weight:bold;text-decoration:none;">Dreamboat - Celebrity Infinity</a></td></tr></table>

I'd sum up the Dreamboat as:

"among the most impressive accommodation you'll hardly even see"

Dreamforce is a pretty full on conference. You can be booked up from breakfast to as late as you want with meetings, sessions, keynotes, and after hours functions. This usually means waking up sometime around 6 am, maybe grabbing a quick breakfast, and then disembarking to the first meeting of the day. Then staggering back in to get some sleep before doing it all again tomorrow (assuming you make it back before midnight).

As far as accommodation goes, I'd have to rate the Dreamboat as among the most impressive I've seen. With multiple swimming pools, a gym, theater, basket ball court, and casino (not operational) all on board, there was no shortage of things to do. If only you can find the time. I don't think I made it to the Constellation Lounge during daylight hours and was surprised to see what it looked like during daylight hours.

Plus the views. Open the curtains before leaving for the morning to catch the sun coming up behind the bay bridge. Then see the silhouette of the Golden Gate bridge as the sun sets. Then the city skyline in the evenings.

Salesforce StackExchange breakfast

It was great to catch up with fellow users of the site prior to the start of the conference. A good way to put faces to names before things get going at the conference.

Random learning's

  • It's hard to take a photo of yourself getting a ride on a Pedicab without getting an ass in the picture. Do have small notes for payment.
  • Don't tweet a picture of Yoshiki unless you want to draw the attention of his fans.
  • You're going to need another bag to bring everything back home.
  • Do stop by the Admin zone for the professional headshots. Try to do it early in the week before the lack of sleep starts to catch up with you.
  • Get your twitter handle and avatar on your badge. I spend all year interacting with people via twitter, then struggle to identify them in real life.
  • AT&T do a 1.5GB nano sim card with 1.5GB of data for $45 USD. Combined with the conference WiFi, it was easily enough to get through and stay connected.
  • You can't give session feedback on sessions held in the DevZone theaters as you can't scan into them like you can with the breakout rooms.
  • If you're a developer, ignore the advice to leave your laptop behind. How are you going to complete the Mini Hacks or try anything out as you go if you don't have your tools on hand?
    My Surface Pro 3 was really useful. I could knock out the mini hacks, take down more complicated notes, do on the spot demos, ... Only catch for me was needing to change my date time settings to PST to connect to the WiFi. Go figure.
  • If you can time it right, drop ship things to the FedEx office at 726 Market St. It is only a quick walk from the conference and you can get a "Hold at FedEx location" when shipping.
  • Got a spare 30 minutes. Make a quick excursion to the Expo in Moscone North.
  • Visit the construction site for the Salesforce tower.
  • To use the pre-purchased BART return ticket you need to print out the receipt to present at the airport information booth. They won't accept a digital version on a screen.

UCSF Benioff Hospital Tour

The hospital has autonomous TUG robots helping with transport tasks around the hospital. I'm surprised these weren't featured in the IoT side of the conference.

See also:

Tuesday, September 8, 2015

Dreamforce 2015 is coming. Are you prepared?

Something has always bothered me a bit about conferences. The reveal of large new roadmap features mid-conference. A day of sessions has already gone by, and now there is a keynote telling you about a great new feature that you want to learn more about before the end of the conference. What to do? Ditch all the other sessions that you have otherwise already carefully selected to start learning about a new feature from scratch?

The recent Salesforce global Lightning Experience event has bypassed that by moving the big announcement to a few weeks out before the conference starts. There is some lead time for delegates to adjust session schedules and hit the conference with some knowledge of what they are getting themselves into.

With Dreamforce 2015 just around the corner, it's a great time to get ahead and get yourself some of that preparation knowledge for the changes that are going to occur to the core user interface.

The Developer Trail - Lightning Experience brings together 5 modules that cover areas of interest to a developer.

With the Lightning experience being so new and not available in all orgs yet (not GA), the modules mostly use multi-choice questions in the evaluation rather than inspecting your connected developer edition org. You will however cover some important topics, such as:

You also get to learn the importance of having good admins and not letting the developers do the rollout to a large org. Confetti canons for Everyone!

Once the developer trail is completed, some of the modules have cross over with other trials. Such as the Lightning Experience Basics, which is the starting point for some of the trails. So you would already have a good start on Admin Trail - Migrating to Lightning Experience.

See Also: