Salesforce Marketing Cloud Developer

The document linked below provides a high-level overview of the Marketing Cloud data modelling and management tools, programming languages, and APIs. For architects and developers taking the Salesforce Marketing Cloud Developer certification the document provides a useful technical reference.

 

Salesforce Marketing Cloud Developer

Salesforce Summer ’20 Architect Highlights

I first published a release highlights post on this blog over 8 years ago; since that time the series has been renamed a few times but retained a focus on summarising the key technical aspects delivered with each release. I’ve always found preparing the content for the post a useful way to organise my own release readiness and feedback has indicated that amongst the plethora of release related blog posts available today there remains space for one with a technical slant. I hope so.

This post marks something of a relaunch to the series, this time with a strong focus on concerns significant to the Salesforce architect community (i.e. technical, solution or integration architects).

Release Timeline

Given the current global situation with COVID-19 the release timeline for Summer ’20 is approximately 1 month later than normal for a summer release. Each Salesforce release represents potential technical disruption for customers and managing this in parallel with the ongoing impact of the pandemic seems like an avoidable situation. The Summer ’20 sandbox preview is now scheduled for May 20-30th and the Summer ’20 production release is scheduled for June 12th (1st release window), July 10th (2nd) and July 17-18th *(3rd and final). As ever the trust site provides the full detail of the release timeline.

In advance of the sandbox preview window Summer ’20 pre-release orgs can be requested via the pre-release sign-up page. During the sandbox preview window Summer ’20 preview Scratch Orgs can be created by adding the release option (“release” : “Preview”) to the scratch org definition file.

The Salesforce Summer ’20 release notes are available from today at https://releasenotes.docs.salesforce.com/en-us/summer20/release-notes

 

Architect Highlights (in no order)

Application Architecture

Record-Changed Flows

Previously Before-Save Flows could be implemented to efficiently update Record field values during the before-commit phase of the record save transaction; historically this has been a strong ApexTrigger use case. For many implementations a significant improvement in record-save performance could be achieved by consolidating Processes and before-event ApexTrigger logic into a single Flow. Refactoring Process Builder Processes which served to populate field values on the same record only could achieve a remarkable reduction in save time which in turn delivers a more responsive end user experience and a potential reduction in CPU timeout errors. With Summer ’20 Before-Save Flows are now Record-Changed Flows which support before-save and after-save events; equating to before or after ApexTrigger events. In the former case the Flow is restricted to field value updates (via $Record) but the latter enables a wider range of Flow actions to be utilised.

This new capability enables Workflows and Processes to be reimplemented following a single Flow pattern which should achieve the best performance outcome.

Platform Event Flows

Process automation initiated via Platform Event has been possible with Process Builder up to now, with Summer ’20 this is extended to Flow Builder. Platform Event Flows represent an obvious next step on the emergence of Flow Builder as the hub for all things process automation.

With this model it is possible to build out complex business logic (declaratively) in Flow Builder which fires in response to on-or-off platform asynchronous events; a powerful combination particularly in the data integration context.

Flow System Context

Flows which are specified to run in System Context (that bypass the permissions of the running user) can now run outside of the Sharing Model (effectively Without Sharing in Apex terms). Previously System Context was limited to removing Object and Field Access permission checks with the Sharing Model record-level access checks enforced by the Flow execution.

Apex-Defined Type Flow Variables

An Apex-Defined Type is simply an Apex Object typically representing deserialised JSON response in a data integration scenario. ADT variables could historically be utilised within Flows but could not be passed into the Flow from the calling context. With Summer ’20 it is now possible to hand-off callout response processing to a Flow, as one example use case. Whilst a seemingly minor change this opens up Flow as viable option for defining business logic for key use cases that would otherwise have required Apex code.

Dynamic Forms (Non GA Preview)

Undoubtably one of the most eagerly anticipated features for some time Dynamic Forms makes its preview debut in the Summer ’20 release. The Dynamic Forms feature is billed as an upgrade to Page Layouts where UI composition (sections, fields and visibility logic) occurs directly within Lightning App Builder. Preview support is limited to custom objects and excludes record pages that use pinned-region or custom page templates.

Lightning Message Service

The Lightning Message Service provides a standardised mechanism for communication across components on a page or across pages. Supported component types include Visualforce Pages, Aura Components and LWC. Communication is facilitated by Lightning Message Channel subscription and publication.

Development Lifecycle

Source Tracking in Sandboxes (Beta)

The source tracking deployment type is now supported for the developer sandbox types (Developer and Developer Pro); previously source tracking was restricted to Scratch Orgs. Source tracking enables efficient synchronisation of changed metadata between the local environment and the Salesforce org. Where existing development or release management processes (i.e. build automation and CI) are yet to be transitioned to Scratch Orgs this capability offers increased efficiency and accuracy as tracking of the changed metadata state is managed by the platform.

Org Dependent Unlocked Packages

Most Salesforce implementations suffer from a legacy accumulation of metadata components built up over a period of time by multiple projects, teams and partners. In such cases the benefits of implementing a structured Unlocked Package approach can appear to be unrealistic due to the degree of interdependency across the environment. With Org Dependent Unlocked Packages, metadata validation (i.e. dependency checking) can be deferred to the time of package installation, rather than during package version upload. Org Dependent Unlocked Packages can be created with the orgdependent Salesforce CLI parameter.

Security Architecture

Initiate Two Factor Authentication (2FA) with Apex

Two new methods have been added to the System.UserManagement class to enable Apex initiation of 2FA verification (e.g. Salesforce Authenticator). One method initiates a 2FA verification service (initVerificationMethod), the second completes the verification (verifyVerificationMethod).

Highly Trusted Users

The new “Skip Identity Confirmation at Login” permission allows users to login without second factor identity verification. Clearly one to use with a high degree of caution but useful for certain use cases where 2FA is impossible or impractical.

Minimum Access User Profile

The new “Minimum Access – Salesforce” User Profile provides a base profile for the Salesforce user license type defined following the principles of least privilege, a well-established security best practice. This profile can be cloned and extended as required or used in concert with Permission Sets. This support for a secure-by-default model feels long overdue.

Integration Architecture

Async Platform Event Publish Operations (Pilot)

The initial success of a Platform Event publication can be straightforward to determine (e.g. access to the SaveResult in Apex code) but the eventual state of the event is not accessible. To address this gap a new standard Platform Event (PlatformEventStatus) has been added; subscribers (e.g. ApexTrigger) are pushed status updates for High Volume Platform Events that have the “Track Publish Status” setting enabled.

Functional Architecture

Service Cloud. Omni-Channel Status-Based Capacity Model

Previously Omni-Channel tracked Agent capacity by the number of open tabs within the Agent Console. For short-lived Work Items (e.g. Case or Lead) that are resolved within a single user session the tab-based capacity model is often appropriate and can work well. However, this is not the case where Work Items are longer-lived and have a lifecycle that spans multiple user sessions or days: this leaves Omni-Channel a poor fit for many service operations. To address this Omni-Channel can now be configured to track Agent capacity based on the status of the Work Items that the Agent owns. The new Omni-Channel setting “Enable Status-Based Capacity Model” is used to switch between the default tab-based capacity model and the new status-based model. This could be a game changer for Omni-Channel given the importance of capacity management to service operations and the limitations of the tab-based model.

ISV

Delete Lightning Components from Managed Packages

A long awaited capability for ISV to delete obsolete Lightning Components from released Managed Packages. From personal experience I know how easy it has been over the last few years to build a legacy of old components in the package following refactoring and transition from Aura to LWC. Note, component deletion must be enabled in the Packaging Org (via Salesforce Support Case).

First Generation Managed Package Conversion (Developer Preview)

The Summer ’20 release includes a developer preview for the conversion of first-generation managed packages to second-generation managed packages. The preview is limited to Scratch Orgs and is intended to communicate how this long-awaited capability will function in due course. Personally, I’m looking forward to bringing the benefits of second-generation packaging to previously released managed packages.

Any-org Design Considerations

The concept of any-org development is an interesting one. The strict definition, to my mind, being the development of a set of components (perhaps packaged) that are designed and coded specifically to install and function in any Salesforce org. This is typically an ISV concern, where testing and maintaining a single-code base can be highly desirable over managing a base package plus multiple extension packages, or in the worse case multiple independent packages. Either way an ISV needs to maximise the addressable market for a product whilst minimising the ongoing effort to do so. The same drivers do not apply in the single-org case, where a consultancy and/or in-house team are delivering technical components to be installed into a known Salesforce org (or multi-org estate). In the single-org case it is common practice to see technical components designed and coded for the current state of the target org(s), with no consideration to how the org(s) may evolve over time. This can often result in situations where costly technical work is required simply to activate an optional product feature, or to provide user access in another locale. In such cases the situation can often be compounded by the fact that the original development team are no longer available.

In short, in my view some degree of future-proofing should be considered in designing for the single-org model, using the techniques applied by ISVs in the any-org model.

    Any-org Design Considerations

  1. Optional Features
  2. Examples; Person Accounts, Quotes

    There are a multitude of optional product features which can be enabled directly in the Salesforce web application UI or via Salesforce support. In the majority of cases such feature activations irreversibly add new objects and fields to the Salesforce instance. From the perspective of keeping simple orgs uncluttered by objects related to unused features this makes perfect sense. From the perspective of designing for the any-org model, this approach poses a few challenges. The main challenge being that Apex code won’t compile where a static reference exists to an object (or field) that doesn’t exist in the org. There is no simple answer to this, instead a selective approach should be taken where optional features that may already be active (or could in the future be activated), that have some impact on your code are accommodated. The approach to achieving this for any-org Apex code basically involves replacing static references with Dynamic SOQL and Dynamic Apex (see coding techniques below).

  3. Multi-currency
  4. The default currency mode of a Salesforce org is single currency, the majority stay this way. It is however common to have multi-currency and perhaps advanced currency management (ACM) activated in orgs where business operations are international. Activation of multi-currency often occurs once the Salesforce org has become established, perhaps in a single region. This can be problematic where technical customisations have been added that aren’t currency aware.

    In the any-org case, all Apex code should be multi-currency aware and use Dynamic SOQL to add the CurrencyIsoCode field to all object queries involving currency fields. Additionally, currency aware logic should include checks to ensure that related transactions are the same currency, and that custom analytics are presenting data in the corporate currency (default and therefore expected behaviour for the native reporting functions). Note, the behaviour of aggregate functions involving currency fields must also be handled.

  5. Editions Support
  6. A key design decision for ISVs is the Salesforce editions to be supported by their managed package. This one has less relevance to the single-org model, unless the multi-org estate includes different editions.

    It is possible to group editions into two distinct groups;
    1. Group (or Team) Edition and Professional Edition
    2. Enterprise Edition and Unlimited Edition

    In the case of group 1 assume that standard objects such as Product, Pricebook2, PricebookEntry, RecordType do not exist and ensure no static references exist in the code. The OrganizationType field on the Organization object tells us which edition the code is executing within.

    public static Boolean isTeamOrProEdition(){
    		
    	if (isTeamOrProEdition==null){		
    		List<Organization> orgs = [select OrganizationType from Organization where Id=:UserInfo.getOrganizationId() limit 1];
    		if (orgs.size()>0)				
    			isTeamOrProEdition=(orgs[0].OrganizationType=='Team Edition' || orgs[0].OrganizationType=='Professional Edition');
    	}
    	return isTeamOrProEdition;
    }
    
  7. Internationalisation
  8. Whether an international user base is anticipated or not it is general software development best practice to externalise string literals into resource files. In the Salesforce context this means Custom Labels. A best practice here is to apply strict categorisation and a meaningful naming convention. Also ensure all literals are externalised not just labels in the UI, for example trigger error messages.

    Another consideration for i18n is the use of currency and date formatting helpers. Where UI components do not apply default formatting for an SObject field you need to handle this in code. An i18nHelper class which translates ISO locale and currency codes to date format strings and currency format strings plus symbols respectively can be very helpful.

    Useful abbreviations:
    i18n – internationalisation; development practice enabling support for localisation.
    l11n – localisation; act of localising an internationalised software product for a specific locale.

  9. Profile Permissions
  10. Visualforce pages are preprocessed for components directly bound to SObject fields where the user profile does not have CRUD or FLS permissions. In such cases the fields are not displayed or are made read-only, depending on visibility state. This comes as a surprise for many developers who assume that User Profile permissions are entirely ignored on Visualforce pages.

    reference: Enforcing_CRUD_and_FLS

    In the any-org model, where direct SObject field binding is being used in a Visualforce page, this may require a manual check during initialisation to protect the functional integrity of the page. For example, a custom page with no fields displayed and no explanation is not a great user experience, instead the page should simply inform the user they don’t have sufficient permissions, they can then take this up with their Administrators.

    private Boolean hasRequiredFLS(){    	
        // rule 1: all custom fields must be accessible.
        // rule 2: check isUpdateable on all fields where inline editing offered.
        	
        Schema.DescribeFieldResult d;
        	
        Map<String, Schema.SObjectField> siFieldNameToToken=Schema.SObjectType.SalesInvoice__c.fields.getMap();
        	
        for (Schema.SObjectField f : siFieldNameToToken.values()){    		
        	d = f.getDescribe();
        		
        	if (!d.isCustom()) continue;
        	if (!d.isAccessible()) return false;
        }
    
        d = siFieldNameToToken.get('InvoiceDate__c').getDescribe();
        if (!d.isUpdateable()) 
        	this.isInlineEditable=false;
        else {
        	d = siFieldNameToToken.get('DueDate__c').getDescribe();
        	if (!d.isUpdateable()) 
        	    	this.isInlineEditable=false;
        	else this.isInlineEditable=true;
        }	
        return true;
    }
    
    Coding Techniques

  1. Dynamic SOQL
  2. Do not statically reference objects or fields that may not exist in the org. Instead compose Dynamic SOQL queries and execute via Database.query(). With this approach, you can build the required query using flags which indicate the presence of optional feature fields such as RecordTypeId, CurrencyIsoCode etc. The Apex Language Reference provides good coverage of Dynamic SOQL. Be very careful to ensure that your composed string does not include user supplied text input – this would open up a vulnerability to SOQL injection security vectors.

    public static Id getStandardPricebookId(){
    	if (standardPricebookId==null){			
    		String q='select Id, isActive from Pricebook2 where IsStandard=true';
    		SObject p = Database.query(q);
    	
    		if (!(Boolean)p.get('IsActive')){
    			p.put('IsActive',true);
    			update p;
    		}
    		standardPricebookId=(String)p.get('Id');
    	}
    	return standardPricebookId;
    }
    
    public SalesInvoice__c retrieveSalesInvoice(String siId){
        try{
            //& Using dynamic Apex to retrieve fields from the fieldset to create a soql query that returns all fields required by the view.
            String q='select Id,Name,OwnerId';
            q+=',TotalGross__c';
    
            for(Schema.FieldSetMember f : SObjectType.SalesInvoice__c.FieldSets.invoices__Additional_Information.getFields()){
                if (!q.contains(f.getFieldPath())) q+=','+f.getFieldPath();
            }   
                
            if (UserInfo.isMultiCurrencyOrganization()) q+=',CurrencyIsoCode';			
            if (AppHelper.isPersonAccountsEnabled()) q+=',PersonEmail,PersonContactId';  
                
        	q+=',(select Id,Description__c,Quantity__c from SalesInvoiceLineItems__r order by CreatedDate asc)';     		
            q+=' from SalesInvoice__c';
            q+=' where Id=\''+siId+'\'';
                
            return Database.query(q);
        } catch (Exception e){
            throw e;
        }
    }
    
  3. Dynamic Apex
  4. Do not statically reference objects or fields that may not exist in the org. Instead use Dynamic Apex techniques such as global describes and field describes. Where a new SObject is required, use the newSObject() method as shown below, this is particularly useful for unit test data creation. The Apex Language Reference provides good coverage of Dynamic Apex, every developer should be familiar with this topic.

    public static List<SObject> createPBE(Id pricebookId, List<SObject> products){
    	SObject pbe;
    	List<SObject> entries = new List<SObject>();		
    		
    	Schema.SObjectType targetType = Schema.getGlobalDescribe().get('PricebookEntry');
    	if (targetType==null) return null;
    				
    	for (SObject p : products){
    		pbe = targetType.newSObject();
    			
    		pbe.put('Pricebook2Id',pricebookId);
    		pbe.put('Product2Id',p.Id);
    		pbe.put('UseStandardPrice',false);
    		pbe.put('UnitPrice',100);	
    		pbe.put('IsActive',true);
    		entries.add(pbe);
    	}	
    	if (entries.size()>0) insert entries;	
    	return entries;
    }
    
  5. UserInfo Methods
  6. The UserInfo standard class provides some highly useful methods for any-org coding such as;
    isMultiCurrencyOrganization(), getDefaultCurrency(), getLocale() and getTimezone(). The isMultiCurrencyOrganization() method will be frequently used to branch code specific to multi-currency orgs.

    public static String getCorporateCurrency(){			
    	if (corporateCurrencyIsoCode==null){			
    		corporateCurrencyIsoCode=UserInfo.getDefaultCurrency();
    		
    		if (UserInfo.isMultiCurrencyOrganization()){
    			String q='select IsoCode, ConversionRate from CurrencyType where IsActive=true and IsCorporate=true';
    			List<SObject> currencies = Database.query(q);
    			if (currencies.size()>0)
    				corporateCurrencyIsoCode=(String)currencies[0].get('ISOCode');				
    		}
    		return corporateCurrencyIsoCode;
    	}
    }
    
    Challenges

  1. Unit Test Data
  2. In the any-org model the creation of unit test data can be a challenge due to the potential existence of mandatory custom fields and/or validation rules. To mitigate the former, Dynamic Apex can be used to identify mandatory fields and their data type such that test data can be added (via a factory pattern of some sort). In the latter case there is no way to reliably detect a validation rule condition and as such for ISVs it is a blessing that unit tests do not actual have to pass in a subscriber org (wrong as this may be in principle). In the single-org case we can improve on this (and we have to), by adding a global Validation Rule switch-off flag in a Org Behaviour Custom Setting (see previous post) – this approach is helpful in many areas but for unit test data creation it can isolate test code from Validation Rules added post-deployment. There’s a tradeoff here between protecting unit tests versus the risk of using test data that may not adhere to the current set of Validation Rules.

  3. Unit Test Code Coverage
  4. The addition of multiple conditional code paths, i.e. branching, for the any-org case makes it challenging to achieve a high code coverage percentage in orgs which do not have the accommodated features activated. For example, unit tests executing in a single currency org, will not be run code specific to multi-currency, and therefore the code coverage drops accordingly. To mitigate this, consider adding OR conditions to IF branches which include unit test flags and perhaps Test.isRunningTest() to cover as much code as possible before leaving the branch. During coding always strive to absolutely minimise the feature-specific code – this approach will help greatly in respect to unit test coverage.

  5. QA
  6. In the any-org model, it is imperative to test your code in an org with the accommodated features activated. This will require multiple QA orgs and can increase the overall testing overhead considerably. Also, factor in the lead time required to have features activated by Salesforce support, such as multi-currency and Person Accounts.

  7. Security
  8. Dynamic SOQL queries open up the possibility of SOQL-injection attacks where user-supplied text values are concatentated into an executed SOQL query string. Always sanitise and escape data values where such code behaviour is necessary.

  9. Governor Limits
  10. The any-org model is highly contingent upon the use of limited resources such as Apex Describes. As a best practice employ a helper class pattern with cached values.

    One Approach – Future Proofing Single-org Developments

    Optional Features – selective
    Multi-currency – yes
    Editions Support – no
    i18n – yes
    Unit Test Data – yes
    Profile Permissions – yes

    The list above is my default position on the approach to take on single-org developments, this can change significantly depending on the current state of the org in terms of configuration and customisation, plus the client perspective on the evolution of their Salesforce org and attitude toward investing in future-proofing/extensibility. In the single-org, consultancy project case it’s advisable to be completely open and let the client decide if the additional X% cost is worth the value. I think the real point here is that the conversation takes place and the client has the opportunity to make an informed decision.

Patterns of Construction

I’m a big advocate of setting out the key elements of the development process succinctly but unambiguously at the start of a software development project, particularly in cases where I have no prior history of working with the development team. Such process elements typically cover environments, coding standards, technical design and review requirements, source-code control strategy etc. Perhaps the most valuable area to cover are the basic patterns of construction (or Design Patterns), without this developers are left to their own devices in naming technical components and structuring code, which can be a serious issue with maintainability and standardisation. It is incredibly time expensive and de-motivating to address this after the fact. Instead a clear picture provided upfront can provide the development team with a strong reference covering 80% of the cases, the remainder can be addressed individually during technical design. The example below provides an example of a basic construction pattern which covers naming conventions and structural concerns. Following such a pattern makes the technical implementation predictable and should improve maintainability, the latter being a obligation to take seriously on consulting projects. My rule of thumb is to try and leave the org in a state a future me would consider acceptable.

Salesforce Architect Essential Reading

For this post I started pulling together my own set of links to the whitepapers and documents I consider essential reading for any architect working in the Salesforce space. In doing so I came across the link below, where salesforce.com have already done a great job of this – bookmark this page now!

Salesforce Architect Core Resources

The Force.com Multitenant Architecture and Record Access under the hood are both excellent resources, the content of both should be fully understood by architects taking a lead role on Salesforce projects of any size.

The one missing link from the referenced page is to the Integration patterns document

Don’t forget to check out the Advanced Apex Programming book by Dan Appleman also, there is some great content in this title highly relevant to architects not just Apex coders.