Archive for the 'Salesforce' Category

How to run a code club – without computers!

Here is a link to a post that Martin Gale and I wrote on the Salesforce Foundation blog.
http://www.salesforce.org/how-to-run-a-code-club-without-computers/

Advertisements

Upgrading a Salesforce App from Classic to Lightning Experience by Sam Garforth

Introduction

A while ago, I wrote a Salesforce app to be used as example of the kinds of apps that can be built on the Salesforce platform. It is called Shared Rides and is a carpooling app to offer and accept shared rides via Chatter. You earn green mile credits which can be tracked on a dashboard. It is available as a Salesforce App Cloud Quick Start App and can be downloaded as a managed package from here.

Salesforce has recently introduced a new look and feel called Lightning Experience (LEX) along with associated tooling to help you develop apps that use it. It is a component based framework (Model View View Controller), as opposed to the Model View Controller framework that Classic uses. I decided to check whether my app worked in the new interface and make any changes necessary take advantage of all the benefits of being a Lightning app.

There are some great training modules in Trailhead. The trail Migrate to Lightning Experience tell you a lot of what you need to know to understand LEX and, in particular, the unit Upgrade a Classic App to a Lightning App in module Lightning Apps gives the recommended steps for upgrading.

The Standard Steps

So here are the steps I took:

  1. Create a fresh org to develop and test the app one
  2. Install the app package that I wanted to upgrade into the new org.
  3. Enable Lightning Experience for the org and switch into it.image001image003image005
  4. From Setup, enter App in the Quick Find box, then select App Manager.
  5. image007

  6. Find your app in the list. In my case, It’s called Shared Rides.
  7. Click the pulldown from the app row, and select Upgrade.
  8. image011

  9. Leave the suggested name as-is, e.g. “Shared Rides Lightning” and click Upgrade.
  10. image013

  11. The Classic app is copied and upgraded for Lightning Experience. There are now two versions of the app: a Classic version, and a Lightning version. After you upgrade it, the Classic app is no longer accessible in Lightning Experience via the App Launcher. You’ll still see the Classic app in the apps list, but with the Visible in Lightning column deselected.image015
  12. After you upgrade a Classic app, the two versions of the app must be managed separately. Future changes you make to the Classic app won’t be reflected in the Lightning version of the app, and vice versa.
  13. So now the Lightning app is available in the App Launcher and it even has the data from the old version
    image017image019

    Adding the Enhancements

    However, it’s not taking advantage of the great enhancements that Lightning apps can offer. So we go through the following steps.

    1. Back in the Lightning Experience App Manager, find the Lightning app in the list.
    2. Click  from the Lightning app row, and select Edit.
    3. image022

    4. Update the description if needed as the app description displays alongside the icon in the App Launcher, so it’s a great way to tell your users what the app is for, but keep it brief.
    5. In the App Branding section, change the Primary Color to something appropriate and also upload an image.image024image026
    6.  

      After saving, click the Select Items tab, and remove the Home tab from the Selected Items list by selecting it and then clicking the ‘<’ button between the two columns. Then ensure you’re happy with the other items and click ‘Save’ and .Done’.image028

      Now, when you go into the App Launcher the app should be there with the correct branding. The changes may not appear immediately as the page is cached. You may need to force a reload of the browser.image030

      That brings us to the end of the official instructions. Now comes the testing.

      Further Tidying

      image032

      The new version of the app has quick action buttons for ‘New Contact’ and ‘New Opportunity’. These aren’t relevant to a car sharing app so I need to remove them.

      Also, there is a pane with functionality for activity, new task, log a call etc which is not relevant.

      So click on ‘edit page’

      image036

      This takes you into Lightning App Builder. Highlight the Activity pane.image038

      and click the x in the top right corner of the paneimage040

      Ideally you would want to change the layout of the page (template) but in my case this option in not available. Perhaps it’s inherited.

      Now we need to remove the ‘New Contact’ and ‘New Opportunity’ buttons so click on the pane that contains these i.e. the Highlights Panel.

      image041

      On the right hand side it tells you which page layout you are using for the actions. Click through to it, in my case I click on “Location Layout”.

      Scroll down the page layout setup page to the Lightning Experience section and click on the ‘override the predefined actions’ hyperlink.

      image043

      Remove the actions you don’t want by dragging them up to the Lightning Actions palette.

      image045

      then click ‘Save’.

      Go back to the Lightning App Builder page and click ‘save’ to save the other changes and then select ‘Activate’.

      Select what level you want to assign the page as the default for. I selected ‘Org Default’.

      image047image049

      Click ‘Back’ to go out of the App Builder back to the page.  I can see that my changes have taken effect.

      image051

      These changes only affected the Location page. I still needed to go through the same steps to adjust the layout and actions on the other pages.

      JavaScript Button

      In the Classic version of my app I had an “Accept Ride” button which someone could click to say that they would like to share a journey that had been offered.image053

      This was a JavaScript button.

      image055image057

      JavaScript buttons are not supported in LEX so instead I needed to create a Lightning Component Quick Action button. So, these are the steps I took:

      Create the Lightning Component

      1. Open the Dev Consoleimage059
      2. Create a new Lightning Component.
      3. Give the component the nameAcceptRide.
      4. I selected Lightning Record Page and Lightning Quick Action.image061
      5. Then I replaced the contents of the component with the following:

      Add a Component Controller

      1. Click the Controller button in the Dev Console.
      2. Replace the contents of the controller with the following and then save it
      ({
      handleAcceptRide: function(component, event, helper) {
      var sharedRide_id = component.get("v.recordId");
      var action = component.get("c.getSharedRide");
      action.setParams({
      "sharedRideID": sharedRide_id
      });
      action.setCallback(this, function(response) {
      var res = response.getReturnValue();
      var resultsToast = $A.get("e.force:showToast");
      if (res) {
      resultsToast.setParams({
      "title": "Ride Accepted",
      "message": "You have been added to the Shared Ride riders list."
      });
      } else {
      resultsToast.setParams({
      "title": "Error",
      "message": "Sorry, you could not be added to the Shared Ride riders list."
      });
      }
      resultsToast.fire();
      $A.get("e.force:refreshView").fire();
      var dismissActionPanel = $A.get("e.force:closeQuickAction");
      dismissActionPanel.fire();
      });
      $A.enqueueAction(action);
      }
      })

      Create the Apex Controller

      1. In the Dev Console, create a new Apex Class,File > New > Apex Class.
      2. Give it a name ofAcceptRideApexController.
      3. I replaced the contents with the following and saved it.
      public class AcceptRideApexController {
      @AuraEnabled
      public static Boolean getSharedRide (Id sharedRideID) {
      PSE_Shared_Rides__c rideToUpdate = [SELECT Id, Number_of_spaces__c FROM PSE_Shared_Rides__c WHERE Id = :sharedRideID];
      Decimal spacesleft = rideToUpdate.Number_of_spaces__c;
      if (spacesleft  0 ) rideToUpdate.Number_of_spaces__c = spacesleft - 1;
      update rideToUpdate;
      return true;
      }
      }
      

      The original javascript looked like this:

      
      /* */
      {!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")}
      try{
      var rideToUpdate = new sforce.SObject("PSE_Shared_Rides__c");
      var spacesleft = "{!PSE_Shared_Rides__c.Number_of_spaces__c}";
      rideToUpdate.Id = "{!PSE_Shared_Rides__c.Id}";
      if (spacesleft == 4) rideToUpdate.Ride_Sharer_4__c = "{!$User.Id}";
      if (spacesleft == 3) rideToUpdate.Ride_Sharer_3__c = "{!$User.Id}";
      if (spacesleft == 2) rideToUpdate.Ride_Sharer_2__c = "{!$User.Id}";
      if (spacesleft == 1) rideToUpdate.Ride_Sharer_1__c = "{!$User.Id}";
      if (spacesleft > 0 ) rideToUpdate.Number_of_spaces__c = spacesleft - 1;
      var result = sforce.connection.update([rideToUpdate]);
      if(result[0].success === "true"){
      location.reload();
      }else{
      alert(
      "An Error has Occurred. Error: " +
      result[0].errors.message
      );
      }
      }catch(e){
      alert(
      "An Unexpected Error has Occurred: Error: " + e
      );
      }
      1. Save the file.
      2. Ensure that the Apex controller is referenced in the tag in AcceptRide.cmp file i.e. controller=”AcceptRideApexController”

      Make the component a Quick Action

      1. Ensure that force:lightningQuickActionWithoutHeader is an implements attribute of the component.
      2. Save all the files.
      3. Navigate back to the Object Manager and choose the Shared Ride object.
      4. Scroll down to the Buttons, Links and Actions section.
      5. Click the New Action button.
      6. Select Lightning Component as the Actions Type.
      7. Select c:AcceptRide as the Lightning Component and set the height to 400px.
      8. Type Accept Ride in the Label field and Accept_Ride becomes the name.
        image063
      9. Click Save.
      10. Navigate back to Shared Ride object page and click the Shared Ride Layout in the Page Layouts section.
      11. Click the override the predefined actions link in the Salesforce1 and Lightning Experience Actions section.
      12. Click the Salesforce1 & Lightning Actions link in the Property Layout box.
      13. Drag the Accept Ride tile to the Salesforce1 and Lightning Experience Actions section and place it as the first item. Remove the buttons that you don’t need.
      14. image065

      15. Click the Save button in the Shared Ride Layout box.
      16. Navigate back to a Shared Ride Record page. If the changes don’t appear then force refresh the page.image067
      17. Click the Accept Ride Quick Action button to accept the offer.
      1. In my case I have different page layouts for different record types and I change record type each time someone accepts a ride. I needed to change each of these layouts.

      Create the Test Class

      So now, although the app is working I want to be able to package it and share it to other users and orgs. For this I need a test class for the new apex code. Here is my new test Apex Class:

      @isTest(seeAllData=true)
      private class PSE_TestAcceptRide {
      static testMethod void myUnitTest() {
      Test.startTest();
      PSE_Location__c l1 = new PSE_Location__c();
      l1.Location__c = 'SO53 1JA';
      insert l1;
      PSE_Location__c l2 = new PSE_Location__c();
      l2.Location__c = 'EC2N 4AY';
      insert l2;
      PSE_Route__c r = new PSE_Route__c();
      r.Start_Location__c = l1.Id;
      r.Destination__c = l2.Id;
      r.Name = 'Chandlers Ford to SFT';
      insert r;
      update r;
      PSE_Shared_Rides__c s = new PSE_Shared_Rides__c();
      s.Name = 'Test Ride';
      s.Route__c = r.Id;
      s.Time__c = Datetime.newInstance(2015, 10, 17);
      s.Number_of_spaces__c = 3;
      try
      {
      insert s;
      update s;
      AcceptRideApexController.getSharedRide(s.Id);
      AcceptRideApexController.getSharedRide(s.Id);
      AcceptRideApexController.getSharedRide(s.Id);
      AcceptRideApexController.getSharedRide(s.Id);
      AcceptRideApexController.getSharedRide(s.Id);
      }
      catch(System.DMLException e)
      {
      e.getMessage();
      }
      Test.stopTest();
      }
      }

      Package The New App

      Once the app is working it needs to be packaged if you intend to share it as a package. So go to the Package Manager and select ‘New’. Give it a name and save it and select ‘Add’ to add the components.

      Start with component type App and select both versions of your app. At first I just selected the Lightning one but then it will only work in LEX. You need the classic version too for people who don’t have LEX.

      I also had to manually add the Apex test class and the AcceptRideController.js

      Select Upload and fill in the fields.

      Conclusion

      This was my personal experience of upgrading a packaged app with a JavaScript button to Lightning Experience. I hope you found it useful. I would welcome any comments on improvements I could make to my process and also other learnings you have had upgrading other apps.

Salesforce Application Lifecycle Management

A Simple Introduction to the Architecture of Salesforce Platform Encryption

The architecture of the Salesforce Platform Encryption solution is described here.

I thought I’d have a go at writing a simplified version in a way that’s easy for me to understand, starting with the encryption of the data and then moving out to key management.

Encryption Basics

In this post I’m going to assume a certain amount of knowledge about encryption but let’s start with some simplified basics.

Symmetric encryption is where you have the same key to both encrypt (for privacy) and decrypt the data. This is the fastest way to encrypt/decrypt but it is also the easiest to crack and if you lose the key then you’re in trouble e.g. if you encrypt something with the key and someone else wants to decrypt it then they need to have the same key and then there’s nothing to stop them imitating you.

Symmetric Encryption

Public key encryption (PKI) addresses this issue using key pairs. The key that does the encryption is different to the key that does the decryption. The key that does the encryption (the public key) can be made public, anyone can use it to encrypt but only the holder of the other half of the pair (the private key) will be able to decrypt it.

Public Key Encryption

The same public key technology can be used for signing (for authentication). Someone can use their private key to sign something and people with the corresponding public key will be able to verify that the sender used that private key. Public key encryption is sometimes called asymmetric because the encrypting/decrypting keys are different.

Public Key Authentication

Asymmetric security is more secure than symmetric because you don’t have to share the encrypting key and it takes longer to crack but it also takes longer to encrypt and so sometimes the performance impact can be too high. So, typically, a combination of the two is used. The symmetric key is used for the encryption/decryption but its distribution and storage is protected using the public key technology.

Salesforce Security

Salesforce has always been a very secure platform, using a range of services such as encryption of the data in transit, two factor authentication, verification of login address, profiles, permissions and penetration tests. They are now adding to this a new feature called Platform Encryption which allows customers to optionally encrypt some fields at rest i.e. while they are stored in the Salesforce database.

How does Salesforce Platform Encryption Work?

Salesforce uses a symmetric encryption key to encrypt the customer data that it stores. (The symmetric encryption used is AES with 256-bit keys using CBC mode, PKCS5 padding, and random initialization vector (IV).) The symmetric mode gives the performance benefit but means that the key needs to be closely protected. For this reason the Data Encryption Key (which is also the decryption key) is never transmitted or even written to disk (persisted). It is created/derived in the Salesforce platform and never leaves. It is created in a component of the platform called the Key Derivation Server.

Platform Encryption Architecture

So this brings us to the question of how is it created, and how can we ensure that it’s the same when it’s recreated to do the decryption? Also, given that this is a multi-tenant environment, what is the customer specific component? The answer is that the encryption key is derived/created from a combination of a Salesforce component and customer/tenant specific component. These are called secrets. Sometimes they are also referred to as key fragments.

The encryption key is generated from the master secret (Salesforce component) and the tenant secret (customer component) using PBKDF2 (Password-Based Key Derivation Function 2). The derived data encryption key is then securely passed to the encryption service and held in the cache of an application server.

Key Derivation Server

The Write Process

So, to write an encrypted record, Salesforce retrieves the Data Encryption Key from the cache and performs the encryption. As well as writing the encrypted data into the record it also stores the IV and the id of the tenant secret.

The Read Process

Similarly, to decrypt the data Salesforce reads the encrypted data from the database and if the encryption (decryption) key is not in the cache then it needs to derive it again using the associated tenant secret, and then it decrypts using the key and the associated IV.

So, we’ve established that the data can’t be accessed without the data encryption key and that this key can’t be accessed without the master and tenant secrets, but how do we know that the secrets are secure?

Generation of Secrets

Remember that for this discussion, there is one master secret for Salesforce itself, and a tenant secret and key derivation server for each customer. Actually these secrets are regularly replaced, which is why we need to keep their ids.

The master secret is created by a dedicated air gapped HSM. It is then encrypted using the key derivation server’s public key (tenant wrapping key) and signed with the HSM’s private key (master wrapping key) and transported to the key derivation server where it is stored.

Master HSM

The tenant secret is created on the key derivation server, with a different HSM. This is initiated by the customer who connects using their usual transport level security. It is then encrypted with the tenant wrapping key (public key) and stored in the database. The tenant secret never leaves the key derivation server and can only be accessed using the tenant wrapping key private key which also never leaves the key derivation server.

The Transit Key

A unique transit key is generated on the a Salesforce Platform application server each time it boots up. The transit key is used to encrypt the derived data encryption key before it’s sent back from the key derivation server to the encryption service. The transit key is a symmetric key but itself is encrypted with an asymmetric key, created by the master HSM, to get it to the key derivation server.

That’s Enough For Now

There’s a lot more that can be explained. There are more keys for more parts of the process. There are more distribution processes, and processes for updating the keys and keeping the system working using updated keys. There are processes for archiving data and keys, and for destroying the archives. But for now, I think I’ve understood enough to be comfortable with the way platform encryption works and the extra layer of security that it provides. Please let me know if you spot any glaring errors. For more detail please see the original document or suggest future posts.

Connecting Salesforce to a Heroku Database

A popular use of Salesforce is as a front end system of engagement application, using a lookup integration to the more static system of record data in a back-end such as SAP. I wanted to set up a demo to show this but I didn’t have access to an SAP environment so I decided to simulate the back-end by creating a Postgres database in Heroku.

I decided to use some publicly available open data on properties as the database and for this to be looked up dynamically from the account record in Salesforce.

Here are the steps I went through.

First get a Heroku account. Go to heroku.com and ‘sign up for free’

image001

Then login.
On my computer I installed node.js from https://nodejs.org/

And npm from https://github.com/npm/npm

And the Heroku toolbelt from https://devcenter.heroku.com/articles/getting-started-with-nodejs#set-up

Once installed, you can use the heroku command from your command shell. Log in using the email address and password you used when creating your Heroku account:

image003

Execute the following commands to clone the sample application:

image004

You now have a functioning git repository that contains a simple application as well as apackage.json file, which is used by Node’s dependency manager.

image005

Now we create an app on Heroku, which prepares Heroku to receive the source code.

image006

When you create an app, a git remote (called heroku) is also created and associated with your local git repository.

Heroku generates a random name (in this case glacial-sierra-8855) for your app.

The package.json file determines both the version of Node.js that will be used to run your application on Heroku, as well as the dependencies that should be installed with your application. When an app is deployed, Heroku reads this file and installs the appropriate node version together with the dependencies using the npm install command.

Run this command in your local directory to install the dependencies, preparing your system for running the app locally:

image007

Now we add a free Heroku Postgres Starter Tier dev database to the app.

image008

Now we need to add Postgres to the path:

image009

I found some sample data of properties here.

Download the CSV file to your current directory and delete first line so there’s only one header.

Now add an index column; so in Excel insert a new column, put 1 and 2 as the first two entries and then highlight these and drag the mouse down so that it auto populates the other records with increasing indices:

image010

image012

Now we create the database table in the same format as the spreadsheet.

image013

Run a select statement to check it worked:

image014

Set the date format to be UK format like the spreadsheet.

image015

Then copy the spreadsheet into the database:

image016

So now we have an app, a database and a table. In order to access it from Salesforce we need to request that the database be enabled as an external object by raising a ticket at https://help.heroku.com/

You will need to provide Support with the application name (in this case glacial-sierra-8855).

Once external object support has been enabled go to https://connect.heroku.com/

and set the app as a Heroku Connect Instance and get the username, password and url for it.

Select the ’emptyproperties’ data source to share:

image017

Now, to connect to this from Salesforce you need a Salesforce org with Lightning Connect/OData enabled. If you request a developer environment from here then you will get this functionality automatically https://developer.salesforce.com/signup

In your Salesforce org:

  • Click Setup (upper right corner)
  • Click Develop > External Data Sources (left navigation)
  • Click New External Data Source
  • Enter OrderDB as the Label. As you click or tab away from the label field, the Name field should automatically default to OrderDB.
  • Select Lightning Connect: OData 2.0 as the Type.

(OrderDB doesn’t have to be the name, choose something meaningful for you).

Enter the url, username and password from heroku

image019

  • click ‘validate and sync’
  • and select the ‘emptyproperties’ table
  • and select ‘sync’

image021

Then click into the ’emptyproperties’ external object

image023

You should be able to see that all the fields have been picked up from the database:

image025

You can now create a Custom Tab to Easily Access properties

  • Click Setup (upper right corner)
  • Click Create > Tabs
  • Click the New button next to Custom Object Tabs.
  • Select properties as the Object.
  • Click the selector next to Tab Style and choose whichever style you like.
  • Click Next.
  • Click Next to accept the default tab visibility settings.
  • Choose the apps that you want the tab to be included in.
  • Click Save.

image027

Now there will be a new tab:

image029

Click on ‘go’ to view all. All the records are now accessible in the database by clicking through the external ids.

image031

Now go back to ‘external objects’ where you were just before creating the tab.

Now we want to make the index an external lookup. Click ‘edit’ next to index.

image033

Select “change field type”:

image035

  • Select External Lookup Relationship and click Next. An external lookup relationship can link any object to an external object.
  • Select emptyproperties as the value of Related To and click Next.

image037

  • Enter4 as the value for Length and click Next.
  • Enable theVisible checkbox to make the relationship visible to all profiles, and click Next.
  • Click Save to accept the defaults – you definitely want an ‘OrderDetails’ related list on the Orders page layout!

Now go to the properties tab and select an external id and the full property detail is displayed:

image039

[Edit: if the property details don’t show up the you will need to go to the user’s Profile and enable READ in the FLS of your External Data Object fields.]

Now let’s assign properties to accounts. Se we’ll edit the account record and add a property

  • Setup, customize, accounts, fields
  • New custom field
  • External lookup
  • Select the properties but change the field label just to Property
  • Step through and save it
  • Now when we go to an account we see an empty field for Property

image041

If we edit the field and put an index in it becomes a link to the Heroku properties database

image043

Now the property also shows a link back to the account from the property:

image045

And that’s it. We now have accounts in the Salesforce CRM system with real-time lookups to the system of record in a Heroku database.


My twitter feed