When Salesforce is life!

Tag: Salesforce Page 10 of 24

Setting up SFDX Continuous Integration using Bitbucket Pipelines with Docker image

Ivano Guerini is a Salesforce Senior Developer at Webresults, part of Engineering Group since 2015.
He started my career on Salesforce during his university studies and based his final thesis on it.
He’s passionate about technology and development, in his spare time he enjoys developing applications mainly on Node.js.


In this article, I’m going to walk you through the steps to set up CI with Salesforce DX.

For this, I decided to take advantage of Bitbucket and it’s integrated tool Bitbucket Pipelines.

This choice is not made after a comparison between the various version control systems and CI tools but is driven by some business needs for which we decided to fully embrace the cloud solutions and in particular the Atlassian suite of which Bitbucket its part.

What is Continuous Integration?

In software engineering, continuous integration (often abbreviated to CI) is a practice that is applied in contexts in which software development takes place through a versioning system. It consists of frequent alignment from the work environments of the developers to the shared environment.

In particular, it is generally assumed that automatic tests have been prepared that developers can execute immediately before releasing their contributions to the shared environment, so as to ensure that the changes do not introduce errors into the existing software.

Let’s apply this concept to our Salesforce development process using sfdx.

First of all, we have a production org where we want to deploy and maintain the application than typically we have one or more sandboxes such as for UAT, Integration Test and development.

With sfdx, we also have the concept of scratch org, disposable and preconfigured organizations where we, as developers, can deploy and test our work before pushing them into the deployment process.

In the image below you can see an approach to the CI with Salesforce DX. Once a developer have finished a feature he can push into the main Developer branch, from this the CI take place creating a scratch Org to run automated tests, such as Apex Unit Test or even Selenium like test automatisms. If there is no error the dev can create a pull request moving forward in the deployment process.

In this article, I’ll show you how to set up all the required tools and as an example, we will only set up an auto-deploy to our Salesforce org on every git push operation.

Toolbox

Let’s start with a brief description of the tools we’re going to use:

  • Git – is a version control system for tracking changes in files and coordinating work on those files across the team. All metadata items, whether modified on the server or locally, are tracked via GIT. This provides us with a version history as well as traceability.
  • Bitbucket – is a cloud-based GIT server from Atlassian used for hosting our repository. It provides a UI to navigate the GIT repository and has many additional features like pull requests. These are used for approving and merging changes.
  • Docker – provides a way to run applications securely, packaged with all its dependencies and libraries. So, we will be using it to create an environment for running sfdx commands.
  • Bitbucket Pipelines – is an add-on for Bitbucket cloud that will allow us to kick off deployments and validations when updates are made to the branches in Bitbucket.

If you have always worked in Salesforce, then it’s quite possible that Docker containers sound alien to you. So what is Docker? In simple terms, Docker can be thought of as a virtual machine in the cloud. Docker provides an environment in the cloud where applications can run. Bitbucket Pipelines support Docker images for running the Continuous Integration scripts. So, instead of installing sfdx in your local system, you’d now specify them to be installed in your Docker image, so that our CI scripts can run.

Create a developer Org and enable the DevHub

We made a brief introduction about what CI is and the tools we’re going to use, now it’s time to get to the heart of it and start configuring our tools. Starting from our Salesforce Org.

We are going to enable the devhub to be able to work with sfdx and we are going to set up a connected app that allows us to handle the login process inside our docker container.

For this article, I created a dedicated developer Org in order to have a clean environment.

We can do this simply filling out the form from the Salesforce site: https://developer.salesforce.com/signup and complete the registration process.

In this way, we will obtain a new environment on which to perform all the tests we want.

Let’s go immediately to enable the DevHub: Setup → Development → DevHub click on the Enable DevHub toggle.

Once enabled it can’t be disabled but this is a requirement to be able to work with SFDX.

Now you can install the sfdx cli tool on you computer.

Create a connected app

Now that we have our new org and the sfdx cli installed, we can run sfdx commands that makes it easy for us to manage the entire application development life cycle from the command line, including creating scripts that facilitate automation.

However, our CI will run in a separate environment where we haven’t a direct control, such as for the logging. So we will need a way to manage the authorization process inside the docker container when your CI automation job runs.

To do this we’ll use the OAuth JSON Web Token (JWT) bearer flow that’s supported in the Salesforce CLI, this OAuth flow gives you the ability to authenticate using the CLI without having to interactively login. This headless flow is perfect for automated builds and scripting.

Create a Self-Signed SSL Certificate and Private Key

For a CI solution to work, you’ll generate a private key for signing the JWT bearer token payload, and you’ll create a connected app in the Dev Hub org that contains a certificate generated from that private key.

To create an SSL certificate you need a private key and a certificate signing request. You can generate these files using OpenSSL CLI with a few simple commands.

If you use Unix Based System, you can install the OpenSSL CLI from the official OpenSSL website.

If you use Windows instead, you can download an installer from Shining Light Productions, although there are plenty of alternatives.

We will follow some specific command to create a certificate for our needs, if you want to better understand how OpenSSL works, you can find a handy guide in this article.

If you are not familiar with OpenSSL you can find a good

  1. Create a folder on your PC to store the generated files
    mkdir certificates
  2. Generate an RSA private key
    openssl genrsa -des3 -passout pass:<password> -out server.pass.key 2048
  3. Create a key file from the server.pass.key file using the same password from before:
    openssl rsa -passin pass:<password> -in server.pass.key -out server.key
  4. Delete the server.pass.key:
    rm server.pass.key
  5. Request and generate the certificate, when prompted for the challenge password press enter to skip the step:
    openssl req -new -key server.key -out server.csr
  6. Generate the SSL certificate:
    openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

The self-signed SSL certificate is generated from the server.key private key and server.csr files.

Create the Connected App

The next step is to create a connected app on Salesforce that includes the certificate we just created.

  1. From Setup, enter App Manager in the Quick Find box, then select App Manager.
  2. Click New Connected App.
  3. Enter the connected app name and your email address:
    1. Connected App Name: sfdx ci
    1. Contact Email: <your email address>
  1. Select Enable OAuth Settings.
  2. Enter the callback URL:
  3. http://localhost:1717/OauthRedirect
  4. Select Use digital signatures.
  5. To upload your server.crt file, click Choose File.
  6. For OAuth scopes, add:
    • Access and manage your data (api)
    • Perform requests on your behalf at any time (refresh_token, offline_access)
    • Provide access to your data via the Web (web)
  7. Click Save

Edit Policies to avoid authorization step

After you’ve saved your connected app, edit the policies to enable the connected app to circumvent the manual login process.

  1. Click Manage.
  2. Click Edit Policies.
  3. In the OAuth policies section, for Permitted Users select Admin approved users are pre-authorized, then click OK.
  4. Click Save.

Create a Permission Set

Lastly, create a permission set and assign pre-authorized users for this connected app.

  1. From Setup, enter Permission in the Quick Find box, then select Permission Sets.
  2. Click New.
  3. For the Label, enter: sfdx ci
  4. Click Save.
  5. Click sfdx ci | Manage Assignments | Add Assignments.
  6. Select the checkbox next to your Dev Hub username, then click Assign | Done.
  7. Go back to your connected app.
    1. From Setup, enter App Manager in the Quick Find box, then select App Manager.
    2. Next to sfdx ci, click the list item drop-down arrow (), then select Manage.
    3. In the Permission Sets section, click Manage Permission Sets.
    4. Select the checkbox next to sfdx ci, then click Save.

Test the JWT Auth Flow

Open your Dev Hub org.

  • If you already authorized the Dev Hub, open it:
    sfdx force:org:open -u DevHub
  • If you haven’t yet logged in to your Dev Hub org:
    sfdx force:auth:web:login -d -a DevHub

Adding the -d flag sets this org as the default Dev Hub. To set an alias for the org, use the -a flag with an argument to set an alias.

To test the JWT auth flow you’ll use some of the information that we asked you to save previously. We’ll use the consumer key that was generated when you created the connected app (CONSUMER_KEY), the absolute path to the location where you generated your OpenSSL server.key file (JWT_KEY_FILE) and the username for the Dev Hub (HUB_USERNAME).

  1. On the command line, create these three session-based environment variables:
    export CONSUMER_KEY=<connected app consumer key>
    export JWT_KEY_FILE= ../certificates/server.key
    export HUB_USERNAME=<your Dev Hub username>


    These environment variables facilitate running the JWT auth command.
  2. Enter the following command as-is on a single line:
    sfdx force:auth:jwt:grant –clientid ${CONSUMER_KEY} –username ${HUB_USERNAME} \ –jwtkeyfile ${JWT_KEY_FILE} –setdefaultdevhubusername

This command logs in to the Dev Hub using only the consumer key (client ID), the username, and the JWT key file. And best of all, it doesn’t require you to interactively log in, which is important when you want your scripts to run automatically.

Congratulations, you’ve created your connected app and you are able to login using it with the SFDX CLI.

Set up your development environment

In this section we will configure our local environment, creating a remote repository in Bitbucket and linking it to our local sfdx project folder.

If you are already familiar with these steps you can skip and pass directly to the next section.

Create a Git Repository on Bitbucket

If you don’t have a bitbucket account, you can create a free one registering to the following link: https://bitbucket.org/account/signup/

Just insert your email and follow the first registration procedure.

Once logged in you will be able to create a new git repository from the plus button on the right menu.

You will be prompted to a window like the following, just insert a name for the repository, in my case I’ll name it: sfdx-ci, leaving Git selected as Version Control System.

We’re in but our repo is totally empty, Bitbucket provides some quick commands to initialize our repo. Select the clone command:

git clone https://[email protected]/username/sfdx-ci.git

Move to your desktop and open the command line tool and paste and execute the git clone command. This command will create a folder named like the Bitbucket repository already linked to it as a remote branch.

Initialize SFDX project

Without moving from our position, execute the sfdx create project command:
force:project:create -n sfdx-ci

Using the -n parameter with the same name of the folder we just cloned from git.

Try deploy commands

Before we pass to configure our CLI operations let’s try to do it in our local environment.

First of all, we must create our sfdx project.

The general sfdx deployment flow into a sandbox or production org is:

  1. Convert from source form to metadata api form
    sfdx force:source:convert -d <target directory>
  2. Use the metadata api to deploy
    sfdx force:mdapi:deploy -d <same directory as step 1> -u <username or alias>

These commands will be the same we are going to use inside our Bitbucket Pipelines, You can try in your local environment to see how they work.

Set up Continuous Integration

In previous sections, we talked mostly about common Salesforce project procedures. In the next one, we are going deeper in the CI world. Starting with a brief introduction to Docker and Bitbucket Pipelines.

Lastly, we’ll see how to create a Docker image with SFDX CLI installed and how to use it in our pipeline to run sfdx deploy commands.

Docker

Wikipedia defines Docker as

an open-source project that automates the deployment of software applications inside containers by providing an additional layer of abstraction and automation of OS-level virtualization on Linux.

In simpler words, Docker is a tool that allows developers, sys-admins, etc. to easily deploy their applications in a sandbox (called containers) to run on the host operating system i.e. Linux. The key benefit of Docker is that it allows users to package an application with all of its dependencies into a standardized unit for software development.

Docker Terminology

Before we go further, let me clarify some terminology that is used frequently in the Docker ecosystem.

  • Images – The blueprints of our application which form the basis of containers.
  • Containers – Containers offer a logical packaging mechanism in which applications can be abstracted from the environment in which they actually run.
  • Docker Daemon – The background service running on the host that manages building, running and distributing Docker containers. The daemon is the process that runs in the operating system to which clients talk to.
  • Docker Client – The command line tool that allows the user to interact with the daemon.
  • Docker Hub – A registry of Docker images. You can think of the registry as a directory of all available Docker images.
  • Dockerfile – A Dockerfile is a simple text file that contains a list of commands that the Docker client calls while creating an image. It’s a simple way to automate the image creation process. The best part is that the commands you write in a Dockerfile are almost identical to their equivalent Linux commands.

Build our personal Docker Image with SFDX CLI installed

Most Dockerfiles start from a parent image. If you need to completely control the contents of your image, you might need to create a base image instead. A parent image is an image that your image is based on. It refers to the contents of the FROM directive in the Dockerfile. Each subsequent declaration in the Dockerfile modifies this parent image.

Most Dockerfiles start from a parent image, rather than a base image, this will be our case, we will start from a Node base image.

Create a folder on your machine and create a file named Dockerfile, and paste the following code:

FROM node:jessie
RUN apk add --update --no-cache git openssh ca-certificates openssl curl
RUN npm install sfdx-cli --global
RUN sfdx --version
USER node

Let’s explain what this code means, in order:

  1. We use a Node base image, this image comes with NPM and Node.js preinstalled. This one is the official Node.js docker image, and jessie indicate the last available version;
  2. Next, with the apk add command we are going to install some additional utility tools mainly git and openssl to handle sfdx login using certificates;
  3. Lastly using npm command we install the SFDX CLI tools;
  4. Just a check for the installed version;
  5. And finally the USER instruction sets the user name to use when running the image.

Now we have to build our image and publishing it to the Docker Hub so to be ready to use in our Pipelines.

  1. Create an account on Docker Hub.
  2. Download and install Docker Desktop. If on Linux, download Docker Engine – Community
  3. Login to Docker Hub with your credentials. 
    docker login –username=yourhubusername –password=yourpassword
  4. Build you Docker Image
    docker build -t <your_username>/sfdxci
  5. Test your docker image locally:
    docker run <your_username>/sfdxci
  6. Push your Docker image to your Docker Hub repository
    docker push <your_username>/sfdxci

Pushing a docker image on the Docker Hub will make it available for use in Bitbucket pipelines.

Bitbucket Pipelines

Now that we have a working Docker Image with sfdx installed we can continue configuring the pipeline, that’s the core of our CI procedure.

Bitbucket Pipelines is an integrated CI/CD service, built into Bitbucket. It allows you to automatically build, test and even deploy your code, based on a configuration file in your repository. Essentially, it creates containers in the cloud for you.

Inside these containers, you can run commands (like you might on a local machine) but with all the advantages of a fresh system, custom configured for your needs.

To set up Pipelines you need to create and configure the bitbucket-pipelines.yml file in the root directory of your repository, if you are working with branches,  to be executed this file must be present in each branch root directory.

A bitbucket-pipelines.yml file looks like the following:

image: atlassian/default-image:2
 pipelines:
   default:
     - step:
         script: 
           - echo "Hello world default"
   branches:
     features/*:
         - step:
             script: 
               - echo "Hello world feature branch"

There is a lot you can configure in the bitbucket-pipelines.yml file, but at its most basic the required keywords are:

  • image – the Docker image that will be used to create the Docker Container, You can use the default image (atlassian/default-image:latest), but using a personal one is preferred to avoid time consumption during the installation of required tools (e.g. SFDX CLI), To specify an image, use image: <your_dockerHub_account/repository_details>:<tag>
  • pipelines – contains all your pipeline definitions.
  • default – contains the steps that run on every push, unless they match one of the other sections.
  • branches – Specify the name of a branch on which run the defined steps, or use a glob pattern (to learn more about the glob patterns, refer to the BitBucket official guide).
  • step – each step starts a new Docker container with a clone of your repository, then runs the contents of your script section.
  • script – a list of cli commands that are executed in sequence.

Other than default and branches there are more signals keyword to identify what step must run, such as pull-request, but I leave you to the official documentation, we are going to use only these two.

Keep in mind that each step in your pipeline runs a separate Docker container and the script runs the commands you provide in this environment with the repository folder available.

Configure SFDX deployment Pipelines

Before configuring our pipeline, let’s review for a moment the steps needed to deploy to a production org using sfdx cli.

First of all we need to login into our SF org, to do so we have created a Salesforce Connected App to allow us logging in without any manual operation, simply using the following command:

sfdx force:auth:jwt:grant --clientid  --username  --jwtkeyfile keys/server.key --setdefaultdevhubusername --setalias sfdx-ci --instanceurl 

As you can see there are three parameters that we have to set in this command line:

  • CONSUMER_KEY
  • SFDC_PROD_USER
  • SFDC_PROD_URL

Bitbucket offer a way to store some variables that can be used in our pipelines in order to avoid hard-coded values.

Under Bitbucket repository Settings → Pipelines → Repository Variables create three variables and fill them in with the data at your disposal.

Another parameter required by this command is the server.key file, in this case I simply added it in my repository under the keys folder.

It’s not a good practice and I will move it in a more secure position, but for this demonstration it’s enough.

Now you are logged in, you need only two sfdx commands to deploy your metadata. One to convert your project in a metadata API format and one to deploy in the sf org:
sfdx force:source:convert -d mdapi
sfdx force:mdapi:deploy -d mdapi -u <SFDC_PROD_USER>

Like the login command we are going to use a Pipeline Variable to indicate the target org username under the -u parameter.

OK, now that we know how to deploy a SFDX proggect we can put all this into our pipeline.

Move to the root of our sfdx project and create the bitbucket-pipelines.yml file and paste the following code (replace the image name with your own Docker image):

image: ivanoguerini/sfdx:latest
 pipelines:
  default:
 step:
    script: 
      - echo $SFDC_PROD_URL
      - echo $SFDC_PROD_USER
      - sfdx force:auth:jwt:grant --clientid $CONSUMER_KEY --username $SFDC_PROD_USER --jwtkeyfile keys/server.key --setdefaultdevhubusername --setalias sfdx-ci --instanceurl $SFDC_PROD_URL
      - sfdx force:source:convert -d mdapi
      - sfdx force:mdapi:deploy -d mdapi -u $SFDC_PROD_USER 

Commit and push this changes to the git repository.

Test the CI

OK we have our CI up and running, let’s do a quick test.

In your project create a new apex class and put some code in it. Then commit and push your changes.

git add .
git commit -am “Test CI”
git push

As we said the pipeline will run on every push into the remote repository, you can check the running status under the Pipelines menu. You will see something like this:

As you know, the mdapi:deploy command is asynchronous so to check if there was some errors during the deploy you have to run the following command mdapi:deploy:report specifying the jobId or if you prefer you can check the deploy directly in the salesforce Org under Deployment section.

Conclusions

With this article I wanted to provide you with the necessary knowledge to start configuring a CI using the BitBucket Pipelines.

Obviously what I showed you is not enough for a CI that can be used in an enterprise project, there is still a lot to do.

Here are some starting points to improve what we have seen:

  1. Store the server.key in a safe place so that it is not directly accessible from your repository.
  2. Manage the CI in the various sandbox environments used
  3. For the developer branch, consider automating the creation a scratch org and running Apex Unit Tests.

But, I leave this to you.

10 signs you’re an amazing Salesforce Developer

I recently joined other Salesforce influencers in contributing to Mason Frank’s ‘Ask The Experts’ series, where I wrote about my ten best tips to become an amazing Salesforce Developer. Here’s a quick summary below and link to the full article, I hope you enjoy!

10 signs you’re an amazing Salesforce Developer

“Am I the best Salesforce Developer I can be?”

This is a question all Salesforce Developers should be asking themselves. If you said “Yes”, well… you don’t need to read this post as you may be in the “Olympus” of coders.

If your answer is “No”, welcome my friend, keep reading this post. I have some tips for you, based on my experiences, that may lead you to the right trail.

I’ve always felt like I’ve never achieved anything to the top level, and I guess this drove me to overcome my limits and achieve a lot in my personal and professional life.

If you are in the circle of developers that believe they can empower their skills day after day, you are using a mental process that I call “Continuous Self-Improvement” (CSI, isn’t it cool? I guess I’ve not invented anything, but I love giving names to stuff). I even call it the “John Snow syndrome”, because your student mentality means you’re a coder who feels like they “know nothing”.

Keep reading on Mason Frank blog…

Salesforce Summer ’19 Platform Release: quick highlights

Our week’s trailblazer is Claudio Marzorati, who will be listing some of his favorite Summer’19 Salesforce platform release.

Claudio is a Senior Salesforce Developer @ Sintegra s.r.l. (Milan). He worked with different retails that allowed him to increase his technical background on several aspects.
From analysis, to development, to the direct relationship with the customer, nothing is left to chance.
Other passions are running and travels!


Summer 19′ hass finally arrived and in our org all changes are going to be applied.

Here I summarize some of the most important features that can impact your org.

Lightning URL parameters have been namespaced

Finally they have been release the funtiality that forces URL parameters to be namespaced.
So if you add ?foo=bar to the URL, it will get auto-stripped.
But if you add ?c__foo=bar to the URL, it will persist.

Keep Record Context When Switching from Salesforce Classic to Lightning Experience

When you switch from Salesforce Classic to Lightning Experience, you land on the same page in Lightning Experience, if it exists. If the same page doesn’t exist in Lightning Experience, you are redirected to your default landing page, which is determined by the org default or your customizations.

Choose from Two Record View Options

Now you have two record page view default options. Choose between the current view—now called Grouped view—and the new Full view. In Setup, enter Record Page Settings in the Quick Find box, and select Record Page Settings.


Full view (1) displays all details and related lists on the same page. Grouped view (2), the original Lightning Experience record view, focuses on specifics by grouping information across tabs and columns.

Search Picklist Fields in List Views

You don’t have to manually pick through your list views to find the picklist values you’re looking for. List view search now includes picklists in your query results. Dependent picklists and picklists with translated values aren’t searchable.

Continuation

Finally we can use the Continuation pattern from an Aura component or a Lightning web component. Continuation class
in Apex are used to make a long-running request to an external web service Process the response in a callback method. An asynchronous callout made with a continuation doesn’t count toward the Apex limit of 10 synchronous requests that last longer than five seconds. Therefore, you can make more long-running callouts and integrate your component with a complex back-end API. In Lightning-Web-Component now we can use
@salesforce/apexContinuation in order to provides access to an Apex method that use the Continuation.

Aura Components

There a lot of improvements expecially in LWC and below I report the most used in my develop.

lightning:recordEditForm

density option

Sets the arrangement style of fields and labels in the form. Accepted values are compact, comfy, and auto. The default is auto, which lets the component dynamically set the density according to the user’s Display Density setting and the width of the form.

onerror handler event changed

You can now return the error details when a required field is missing using event.getParam("output").fieldErrors. To display the error message automatically on the form, include lightning:messages immediately before or after the lightning:inputField components.  

lightning:inputField

reset function added

Resets the form fields to their initial values.

There are few deprecated component in force and ui: force:recordEdit, force:recordView, ui:input (all types), ui:button, ui:menu (all types), ui:output (all types), ui:spinner.

Web Component

Salesforce is spending a lot of time and resources in improving this new components. There are a lot of new functionalities added and below I report the most significant.

lightning-input

autocomplete function added

Controls autofilling of the field. This attribute is supported for email, search, tel, text, and url input types.

date-style (or time-style) function added

The display style of the date when type='date/time' or type='datetime'. Valid values are short, medium, and long. The default value is medium. The format of each style is specific to the locale. This attribute has no effect on mobile devices. 

lightning-input-field

reset function added

Resets the form fields to their initial values.

lightning-record-edit-form

density option

Sets the arrangement style of fields and labels in the form. Accepted values are compact, comfy, and auto. The default is auto, which lets the component dynamically set the density according to the user’s Display Density setting and the width of the form.

onerror handler event changed

You can now return the error details when a required field is missing using event.getParam("output").fieldErrors. To display the error message automatically on the form, include lightning:messages immediately before or after the lightning:inputField components.  

Minor UX Improvement

They have changed the UX provided. Some example for recent records and for the related list are below reported.

More comprehensive layout for Recent Records
Related Lists have more impact for users

More details can be found at
https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/salesforce_release_notes.htm.

[Salesforce] Handle encryption and decryption with Apex Crypto class and CrypoJS

One of the easiest Javascript libraries for encryption I usually adopt is CryptoJS, quick setup and good support for most algorithms.

But I got an headache trying to make it talk with Salesforce, this was due to my relatively low encryption-topics training but also to a specific way Salesforce handles encryption.

I was surprised that none has ever had the same need before.

I’m not going to explain how I came up to this solution (one of the reasons is that I already forgot it…as I always say, my brain is a cool CPU but with a low amount of storage), but I’ll just give you the way I solved encrypted data exchange between a Javascript script (whether it is client or server side) and Salesforce.

In Apex encrypting and decrypting a string is quite easy:

//encrypt
String algorithmName = 'AES256';
Blob privateKey = Crypto.generateAesKey(256);
Blob clearText = Blob.valueOf('Encrypt this!');
Blob encr = Crypto.encryptWithManagedIV(algorithmName, privateKey, clearText);
system.debug('## ' + EncodingUtil.base64encode(encr));
//decrypt
Blob decr = Crypto.decryptWithManagedIV(algorithmName, privateKey, encr );
System.debug('## ' + decr.toString());

This could be an example of the output:

## Lg0eJXbDvxNfLcFMwJm6CkFtxy4pWgkmanTvKLcTttQ=
## Encrypt this!

For encryption noobs out there, the encrypted string changes every time you run the script.

The string if first encrypted with the AES256 algorithm and then decrypted using the same secret key (generated automatically by Salesforce).

All is done through Crypto class’ methods:


Valid values for algorithmName
are:

– AES128
– AES192
– AES256

These are all industry standard Advanced Encryption Standard (AES) algorithms with different size keys. They use cipher block chaining (CBC) and PKCS5 padding.

Salesforce HELP

PKCS5 padding is a subset of the more general PKCS7, that is supported by CryptJS, so it still works.

The only thing that is not clearly stated here (at least for my low storage brain) is that this method uses an Initialization Vector (IV, that is used together with the private key to generate the proper encryption iterations) which has a fixed 16 Bytes length.

Also, the IV is included within the encrypted string: this is the key point.

To encrypt and decrypt using the following method the CryptoJS must be aware of the first 16 Bytes of the IV and append it to (if we are encrypting from JS to Salesforce) or extract it from (if we are decrypting in JS from a Salesforce encrypted string) the encrypted string.

This is what I came up with after a bit of research (you have to deal with binary data when encrypting, that’s why we use Base64 to exchange keys and encrypted strings).

//from https://gist.github.com/darmie/e39373ee0a0f62715f3d2381bc1f0974
var base64ToArrayBuffer = function(base64) {
    var binary_string =  atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
};
//from //https://gist.github.com/72lions/4528834
var appendBuffer: function(buffer1, buffer2) {
    var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
    tmp.set(new Uint8Array(buffer1), 0);
    tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
    return tmp.buffer;
};
//from //https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string
var arrayBufferToBase64 = function( arrayBuffer ) {
    return btoa(
        new Uint8Array(arrayBuffer)
            .reduce(function(data, byte){
                 return data + String.fromCharCode(byte)
            }, 
        '')
    );
},
//Encrypts the message with the given secret (Base64 encoded)
var encryptForSalesforce = function(msg, base64Secret){
    var iv = CryptoJS.lib.WordArray.random(16);
    var aes_options = { 
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
        iv: iv
    };
    var encryptionObj  = CryptoJS.AES.encrypt(
        msg,
        CryptoJS.enc.Base64.parse(base64Secret),
        aes_options);
    //created a unique base64 string with  "IV+EncryptedString"
    var encryptedBuffer = base64ToArrayBuffer(encryptionObj.toString());
    var ivBuffer = base64ToArrayBuffer((encryptionObj.iv.toString(CryptoJS.enc.Base64)));
    var finalBuffer = appendBuffer(ivBuffer, encryptedBuffer);
    return arrayBufferToBase64(finalBuffer);
};
//Decrypts the string with the given secret (both params are Base64 encoded)
var decryptFromSalesforce = function(encryptedBase64, base64Secret){
    //gets the IV from the encrypted string
    var arrayBuffer = base64ToArrayBuffer(encryptedBase64);
    var iv = CryptoJS.enc.Base64.parse(arrayBufferToBase64(arrayBuffer.slice(0,16)));
    var encryptedStr = arrayBufferToBase64(arrayBuffer.slice(16, arrayBuffer.byteLength));

    var aes_options = { 
        iv: iv,
        mode: CryptoJS.mode.CBC
    };

    var decryptObj  = CryptoJS.AES.decrypt(
        encryptedStr,
        CryptoJS.enc.Base64.parse(base64Secret),
        aes_options
    );

    return decryptObj.toString(CryptoJS.enc.Utf8);
};

By sharing the Base64 of the Salesforce generated secret (using the method Crypto.generateAesKey(256) ) between your JS client and Salesforce, you can store and exchange encrypted data with a blink of an eye.

Salesforce DX Setup – Everything You need to Know

Let’s talk about a great new addition of the Spring’19 platform release to the
Salesforce Dev world, the Lightning Web Components framework, with our guest blogger Priscilla Sharon, Salesforce Business Solution Executive for DemandBlue.

DemandBlue is in the business of helping its customers maximize their Salesforce investment through predictable outcomes. As we thrive in an era of cloud-based Infrastructure, Platform and Software services, DemandBlue has pioneered “Service-as-a-Service” through a value-based On Demand Service model that drives bottom-line results. They foster innovation through “Continuous Engagement and On Demand Execution” that offers their customers Speed, Value and Success to achieve their current and future business objectives.


Salesforce DX Setup – Since inception, one of Salesforce’s core philosophies and the Big Idea has been to make building easy. Software should not be complex to install, set up, or customize. In fact, you shouldn’t have to even install software – it should be available to you at the click of a button – This declarative approach of Salesforce brought an end to complex and traditional methods of software development that even non-tech executives including business analysts and managers could slickly build line-of-business applications in a few clicks. However, while Salesforce was democratizing application development through clicks-not-code approach and ushering in the era of citizen programmer, there were other players who were strengthening their appeal to the traditional developer. With nuanced business requirements, modeling complex domains require more flexibility than clicks-not-code affords. Traditional methods of development weren’t dead after all.

As a result, Salesforce’s marketing and development efforts wanted to cater to the traditional developer with the introduction of Salesforce DX, a revolutionary product in the Salesforce App Cloud that allows users to develop and manage Salesforce apps throughout the entire platform in a more direct and efficient way. Used primarily by developers, Salesforce DX setup enables users to have true version control that allows them to have a better control over collaboration, auditing, disaster control and more.

Take a deeper dive into the comprehensive blog that gives you in-depth insights on how you can enable Salesforce DX environment and truly maximize its unique benefits.

Your 12 Step Salesforce DX Setup Guide

1.     Set up your project

Salesforce DX introduces a new project structure for your org’s metadata (code and configuration), your org templates, your sample data, and all your team’s tests. Store these items in a version control system (VCS) to bring consistency to your team’s development processes. Retrieve the contents of your team’s repository when you’re ready to develop a new feature.

2.     Salesforce DX Setup – Authorize the Developer Hub org for the project

During Salesforce DX setup, the Dev Hub org enables you to create, delete, and manage your Salesforce scratch orgs. After you set up your project on your local machine, you authorize with the Dev Hub org before you create a scratch org.

For this, you need to login to Dev/Sandbox Org from CLI

Run the force:auth:web:login CLI command on a directory where code for deploy to sfdx will be available.

sfdx force:auth:web:login –d

or

sfdx force:auth:web:login --setdefaultdevhubusername --setalias {ALIAS HERE}

NOTE: Login must be a valid login to your Dev/Sandbox Org and with Admin permissions.

3.     Configure your local project

The project configuration file sfdx-project.json indicates that the directory is a Salesforce DX setup project. The configuration file contains project information and facilitates the authentication of scratch orgs and the creation of second-generation packages. It also tells the Salesforce CLI where to put files when syncing between the project and scratch org.

4.     Configure your local project

After you create the scratch org definition file, you can easily spin up a scratch org and open it directly from the command line.

a)      Create the scratch org

  • Create a scratch org for development using a scratch org definition file. The scratch org definition defines the org edition, features, org preferences, and some other options.
  • Specify scratch org definition values on the command line using key=value pairs
  • Create a scratch org with an alias
  • Create a scratch org for user acceptance testing or to test installations of packages
  • Indicate that this scratch org is the default
  • Specify the scratch org’s duration, which indicates when the scratch org expires (in days)

b)      Open the org

  • To open the scratch org: sfdx force:org:open -u <username/alias>
  • To open the scratch org in Lightning Experience or open a Visualforce page, use the –path parameter: sfdx force:org:open –path lightning

c)       Set default user

Copy the username and enter the following command to set the defaultusername:

sfdx force:config:set defaultusername={SET THIS TO NEW SCRATCH ORG’S USERNAME FROM THE ABOVE  COMMAND}

d)      Display All Orgs

Run the following command to confirm the default Dev Hub [marked with (D)] and Active Scratch Org [marked with (U)]:

sfdx force:org:list --all

5.        Push the source from your project to the scratch org

To push changed source to your default scratch org:

sfdx force:source:push

To push changed source to a scratch org that’s not the default, you can indicate it by its username or alias:

sfdx force:source:push --targetusername [email protected]
sfdx force:source:push -u [email protected]
sfdx force:source:push -u MyGroovyScratchOrg

Selecting Files to Ignore During Push. It’s likely that you have some files that you don’t want to sync between the project and scratch org. You can have the push command ignore the files you indicate in .forceignore.

If Push Detects Warnings. If conflicts have been detected and you want to override them, here’s how you use the power of the force (overwrite) to push the source to a scratch org.

sfdx force:source:push –forceoverwrite

6. Salesforce DX Setup – Develop the app

a.       Create Source Files from the CLI

To add source files from the Salesforce CLI, make sure that you are working in an appropriate directory.

Execute one of these commands.

apex:class:create
apex:trigger:create
lightning:app:create
lightning:component:create
lightning:event:create
lightning:interface:create
lightning:test:create
visualforce:component:create
visualforce:page:create

b.       Edit Source Files

To edit a FlexiPage in your default browser—for example, to edit the Property_Record_Page source—execute this command.

sfdx force:source:open -f Property_Record_Page.flexipage-meta.xml

7.     Pull the source to keep your project and scratch org in sync

After you do an initial push, Salesforce DX tracks the changes between your local file system and your scratch org. If you change your scratch org, you usually want to pull those changes to your local project to keep both in sync.

During development, you change files locally in your file system and change the scratch org using the builders and editors that Salesforce supplies. Usually, these changes don’t cause a conflict and involve unique files.

By default, only changed source is synced back to your project.

To pull changed source from the scratch org to the project:

sfdx force:source:pull

To pull source to the project if a conflict has been detected (read more):

sfdx force:source:pull –forceoverwrite

8.     Salesforce DX Setup – Run tests

When you’re ready to test changes to your Salesforce app source code, you can run Apex tests from the Salesforce DX CLI. Apex tests are run in your scratch org.

You can also execute the CLI command for running Apex tests (force:apex:test:run) from within third-party continuous integration tools, such as Jenkins.

9.     Export The Package.xml

Export package.xml file into the temporary directory. Type the commands below in the root folder of your Salesforce DX project:

sfdx force:mdapi:retrieve -r ./temp -u {TARGETUSERNAME} -k  {SFDC PROJECT SOURCE LOCATION}\src\package.xml

10.       Convert Source code to Salesforce  DX

Convert the source code to the Salesforce Developer Experience project structure by running the following command:

sfdx force:mdapi:convert --rootdir temp --outputdir force-app

11.        Track Changes Between the Project and Scratch Org

To view the status of local or remote files:

sfdx force:source:status 

12. Salesforce DX Setup – Sync up

Sync the local version with the version deployed to Scratch Org for every change and test the changes on the Scratch Org by repeating the above steps. Once the testing is completed, we need to convert the source from Salesforce DX format to the Metadata API format. This is done by running the following command:

sfdx force:source:convert --outputdir {OUTPUT DIRECTORY HERE}

Copy the modified metadata files from this output location to the actual source location where the metadata files are downloaded from Dev/Sandbox Org to deploy the files to the server.

[Salesforce / Back To Basics] How to make a field required based on selected picklist value

For this new Back To Basics post, welcome Akashdeep Arora, Salesforce Evangelist/Consultant at HyTechPro. He started Salesforce journey in 2015. 3X Salesforce Certified Professional, 4X Trailhead Ranger, 5X Trailhead Academy Certified.Founder of #BeASalesforceChamp campaign.


Well, Astro turned 5 recently. So, what’s better than writing something related to Astro. As we all know, when you need a guide, Astro’s there for you.

#Astroturns5 #AppyBirthday #BeASalesforceChamp

Albeit, it sounds easy but still many Developers/Admins gets stuck when they want to make a field required based on one value selected from picklist field. Now, you must be thinking the way to achieve it.

We have different ways to make a field required:

  • Required Checkbox while field creation
  • Page Layout
  • Validation Rule
  • Using custom code (Visualforce Page, Lightning component, Apex Trigger to say a few)

But our scenario is little bit different as we want to make it required based on criteria, i.e. selected picklist value must be Astro.

Yay, let’s begin the fun without any delay.

The easiest way to achieve it is to use a validation rule. We have two fields:

  • Salesforce Character (a picklist field with values Appy, Astro, Codey, Cloudy and Einstein)
  • Astro Mom (a text field).

Here, we go.

After saving the rule, it will look like below:

Well, it’s time for testing. Testing is very necessary for anything. (Wink)

Let’s create a record without giving value in the Astro Mom text field and Select “Astro” from Salesforce Character picklist field like below:

As soon as you click on the Save button, it will give you an error “Please enter Astro Mom“.

Wohoooo, our validation rule is perfect it seems. Now, let’s provide the name of Astro Mom in the text field and click on Save button.

Hurrayyy, the record is saved this time. This is how you can make any field required based on selection of a picklist field value.

Don’t compare yourself with others.

You are best.

#Beasalesforcechamp

[Salesforce / LWC] Autocomplete magic with HTML Datalist

Ivano Guerini is a Salesforce Senior Developer at Webresults (Engineering Group) since 2015.
He started my career on Salesforce during his university studies and based his final thesis on it.
He’s passionate about technology and development, in his spare time he enjoys developing applications mainly on Node.js.


The <datalist> element is a new tag available in the HTML5.
This element can be used to create native autocomplete dropdowns without using complex JS and DOM manipulation for data filtering.

As you may have experienced, autocomplete picklist is a usefull component commonly used in forms to facilitate users in finding the correct value in case of very large lists of values.

In this article post, you’re going to learn how to use the datalist element to create a autocomplete dropdowns as Lightning Web Component.

For the TL;DR guys over there, this is the repo.

Let’s get started.

First let’s see how it works in an HTML page.

Simply write this code in an HTML page and we obtain a autocomplete dropdown like the below.

<input list="countries">

<datalist id="countries">
	<option>Italy</option>
	<option>Spain</option>
	<option>France</option>
	<option>USA</option>
	<option>England</option>
	<option>Belgium</option>
	<option>Brazil</option>
	<option>Mauritius</option>
	<option>Colombia</option>
	<option>Portugal</option>
	<option>Russia</option>
	<option>Mauritania</option>
</datalist>

Simple like that, all without any JS code.

Now let’s try to do the same in Salesforce.
Open your favorite IDE, and create a new LWC component, naming it ‘autocomplete’.

The html template we report the same code written above.

<template>
    <input id="input" name="input" list="countries" class="slds-input" type="text" />
    <datalist id="countries">
		<option>Italy</option>
		<option>Spain</option>
		<option>France</option>
		<option>USA</option>
		<option>England</option>
		<option>Belgium</option>
		<option>Brazil</option>
		<option>Mauritius</option>
		<option>Colombia</option>
		<option>Portugal</option>
		<option>Russia</option>
		<option>Mauritania</option>
	</datalist>
</template>

If we try to execute this component, we will see that it does not work as we would expect.
This is because the link between the input and the datalit is managed through the Id attribute. But as Salesforce reminds us:

The IDs that you define in HTML templates may be transformed into globally unique values when the template is rendered. If you use an ID selector in JavaScript, it won’t match the transformed ID.

To overcome this problem we can take advantage of a few lines of JS code, hooking up to the rerenderCallback.
Then in the Javascript controller we write the following function:

renderedCallback() {
     let listId = this.template.querySelector('datalist').id;
     this.template.querySelector("input").setAttribute("list", listId);
}

This code simply searches for our Datalist element and retrieves the ID generated by Salesforce, and consequently updates the input list attribute with the new Value.

Again the rendered callback can run a lot of times, but our code must be executed only once. To do it we can use a private attribute to know if the renderedCallback has been already executed:

initialized = false;

renderedCallback() {
        if (this.initialized) {
            return;
        }
        this.initialized = true;
        let listId = this.template.querySelector('datalist').id;
        this.template.querySelector("input").setAttribute("list", listId);
    }

Now our LWC component will work as autocomplete dropdown.

Let’s evolve it a bit, using dinamic options and decorating it with a label ad other attributes.

The HTML template will tranform like this:

<template>
    <label class="slds-form-element__label" for="input">
        <template if:true={required}>
            <abbr class="slds-required" title="required">* </abbr>
        </template>
        {label}
    </label>
    <div class="slds-form-element__control">
        <input id="input" name="input" list="valueList" placeholder={placeholder} required={required} class="slds-input" type="text"  />
        <datalist id="valueList" class="">
            <template for:each={values} for:item='item'>
                <option key={item.key} value={item.value}>{item.value}</option>
            </template>
        </datalist>
    </div>
</template>

In the JS controller we handle this values with @api decorator.

import { LightningElement, api } from 'lwc';

export default class Autocomplete extends LightningElement {
    @api values;
    @api label = '';
    @api name = '';
    @api required;
    @api placeholder = '';
    initialized = false;

    renderedCallback() {
        if (this.initialized) {
            return;
        }
        this.initialized = true;
        let listId = this.template.querySelector('datalist').id;
        this.template.querySelector("input").setAttribute("list", listId);
    }

}

Full repo here.

[ORGanizer] Giraffe release is live: few steps closer to release 1.0!

More then 3 months from the last Reindeer Release say hello to the ORGanizer for Salesforce Giraffe Release (0.6.8.4).

Why a Giraffe, you ask?

Like a Giraffe points its head up to the sky, the Giraffe Release points toward release 1.0, when we’ll finally go out of beta, closing an almost 3 years old path since its first release 0.1 in September 2016.

I’ve worked a lot on stability and bug fixing in these months, reviewing tens of issues and suggestions, provided by my beloved ORGanusers who support my day by day work.

A brand new sponsor

It’s also a pleasure to introduce you to our next sponsor NativeVideo for the next months, starting from the current release!

Founded in London in 2018, NativeVideo is on a mission to bring businesses and people closer together with the power of Video.

NativeVideo is the platform that, once installed from the AppExchange, enables video recording and browsing as a native functionality inside Salesforce.

The company has already released two “extension packages” that customise the solution to 2 specific use cases:

  • LeadGenVideo demand generation / deal nurturing thanks to video messages that include both classic webcam video recording and screen recording
  • TalentVideo designed for those companies that use Salesforce for their recruitment and adds video interviews to the process, with a very well designed workflow and collaboration features.

NativeVideo customers have customised the NativeVideo platform and the use of Video to their needs on other use cases, like Service – screen recording sent by the service representative to answer questions and solve bugs, CPQ – a walkthrough screen recording video where the offer is explained when it is sent to the customer, Customer feedback / testimonial – inviting customers to answer a few questions on video to provide feedback on the service and results they are receiving, and many more.

Jump to NativeVideo landing page to say hello and thank them for helping the ORGanizer to keep the hard work going!

What’s new with the Giraffe?

First we have new consolidated limits for logins storage:

Approaching to release 1.0 the number of logins that can be stored with the free edition of the ORGanizer will gradually decrease. The number of logins will be limited in the free edition but all the other features will always be kept free.

Pro version can be purchased from the Chrome Web Store and now using Promo Codes (only available on Chrome version as of now):

A promo code is strictly related to the user email address and has an expiration date, and conveys the same enhanced limits of the Pro version in-app purchase.

Why a promo code?

To allow companies to mass purchase ORGanizer licenses or for promotions or free trials.

New permissions required

The following permissions are now required:

  • Know your email address: needed to get your email address for Promo Code verification (your email address is never sent to anyone but only used to validate your codes, if any)
  • Read and change data on a number of websites:
    • force.com, salesforce.com, visualforce.com, documentforce.com, salesforce-communities.com: main Salesforce domains
    • organizer-api.enree.co: Promo Code verification endpoint. This endpoint is called only after Promo code validation (if any)

And more and more enhancements and bug fixes

Read the change log for the whole list of what’s inside this new release, and see you in the next release!

This blog has been verified by Rise: Rb4a7093bc3979124c781aae186805e25

[Salesforce / Lightning Web Components] Build Lightning fast Salesforce Apps

Let’s talk about a great new addition of the Spring’19 platform release to the
Salesforce Dev world, the Lightning Web Components framework, with our guest blogger Priscilla Sharon, Salesforce Business Solution Executive for DemandBlue.

DemandBlue is in the business of helping its customers maximize their Salesforce investment through predictable outcomes. As we thrive in an era of cloud-based Infrastructure, Platform and Software services, DemandBlue has pioneered “Service-as-a-Service” through a value-based On Demand Service model that drives bottom-line results. They foster innovation through “Continuous Engagement and On Demand Execution” that offers their customers Speed, Value and Success to achieve their current and future business objectives.


Salesforce launched Lightning Web Components as part of Spring ’19 pre-release to enable a quicker and easier way to program applications on the Salesforce Lightning platform. It engages modern Javascript innovations such as web components, custom elements, shadow DOM and more. Lightning Web Components is the Salesforce implementation of Lightweight frameworks built as per the web standards. It provides specialized salesforce services in addition to the core stack, such as Base Lightning Components, Lightning Data Service, User Interface API, etc.

Read on to discover how the Lightning Web Components fuses Web components programming model with Salesforce metadata and services to deliver unparalleled performance and productivity.

With Lightning Web Components, we are giving developers a standards-driven JavaScript model for building enterprise apps on Lightning. Every time we release a new platform capability we see an acceleration of innovation in our 150,000 customer base, and we are excited to see what our community of developers will do with Lightning Web Components.

Mike Rosenbaum, EVP of Product, Salesforce

Why Lightning Web Components

Lightning Web Components is like a newer version of Lightning Components with additional features.

  • Knowledge Domain – Developers who know Web Components are familiar with Salesforce Lightning Web Components out-of-the-box. Aura is proprietary, so the better you know the web standards, the better you’ll have of skills that can be used outside Salesforce.
  • Better Execution – Lightning Web Components leverages built-in browser security features from Web Components standards, which reduces the level of custom coding, which means they run faster and are more consistent in how they ensure security. Moreover, events have a limited scope, so there is lesser processing required handling events.
  • New Security Features – It gives better CSS isolation, DOM isolation, script isolation and limited event scope that facilitate a more consistent component design.
  • ES6+ – We have a better support for ES6 and ES7 that is not available in Aura. This enables you to do more with less coding. This also transpires code to work in IE 11 and other browsers which were not supported earlier.
  • More Consistent Data Binding – The not so user-friendly two-way data binding has been eliminated. This pushes developers to coordinate the way in which data moves between components. It also means that data binding will work as expected, without any unforeseen problems from Aura.
  • Mixins – You can even import accessible methods from other components and import specific Apex methods from multiple classes. Moreover, the Apex methods can be cached for improved performance.

What Lightning Web Components means for Developers and Customers

Cutting-Edge Advantages of Lightning Web Components

Boosted Performance – Developing Lightning Web Components does not involve complex abstractions to run on the browser, providing better performance to end users.

Ease of Use – Post development, the admins can deploy Lightning Web components with just clicks, not code to the applications.

Standardized – Salesforce Lightning Web Components is built on ES6+ that provides developers with modern and advanced JavaScript features.

How to create a Lightning Web Components framework?

LWC (Lightning Web Components) cannot be created directly from the developer console. You need to set up Salesforce DX to create a Lightning component. After the SFDX setup, you need to do a few more things:

  • Sign-up for development org
  • Get your Salesforce DX plugin updated with the latest release (Spring’19). Run the command below in your terminal or command prompt.
  • Command:
sfdx update  
  • Once you finish this process, follow the trailhead link to set up the basic project and create a basic Lightning Web Component

Transition from Aura Components to Lightning Web Components

Developers using Aura framework to build lightning components can continue to work on it as the Aura components will continue to function like before. However, the new components can be created using Aura or the Lightning Web Component framework. For future developments, it is best if you use the Lightning Web Components.

Lightning Web Components Availability

Lightning Web Components are available for users since February 2019 in Enterprise, Unlimited, Performance and Developer editions.

For more information, check out the official Salesforce page on Lightning Web Components.

[Salesforce / Apex] Handling constants on classes

Few days ago I was thinking about optimizing the use of constants (usually of String type) inside projects to avoid proliferation of public static final String declarations on various classes (with a limited control over duplicates) but giving at the same time developers a way to increase readability of constants in their code.

The reason for this post is that I want to know your opinion on this strategy, that on my eyes appear elegant and clear but may bring some drawbacks.

public class Constants{ 
	private static ObjectName_Constants objectNameConstants; 

	public static ObjectName_Constants ObjectName{  
		get { 
			if(objectNameConstants == null){ 
				objectNameConstants = new ObjectName_Constants(); 
			} 
			return objectNameConstants; 
		} 
	} 

	public class ObjectName_Constants{ 
		public String CustomField_AValue  { get { return 'aValue'; } } 
		public String RecordType_ADevName  { get { return 'aDevName'; } } 
	} 
} 

The class is basically shaped as follows:

This brings to a cool looking:

String myDevName = Constants.ObjectName.RecordType_ADevName;

This way we have the following pros:

  • Clear hirearchy for constants
  • More readable constants names (they are all getters but are used as constants, so no need for upper case)
  • Heap space is allocated on constants only if they are actually used
  • Centralized place for common constants

And these are the cons:

  • More quantity of Apex used to write a constants

I’m curious to get some feedbacks.

Page 10 of 24

Powered by WordPress & Theme by Anders Norén