Andy in the Cloud

From BBC Basic to Force.com and beyond…


3 Comments

Extending Lightning Process Builder and Visual Workflow with Apex

MyProcessBuilderI love empowering as many people to experience the power of Salesforce’s hugely customisable and extensible platform as possible. In fact this platform has taught me that creating a great solution is not just about designing how we think a solution would be used, but also about empowering how others subsequently use it in conjunction with the platform, to create totally new use cases we never dream off! If your not thinking about how what your building sits “within” the platform your not fully embracing the true power of the platform.

So what is the next great platform feature and what has it go to do with writing Apex code? Well for me its actually two features, one has been around for a while, Visual Workflow, the other is new and shiny and is thus getting more attention, Lightning Process Builder. However as we will see in this blog there is a single way in which you can expose your finely crafted Apex functionality to users of both tools. Both of them have their merits and in fact can be used together for a super charged clicks not code experience!

IMPORTANT NOTE: Regardless if your developing building a solution in a Sandbox or as part of packaged AppExchange solution, you really need to understand this!

What is the difference between Visual Workflow and Lightning Process Builder?

At first sight these two tools look to achieve similar goals, letting the user turn a business process into steps to be executed one after another applying conditional logic and branching as needed.

One of the biggest challenges i see with the power these tools bring is educating users on use cases they can apply. While technically exposing Apex code to them is no different, its important to know some of the differences between how they are used when talking to people about how to best leverage them with your extensions.

  • UI based Processes. Here the big difference is that mainly, where Visual Workflow is concerned its about building user interfaces that allow users to progress through your steps through a wizard style UI, created by the platform for you based on the steps you’ve defined. Such UI’s can be started when the end user clicks on a tab, button or link to start the Visual Workflow (see my other blogs).
    VisualFlowUI
  • Record based Processes. In contrast Process Builder is about steps you define that happen behind the scenes when users are manipulating records such as Accounts, Opportunities an in fact any Standard or Custom object you choose. This also includes users of Salesforce1 Mobile and Salesforce API’s. As such Process Builder actually has more of an overlap with the capabilities of classic Workflow Rules.
    ProcessBuilderActions
  • Complexity. Process Builder is more simplistic compared to Flow, that’s not to say Flow is harder to use, its just got more features historically, for variables, branching and looping over information.
  • Similarities. In terms of the type steps you can perform within each there are some overlaps and some obvious differences, for example there are no UI related steps in Process Builder, yet both do have some support for steps that can be used to create or update records. They can both call out to Apex code, more on this later…
  • Power up with both! If you look closely at the screenshot above, you’ll see that Flows, short for Visual Workflow, can be selected as an Action Type within Process Builder! In this case your Flow cannot contain any visual steps, only logic steps, since Process Builder is not a UI tool. Such Flows are known as Autolaunched Flows (previously known as ‘Headless Flows’), you can read more here. This capability allows you to model more complex business processes in Process Builder.

You can read more details on further differences here from Salesforce.

What parts of your code should you expose?

Both tools have the ability to integrate at a record level with your existing custom objects, thus any logic you’ve placed in Apex Triggers, Validation Rules etc is also applied. So as you read this, your already extending these tools! However such logic is of course related to changes in your solutions record data. What about other logic?

  • Custom Buttons, Visualforce Buttons, If you’ve developed a Custom Button or Visualforce page with Apex logic behind it you may want to consider if that functionality might also benefit from being available through these tools. Allowing automation and/or alternative UI’s to be build without the need to involve a custom Visualforce or Apex development or changes to your based solution.
  • Share Calculations and Sub-Process Logic, You may have historically written a single peace of Apex code that orchestrates in a fixed a larger process via a series of calculations in a certain order and/or chains together other Apex sub-processes together. Consider if by exposing this code in a more granular way, would give users more flexibility in using your solution in different use cases. Normally this might require your code to respond to a new configuration you build in. For example where they wish to determine the order your Apex code is called, if parts should be omitted or even apply the logic to record changes on their own Custom Objects.

Design considerations for Invocable Methods

Now that we understand a bit more about the tools and the parts of your solution you might want to consider exposing, lets consider some common design considerations in doing so. The key to exposing Apex code to these tools is leveraging a new Spring’15 feature known as Invocable Methods. Here is an example i wrote recently…

global with sharing class RollupActionCalculate
{
	/**
	 * Describes a specific rollup to process
	 **/
	global class RollupToCalculate {

		@InvocableVariable(label='Parent Record Id' required=true)
		global Id ParentId;

		@InvocableVariable(label='Rollup Summary Unique Name' required=true)
		global String RollupSummaryUniqueName;

		private RollupService.RollupToCalculate toServiceRollupToCalculate() {
			RollupService.RollupToCalculate rollupToCalculate = new RollupService.RollupToCalculate();
			rollupToCalculate.parentId = parentId;
			rollupToCalculate.rollupSummaryUniqueName = rollupSummaryUniqueName;
			return rollupToCalculate;
		}
	}

	@InvocableMethod(
		label='Calculates a rollup'
		description='Provide the Id of the parent record and the unique name of the rollup to calculate, you specificy the same Id multiple times to invoke multiple rollups')
	global static void calculate(List<RollupToCalculate> rollupsToCalculate) {

		List<RollupService.RollupToCalculate> rollupsToCalc = new List<RollupService.RollupToCalculate>();
		for(RollupToCalculate rollupToCalc : rollupsToCalculate)
			rollupsToCalc.add(rollupToCalc.toServiceRollupToCalculate());

		RollupService.rollup(rollupsToCalc);
	}
}

NOTE: The use of global is only important if you plan to expose the action from an AppExchange package, if your developing a solution in a Sandbox for deployment to Production, you can use public.

As those of you following my blog may have already seen, i’ve been busy enabling my LittleBits Connector and Declarative Lookup Rollup Summary packages for these tools. In doing so, i’ve arrived at the following design considerations when thinking about exposing code via Invocable Methods.

  1. Design for admins not developers. Methods appear as ‘actions’ or ‘elements’ in the tools. Work with a few admins/consultants you know to sense check what your exposing make sense to them, a method name or purpose from a developers perspective might not make as much sense to an admin.

  2. Don’t go crazy with the annotations! Salesforce has made it really easily to expose an Apex method via simple Apex annotations such as @InvocableMethod and @InvocableVariable. Just because its that easy doesn’t mean you don’t have to think carefully about where you apply them. I view Invocable Methods as part of your solutions API, and treat them as such, in terms of separation of concerns and best practices. So i would not apply them to methods on controller classes or even service classes, instead i would apply them to dedicate class that delegates to my service or business layer classes.

  3. Apex class, parameter and member names matter. As with my thoughts on API best practices, establish a naming convention and use of common terms when naming these. Salesforce provides a REST API for describing and invoking Invocable Methods over HTTP, the names you use define that API. Currently both tools show the Apex class name and not the label, so i would derive some kind of way to group like actions together, i’ve chosen to follow the pattern [Feature]Action[ActionName], e.g. LittleBitsActonSendToDevice, so all actions for a given feature in your application at least group together.

  4. Use the ‘label’ and ‘description’ annotation attributes. Both the @InvocableMethod and @InvocableVariable annotations support these, the tools will show your label instead of your Apex variable name in the UI. The Process Builder tool currently as far as i can see does not presently use the parameter description sadly (though Visual Workflow does) and neither tool the method description. Though i would recommend you define both in case in future releases that start to use it.
    • NOTE: As this text is end user facing, you may want to run it past a technical author or others to look for typos, spelling etc. Currently, there does not appear to be a way to translate these via Translation Workbench.

  5. Use the ‘required’ attribute. When a user adds your Invocable Method to a Process or Flow, it automatically adds prompts in the UI for parameters marked as required.
    	global class SendParameters {
    		@InvocableVariable(
                       Label='Access Token'
                       Description='Optional, if set via Custom Setting'
                       Required=False)
    		global String AccessToken;
    		@InvocableVariable(
                      Label='Device Id' Description='Optional, if set via Custom Setting'
                      Required=False)
            global String DeviceId;
    		@InvocableVariable(
                       Label='Percent'
                       Description='Percent of voltage sent to device'
                       Required=True)
            global Decimal Percent;
    		@InvocableVariable(
                       Label='Duration in Milliseconds'
                       Description='Duration of voltage sent to device'
                       Required=True)
            global Integer DurationMs;
    	}
    
        /**
         * Send percentages and durations to LittleBits cloud enabled devices
         **/
        @InvocableMethod(Label='Send to LittleBits Device' Description='Sends the given percentage for the given duration to a LittleBits Cloud Device.')
        global static void send(List<SendParameters> sendParameters) {
        	System.enqueueJob(new SendAsync(sendParameters));
    	}
    

    Visual Workflow Example
    FlowParams

    Lightning Process Builder Example
    ProcessBuilderParams

  6. Bulkification matters, really it does! Play close attention to the restrictions around your method signature when applying these annotations, as described in Invocable Method Considerations and Invocable Variables Considerations. One of the restrictions that made me smile was the insistence on the compiler requiring parameters be list based! If you recall this is also one of my design guidelines for the Apex Enterprise Patterns Service layer. Basically because it forces the developer to think about the bulk nature of the platform. Salesforce have thankfully enforced this, to ensure that when either of these tools call your method with multiple parameters in bulk record scenarios your strongly reminded to ensure your code behaves itself! Of course if your delegating to your Service layer, as i am doing in the examples above, this should be a fairly painless affair to marshall the parameters across.
    • NOTE: While you should of course write your Apex tests to pass bulk test data and thus test your bulkification code. You can also cause Process Builder and Visual Workflow to call your method with multiple parameters by either using List View bulk edits, Salesforce API or Anonymous Apex to perform a bulk DML operation on the applicable object.

  7. Separation of Concerns and Apex Enterprise Patterns. As you can see in the examples above, i’m treating Invocable Actions as just another caller of the Service layer (described as part of the Apex Enterprise Patterns series). With its own concerns and requirements.
    • For example the design of the Service method signatures is limited only by the native Apex language itself, so can be quite expressive. Where as Invocable Actions have a much more restricted capability in terms of how they define themselves, we want to keep these two concerns separate.
    • You’ll also see in my LittleBits action example above, i’m delegating to the Service layer only after wrapping it in an Async context, since Process Builder calls the Invocable Method in the Trigger context. Remember the Service layer is ‘caller agnostic’, thus its not its responsibility to implement Aysnc on the callers behalf.
    • I have also taken to encapsulating the parameters and marshalling of these into the Service types as needed, thus allowing the Service layer and Invocable Method to evolve independently if needed.
    • Finally as with any caller of the Service layer i would expect only one invocation and to create a compound Service (see Service best practices) if more was needed, as apposed to calling multiple Services from the one Invocable Method.

  8. Do I need to expose a custom Apex or REST API as well? So you might be wondering that since we now have a way to call Apex code declaratively and in fact via the Standard Salesforce REST API (see Carolina’s exploits here). Would you ever still consider exposing a formal Apex or REST API (as described here)? Well here are some of my current thoughts on this, things are still evolving so i stress these are still my current thoughts…
    • The platform provides as REST API generated from you Invocable Method annotations, so aesthetically and functionally may look different from what you might consider a true RESTful API, in addition will fall under a different URL path to those you defined via the explicit Apex REST annotations.
    • If your data structures of your API are such that they don’t fall within those defined by Invocable Methods (such as Apex types referencing other Apex types, use of Maps, Enums etc..) then you’ll have to expose the Service anyway as an Apex API.
    • If your parameters and data structures are no more complex then those required for an Invocable Method, and thus would be identical to those of the Apex Service you might consider using the same class. However keep in mind you can only have one Invocable Method per class, and Apex Services typically have many methods related to the feature or service itself. Also while the data structure may match today, new functional requirements may stress this in the future, causing you to reinstate a Service layer, or worse, bend the parameters of your Invocable Methods.
    • In short my current recommendation is to continue to create a full expressive Service driven API for your solutions and treat Invocable Methods as another API variant.

 

Hopefully this has given you some useful things to think about when planning your own use of Invocable Methods in the future. As this is a very new area of the platform, i’m sure the above will evolve further over time as well.

 

 

 


14 Comments

Declarative Lookup Rollup Summaries – Spring’15 Release

This tool has had a steady number of releases last year, containing a few bug fixes and tweaks. This Spring’15 release contains a few enhancements i’d like to talk about in more detail in this blog. So lets get started with the list…

  • Support for Count Distinct rollups
  • Support for Picklist / Text based rollups via Concatenate and Concatenate Distinct operations
  • Support for Rolling up First or Last child records ordered by fields on the child such as Created by Date
  • Support for Lightning Process Builder

UPGRADE NOTE: The Lookup Rollup Summaries object has some new fields and pick list values to support the above features. If you are upgrading you will need to add these fields and pick list values manually. I have listed these in the README.

NewRollup

The following sections go into more details on each of the features highlighted above.

Support for Count Distinct rollups

If you want to exclude duplicate values from the Field to Aggregate on the child object select the Count Distinct option. For example if your counting Car__c child records by Colour__c and it has 4 records, Red, Green, Blue, Red, the count would result in 3 being stored in the Aggregate Result Field. You can read more about the original idea here.

Support for Picklist / Text based rollups

TextRollupThe rollup operations Sum, Min, Max, Avg, Count and Count Distinct operations are still restricted to rolling up number and date/time fields as per the previous releases of the tool.

However this version of the tool now supports new operations Concatenate and Concatenate Distinct that support text based fields. Allowing you to effectively concatenate field values on children into a multi-picklist or text field on the parent object record.

By default children are concatenated based on ascending order of the values in the Field to Aggregate field. However you can also use the Field to Order By field to specify an alternative child field to order by. You can define a delimiter via the Concatenate Delimiter field. You can also enter BR() in this field to add new lines between the values or a semi-colon ; character to support multi-picklist fields. You can read more about the original idea here.

Support for Rolling up First or Last child records

RollupFirstBy using the new First and Last operations you can choose to store the first or last record of the associated child records in the parent field. As with the concatenate feature above, the Field to Aggregate is used to order the child records in ascending order. However the Field to Order By field can also be used to order by an alternative field. Original idea here.

Support for Lightning Process Builder

To date the tool requires a small Apex Trigger to be deployed via the Manage Child Trigger button. With added support for Lightning Process Builder actions. This allows rollup calculations to be performed when creating or updating child object records. Sadly for the moment Process Builder does not support record deletion, so if your rollups require calculation on create, update and delete, please stick to the traditional approach.

ProcessBuilderModeTo use the feature ensure you have selected Process Builder from the Calculation Mode field and specified a unique name for the rollup definition in the Lookup Rollup Summary Unique Name. RollupUniqueName

Once this is configured your ready to add an Action in the Process Builder to execute the rollup. The following Process shows an example configuration.

ProcessBuilder1

ProcessBuilder2

As you’ve seen from some of my more recent blogs, i’m getting quite excited about Process Builder. However i have to say on further inspection, its got a few limits that really stop it for now being really super powerful! Having support for handling deletion of records and also some details in terms of how optimal it invokes the actions prevent me from recommending this feature in production. Please give me your thoughts on how else you think it could be used.


4 Comments

Controlling Internet Devices via Lightning Process Builder

Lightning Process Builder will soon become GA once the Spring’15 rollout completes in early February, just a few short weeks away as i write this. I don’t actually know where to start in terms of how huge and significant this new platform feature is! In my recent blog Salesforce evolves customization to a new level! over on the FinancialForce blog, i describe Salesforce as ‘the most powerful and productive cloud platform on the planet’. The more and more i get into Process Builder and how as a developer i can empower users of it, that statement is already starting to sound like an understatement!

There are many things getting me excited (as usual) about Salesforce these days, in addition to Process Builder and Invocable Actions (more on this later), its the Internet of Things. I just love the notion of inspecting and controlling devices no matter where i am on the planet. If you’ve been following my blog from earlier this year, you’ll hopefully have seen my exploits with the LittleBits cloud enabled devices and the Salesforce LittleBits Connector.

pointingdeviceI have just spent a very enjoyable Saturday morning in my Spring’15 Preview org with a special build of the LittleBits Connector. That leverages the ability for Process Builder to callout to specially annotated Apex code that in turn calls out to the LittleBits Cloud API.

The result, a fully declarative way to connect to LittleBits devices from Process Builder! If you watch the demo from my past blog you’ll see my Opportunity Probability Pointer in action, the following implements the same process but using only Process Builder!

LittleBitsProcessBuilder

Once Spring’15 has completely rolled out i’ll release an update to the Salesforce LittleBits Connector managed package that supports Process Builder, so you can try the above out. In the meantime if have a Spring’15 Preview Org you can deploy direct from GitHub and try it out now!

How can developers enhance Process Builder?

There are some excellent out of the box actions from which Process Builder or Flow Designer users can choose from, as i have covered in past blogs. What is really exciting is how developers can effectively extend these actions.

So while Salesforce has yet to provide a declarative means to make Web API callouts without code. A developer needs to provide a bit of Apex code to make the above work. Salesforce have made it insanely easy to expose code to tools like Process Builder and also Visual Flow. Such tools dynamically inspects Apex code in the org (including that from AppExchange packages) and renders a user interface for the Process Builder user to provide the necessary inputs (and map outputs if defined). All the developer has to do is use some Apex annotations.

global with sharing class LittleBitsActionSendToDevice {

	global class SendParameters {
		@InvocableVariable
		global String AccessToken;
		@InvocableVariable
        global String DeviceId;
		@InvocableVariable
        global Decimal Percent;
		@InvocableVariable
        global Integer DurationMs;
	}
	
    /**
     * Send percentages and durations to LittleBits cloud enabled devices
     **/
    @InvocableMethod(
    	Label='Send to LittleBits Device' 
    	Description='Sends the given percentage for the given duration to a LittleBits Cloud Device.')
    global static void send(List<SendParameters> sendParameters) {
    	System.enqueueJob(new SendAsync(sendParameters));
	}	
}

I learn’t quite a lot about writing Invocable Actions today and will be following up with some guidelines and thoughts on how i have integrated them with Apex Enterprise Patterns Service Layer.


5 Comments

Creating, Assigning and Checking Custom Permissions

I have been wanting to explore Custom Permissions for a little while now, since they are now GA in Winter’15 i thought its about time i got stuck in. Profiles, Permission Sets have until recently, been focusing on granting permissions to entities only known to the platform, such as objects, fields, Apex classes and Visualforce pages. In most cases these platform entities map to a specific feature in your application you want to provide permission to access.

However there are cases where this is not always that simple. For example consider a Visualforce page you that controls a given process in your application, it has three buttons on it Run, Clear History and Reset. You can control access to the page itself, but how do you control access to the three buttons? What you need is to be able to teach Permission Sets and Profiles about your application functionality, enter Custom Permissions!

CustomPermissions
CustomPermission

NOTE: That you can also define dependencies between your Custom Permissions, for example Clear History and Reset permissions might be dependent on a Manage Important Process  custom permission in your package.

Once these have been created, you can reference them in your packaged Permission Sets and since they are packaged themselves, they can also be referenced by admins managing your application in a subscriber org.

SetCustomPermissions

The next step is to make your code react to these custom permissions being assigned or not.

New Global Variable $Permission

You can use the $Permission from a Visualforce page or as SFDCWizard points out here from Validation Rules! Here is the Visualforce page example given by Salesforce in their documentation.

<apex:pageBlock rendered="{!$Permission.canSeeExecutiveData}">
   <!-- Executive Data Here -->
</apex:pageBlock>

Referencing Custom Permissions from Apex

In the case of object and field level permissions, the Apex Describe API can be used to determine if an object or field is available and for what purpose, read or edit for example. This is not going help us here, as custom permissions are not related to any specific object or field. The solution is to leverage the Permission Set Object API to query the SetupEntityAccess and CustomPermission records for Permission Sets or Profiles that are assigned to the current user.

The following SOQL snippets are from the CustomPermissionsReader class i created to help with reading Custom Permissions in Apex (more on this later). As you can see you need to run two SOQL statements to get what you need. The first to get the Id’s the second to query if the user actually has been assigned a Permission Set with them in.


List<CustomPermission> customPermissions =
    [SELECT Id, DeveloperName
       FROM CustomPermission
       WHERE NamespacePrefix = :namespacePrefix];

List<SetupEntityAccess> setupEntities =
    [SELECT SetupEntityId
       FROM SetupEntityAccess
       WHERE SetupEntityId in :customPermissionNamesById.keySet() AND
             ParentId IN (SELECT PermissionSetId
                FROM PermissionSetAssignment
                WHERE AssigneeId = :UserInfo.getUserId())];

Now personally i don’t find this approach that appealing for general use, firstly the Permission Set object relationships are quite hard to get your head around and secondly we get charged by the platform to determine security through the SOQL governor. As a good member of the Salesforce community I of course turned my dislike into an Idea “Native Apex support for Custom Permissions” and posted it here to recommend Salesforce include a native class for reading these, similar to Custom Labels for example.

Introducing CustomPermissionReader

In the meantime I have set about creating an Apex class to help make querying and using Custom Permissions easier. Such a class might one day be replaced if my Idea becomes a reality or maybe its internal implementation just gets improved. One things for sure, i’d much rather use it for now than seed implicit SOQL’s throughout a code base!

Its pretty straight forward to use, construct it in one of two ways, depending if you want all non-namespaced Custom Permissions or if your developing a AppExchange package, give it any one of your packaged Custom Objects and it will ensure that it only ever reads the Custom Permissions associated with your package.

You can download the code and test for CustomPermissionsReader here.


// Default constructor scope is all Custom Permissions in the default namespace
CustomPermissionsReader cpr = new CustomPermissionsReader();
Boolean hasPermissionForReset = cpr.hasPermission('Reset');

// Alternative constructor scope is Custom Permissions that share the
//   same namespace as the custom object
CustomPermissionsReader cpr = new CustomPermissionsReader(MyPackagedObject.SObjectType);
Boolean hasPermissionForReset = cpr.hasPermission('Reset');

Like any use of SOQL we must think in a bulkified way, indeed its likely that for average to complex peaces of functionality you may want to check at least two or more custom permissions once you get started with them. As such its not really good practice to make single queries in each case.

For this reason the CustomPermissionsReader was written to load all applicable Custom Permissions and act as kind of cache. In the next example you’ll see how i’ve leveraged the Application class concept from the Apex Enterprise Patterns conventions to make it a singleton for the duration of the Apex execution context.

Here is an example of an Apex test that creates a PermissionSet, adds the Custom Permission and assigns it to the running user to confirm the Custom Permission was granted.

	@IsTest
	private static void testCustomPermissionAssigned() {

		// Create PermissionSet with Custom Permission and assign to test user
		PermissionSet ps = new PermissionSet();
		ps.Name = 'Test';
		ps.Label = 'Test';
		insert ps;
		SetupEntityAccess sea = new SetupEntityAccess();
		sea.ParentId = ps.Id;
		sea.SetupEntityId = [select Id from CustomPermission where DeveloperName = 'Reset'][0].Id;
		insert sea;
		PermissionSetAssignment psa = new PermissionSetAssignment();
		psa.AssigneeId = UserInfo.getUserId();
		psa.PermissionSetId = ps.Id;
		insert psa;

		// Create reader
		CustomPermissionsReader cpr = new CustomPermissionsReader();

		// Assert the CustomPermissionsReader confirms custom permission assigned
		System.assertEquals(true, cpr.hasPermission('Reset'));
	}

Seperation of Concerns and Custom Permissions

Those of you familiar with using Apex Enterprise Patterns might be wondering where checking Custom Permission fits in terms of separation of concerns and the layers the patterns promote.

The answer is at the very least in or below the Service Layer, enforcing any kind of security is the responsibility of the Service layer and callers of it are within their rights to assume it is checked. Especially if you have chosen to expose your Service layer as your application API.

This doesn’t mean however you cannot improve your user experience by using it from within Apex Controllers,  Visualforce pages or @RemoteAction methods to control the visibility of related UI components, no point in teasing the end user!

Integrating CustomerPermissionsReader into your Application class

The following code uses the Application class concept i introduced last year and at Dreamforce 2014, which is a single place to access your application scope concepts, such as factories for selectors, domain and service class implementations (it also has a big role to play when mocking).

public class Application {

	/**
	 * Expoeses typed representation of the Applications Custom Permissions
	 **/
	public static final PermissionsFactory Permissions = new PermissionsFactory();

	/**
	 * Class provides a typed representation of an Applications Custom Permissions
	 **/
	public class PermissionsFactory extends CustomPermissionsReader
	{
		public Boolean Reset { get { return hasPermission('Reset'); } }
	}
}

This approach ensures their is only one instance of the CustomPermissionsReader per Apex Execution context and also through the properties it exposes gives a compiler checked way of referencing the Custom Permissions, making it easier for application developers code to access them.

if(Application.Permissions.Reset)
{
  // Do something to do with Reset...
}

Finally, as a future possibility, this approach gives a nice injection point for mocking the status of Custom Permissions in your Apex Unit tests, rather than having to go through the trouble of setting up a Permission Set and assigning it in your test code every time as shown above.

Call to Action: Ideas to Upvote

While writing this blog I created one Idea and came across a two others, i’d like to call you the reader to action on! Please take a look and of course only if you agree its a good one, give it the benefit of your much needed up vote!


3 Comments

Introducing the LittleBits Connector for Salesforce

As those of you know that follow my brickinthecloud.com blog, i love using API’s in the cloud to connect not only applications, but devices. Salesforce themselves also share this passion, just take a look at their Internet of Things page to see how it can improve your business and the work Reid Carlberg is doing.

LittleBitsWithEV3When Salesforce sent me a LittleBits Cloud Starter Kit as Christmas present i once again set about connecting it to my favourite cloud platform! This blog introduces two new GitHub repos and a brand new installable package to allow you to take full advantage of the snap-not-solder that LittleBits electronics brings with the Salesforce clicks-not-code design model! So if your not an electronics whiz or coder, you really don’t have any excuses for not getting involved! LittleBits provides over 60 snap together components, to build automated fish feeders, to home security systems and practically anything else you can imagine!

cloud_diagram2The heart of the kit is a small computer module, powered by a USB cable (i plugged mine into my external phone battery pack!). It boots from an SD card and uses an onboard USB Wifi adapter to connect itself to the internet (once you’ve connected it to your wifi). After that you send commands to connected outputs to it via a mobile site or set of LittleBits Cloud API’s provided. So far i have focused on sending commands to the outputs (in my case i connected the servo motor), however as i write this i’m teaming up with Cory Cowgill who has also starting working with his kit from an inputs perspective (e.g. pressing on a button on the device).

Everyone in the Salesforce MVP community was lucky enough to get one of these kits and i wanted to make sure everyone could experience it with the cloud platform we love so much! Sadly right now the clicks-not-code solution IFTTT  (If-This-Then-That) used for controlling LittleBits devices does not fully support Salesforce (there is only a Salesforce Chatter plugin). Borrowing an approach i’ve been using for my Declarative Rollup Summary Tool, i set about building a declarative based tool that would allow the Salesforce admin to connect updates to any standard or custom object record to a LittleBits device!

The result is the LittleBits Connector!

LittleBitsTrigger

Once you have assembled and connected your LittleBits device, go to the Settings page under LittleBits Cloud Control and take note of your Access Token and Device ID. As you can see in the screenshot above enter these in the LittleBits Device section or in the LittleBits API custom setting.

The Trigger section needs only the Record ID of the record you want to monitor and have your device respond to when changes are made. Simply list the field API names (separated by a comma) of those you want the tool to monitor. Next fill in the LittleBits Output section with either literal values (on the left) and/or dynamic values driven by values from the record itself. This gives you quite a lot of flexibility to use Formula Fields for example to calculate the percentage.

Controlling a LittleBits cloud device is quite simple, define the duration of the output (how long to apply a voltage) and the amount of voltage as a percentage. Depending on the output module you’ve fitted, light or motor, the effects differ but the principle is the same. In the motor case, i set mine to Turn mode (see below). Then by applying a duration of 100,000 and a percent the motor turns to a specific point each time. Making it ideal for building pointing devices!

With the help of my wifes crafting skills we set about on a joint Christmas project to build a pointing device that would show the Probability of a given Opportunity in realtime. Though the tool I ended up building can effectively be used with any standard or custom object. I also wanted to use only the modules in the LittleBits Cloud Start Kit. So with Salesforce Org and the tool the Internet of Things is in your hands!

Here is a video of our creation in action…

If you want to have a go yourself follow these steps…

Building your own Opportunity Probability Indicator Device #clicksnotcode

If clicks are more your thing than coding, fear not and follow these simple steps!

  1. Purchase a LittleBits Cloud Connector and follow the onscreen instructions once you have created your LittleBits account here. Complete the tutorial to confirm its connected.
  2. Build the device modules configuration as shown in the picture below. On the servo module, there is a tiny switch, use the small screw driver provided to push it to the down position, to put the servo in “turn” mode.
    LittleBitsDevice
  3. Next the fun bit, construct your pointing device! I’d love to see tweets of everyones crafting skills!
    pointingdevice
  4. Install the latest LittleBits Connector either via clicking the package install links or as code, see GitHub README. The first time you go to the LittleBits Trigger tab, you maybe asked to complete the post install step to configure the Metadata API needed by the tool to deploy the Apex Triggers, complete this step as instructed on screen.
  5. Click New on the LittleBits Trigger tab, complete the LittleBits Trigger record as described above, but of course using a record Id from an Opportunity record in your org then click Save.
  6. Click the Manage Object Trigger button to automatically deploy a small Apex Trigger to pass on updates made to the records to the LittleBits Connector engine.
  7. In Salesforce or Salesforce1 Mobile for that matter, update your Opportunity Stage (which updates the Probability). This results in an Apex Job which typically fires fairly promptly and you should see your device respond! If you don’t see anything change on your device confirm its working via the LittleBits Cloud Control test page, next go to the Setup menu check the jobs are completing without error via the Apex Jobs page.

Using the LittleBits Cloud API from Apex

The above tool was built around an Apex wrapper i have started to build around the LittleBits Cloud API, which is a REST API. With a little more time and help from fellow LittleBits fan Cory, we will update it to support not only controlling devices, but also allow them to feedback to Salesforce. In the meantime if you want to code your own solution directly you can install the library here.

The code is quite simply for now, you can read more about it in the README file.

new LittleBits().getDevice().output(80, 10000);

Whats next?

Well i’m quite addicted to this new device, my Lego EV3 robot might be justified in feeling a little left out, but fear not, i’ll find a way to combine them i’m sure! Next up for the LittleBits Connector is subscribing to output from the device back to Salesforce, possibly calling out to a headless Flow, to keep that clicks not code feel going!


9 Comments

Permission Sets and Packaging

Permission Sets have been giving me and an unlucky few who are unable to install my Declarative Rollup Summary Tool some headaches since i introduced them. Thankfully I’ve recently discovered why and thought it worth sharing along with some other best practices i have adopted around packaging permission sets since…

Package install failures due to Permission Sets

After including Permission Sets in my package, I found that some users where failing to install the package, they received via email, the following type of error (numbers in brackets tended to differ).

Your requested install failed. Please try this again.
None of the data or setup information in your salesforce.com organization should have been 
 affected by this error.
If this error persists, contact salesforce.com Support through your normal channels
 and reference number: 604940119-57161 (929381962)

It was frustrating that i could not help them decode this message, it required them to raise a Salesforce support case and pass their org ID and error codes on the case. For those that did this, it became apparent after several instances, a theme was developing, a package platform feature dependency!

Normally such things surface in the install UI for the user to review and resolve. Dependencies also appear when you click the View Dependencies button prior to uploading your package. However it seems that Salesforce is currently not quite so smart in the area of Permission Sets and dependency management, as these are hidden from both!

Basically i had inadvertently packaged dependencies to features like Ideas and Streaming API via including my Permission Sets, one of which i had chosen to enable the Author Apex permission. This system permission seems to enable a lot of other permissions as well as enabling other object permissions (including optional features like Ideas, which happened to be enabled in my packaging org). Then during package install if for historic reasons the subscriber org didn’t have these features enabled the rather unhelpful error above occurs!

Scrubbing my Permission Sets

I decided enough was enough and wanted to eradicate any Salesforce standard permission from my packaged Permission Sets. This was harder than i thought, since simply editing the .permissionset file and uploading it didn’t not remove anything (this approach is only suitable for changing or adding permissions within a permission set).

Next having removed entries from the .permissionset file, i went into the Permission Set UI within the packaging org and set about un-ticking everything not related to my objects, classes and pages. This soon became quite an undertaking and i wanted to be sure. I then recalled that Permission Sets are cool because they have an Object API!

I started to use the following queries in the Developer Console to view and delete on mass anything i didn’t want, now i was sure i had removed any traces of any potentially dangerous and hidden dependencies that would block my package installs. I obtained the Permission Set ID below from the URL when browsing it in the UI.

select Id, SobjectType, PermissionsCreate, PermissionsEdit, PermissionsDelete, PermissionsRead
  from ObjectPermissions where ParentId = '0PSb0000000HT5A'
select Id, SobjectType, Field
  from FieldPermissions where ParentId = '0PSb0000000HT5A'

CheckObjectPermissions

Note that System Permissions (such as Author Apex) which are shown in the UI, currently don’t have an Object API, so you cannot validate them via SOQL. However at least these are listed on a single page so are easier to check visually.

Lessons learned so far…

So here are a few lessons i’ve learned to date around using Permission Sets…

  • Don’t enable System Permissions unless your 100% sure what other permissions they enable!
  • When editing your .permissionset files don’t assume entries you remove will be removed from the org.
  • Use SOQL to query your Permission Sets to check they are exactly what you want before uploading your package
  • Don’t make your Permission Sets based on a specific User License type (this is covered in the Salesforce docs but i thought worth a reminder here as it cannot be undone).
  • Do design your Permission Sets based on feature and function and not based on user roles (which are less likely to match your perception of the role from one subscriber to another). Doing the former will reduce the chances of admins cloning your Permission Sets and loosing out on them being upgraded in the future as your package evolves.


1 Comment

Mocking SOQL sub-select query results

If your a fan of TDD you’ll hopefully have been following FinancialForce.com‘s latest open source contribution to the Salesforce community, known as ApexMocks. Providing a fantastic framework for writing true unit tests in Apex. Allowing you to implement mock implementations of classes used by the code your testing.

The ability to construct data structures returned by mock methods is critical. If its a method performing a SOQL query, there has been an elusive challenge in the area of queries containing sub-selects. Take a look at the following test which inserts and then queries records from the database.

	@IsTest
	private static void testWithDb()
	{
		// Create records
		Account acct = new Account(
			Name = 'Master #1');
		insert acct;
		List<Contact> contacts = new List<Contact> {
			new Contact (
				FirstName = 'Child',
				LastName = '#1',
				AccountId = acct.Id),
			new Contact (
				FirstName = 'Child',
				LastName = '#2',
				AccountId = acct.Id) };
		insert contacts;

		// Query records
		List<Account> accounts =
			[select Id, Name,
				(select Id, FirstName, LastName, AccountId from Contacts) from Account];

		// Assert result set
		assertRecords(acct.Id, contacts[0].Id, contacts[1].Id, accounts);
	}

	private static void assertRecords(Id parentId, Id childId1, Id childId2, List<Account> masters)
	{
		System.assertEquals(Account.SObjectType, masters.getSObjectType());
		System.assertEquals(Account.SObjectType, masters[0].getSObjectType());
		System.assertEquals(1, masters.size());
		System.assertEquals(parentId, masters[0].Id);
		System.assertEquals('Master #1', masters[0].Name);
		System.assertEquals(2, masters[0].Contacts.size());
		System.assertEquals(childId1, masters[0].Contacts[0].Id);
		System.assertEquals(parentId, masters[0].Contacts[0].AccountId);
		System.assertEquals('Child', masters[0].Contacts[0].FirstName);
		System.assertEquals('#1', masters[0].Contacts[0].LastName);
		System.assertEquals(childId2, masters[0].Contacts[1].Id);
		System.assertEquals(parentId, masters[0].Contacts[1].AccountId);
		System.assertEquals('Child', masters[0].Contacts[1].FirstName);
		System.assertEquals('#2', masters[0].Contacts[1].LastName);
	}

Now you may think you can mock the results of this query by simply constructing the required records in memory, but you’d be wrong! The following code fails to compile with a ‘Field is not writeable: Contacts‘ error on line 16.

		// Create records in memory
		Account acct = new Account(
			Id = Mock.Id.generate(Account.SObjectType),
			Name = 'Master #1');
		List<Contact> contacts = new List<Contact> {
			new Contact (
				Id = Mock.Id.generate(Contact.SObjectType),
				FirstName = 'Child',
				LastName = '#1',
				AccountId = acct.Id),
			new Contact (
				Id = Mock.Id.generate(Contact.SObjectType),
				FirstName = 'Child',
				LastName = '#2',
				AccountId = acct.Id) };
		acct.Contacts = contacts;

While Salesforce have gradually opened up write access to previously read only fields, the most famous of which being Id, they have yet to enable the ability to set the value of a child relationship field. Paul Hardaker contacted me recently to ask if this problem had been resolved, as he had the very need described above. Using his ApexMock’s framework he wanted to mock the return value of a Selector class method that makes a SOQL query with a sub-select.

Driven by an early workaround (I believe Chris Peterson found) to the now historic inability to write to the Id field. I started to think about using the same approach to stich together parent and child records using the JSON serialiser and derserializer. Brace yourself though, because its not ideal, but it does work! And i’ve managed to wrap it in a helper method that can easily be adapted or swept out if a better solution presents itself.

	@IsTest
	private static void testWithoutDb()
	{
		// Create records in memory
		Account acct = new Account(
			Id = Mock.Id.generate(Account.SObjectType),
			Name = 'Master #1');
		List<Contact> contacts = new List<Contact> {
			new Contact (
				Id = Mock.Id.generate(Contact.SObjectType),
				FirstName = 'Child',
				LastName = '#1',
				AccountId = acct.Id),
			new Contact (
				Id = Mock.Id.generate(Contact.SObjectType),
				FirstName = 'Child',
				LastName = '#2',
				AccountId = acct.Id) };

		// Mock query records
		List<Account> accounts = (List<Account>)
			Mock.makeRelationship(
				List<Account>.class,
				new List<Account> { acct },
				Contact.AccountId,
				new List<List<Contact>> { contacts });			

		// Assert result set
		assertRecords(acct.Id, contacts[0].Id, contacts[1].Id, accounts);
	}

NOTE: Credit should also go to Paul Hardaker for the Mock.Id.generate method implementation.

The Mock class is provided with this blog as a Gist but i suspect will find its way into the ApexMocks at some point. The secret of this method is that it leverages the fact that we can in a supported way expect the platform to deserialise into memory the following JSON representation of the very database query result we want to mock.

[
    {
        "attributes": {
            "type": "Account",
            "url": "/services/data/v32.0/sobjects/Account/001G000001ipFLBIA2"
        },
        "Id": "001G000001ipFLBIA2",
        "Name": "Master #1",
        "Contacts": {
            "totalSize": 2,
            "done": true,
            "records": [
                {
                    "attributes": {
                        "type": "Contact",
                        "url": "/services/data/v32.0/sobjects/Contact/003G0000027O1UYIA0"
                    },
                    "Id": "003G0000027O1UYIA0",
                    "FirstName": "Child",
                    "LastName": "#1",
                    "AccountId": "001G000001ipFLBIA2"
                },
                {
                    "attributes": {
                        "type": "Contact",
                        "url": "/services/data/v32.0/sobjects/Contact/003G0000027O1UZIA0"
                    },
                    "Id": "003G0000027O1UZIA0",
                    "FirstName": "Child",
                    "LastName": "#2",
                    "AccountId": "001G000001ipFLBIA2"
                }
            ]
        }
    }
]

The Mock.makeRelationship method turns the parent and child lists into JSON and goes through some rather funky code i’m quite proud off, to splice the two together, before serialising it back into an SObject list and vola! It currently only supports a single sub-select, but can easily be extended to support more. Regardless if you use ApexMocks or not (though you really should try it), i hope this helps you write a few more unit tests than you’ve previous been able.

 

Follow

Get every new post delivered to your Inbox.

Join 198 other followers