143
Salesforce Developer Workshop

Elevate london dec 2014.pptx

Embed Size (px)

Citation preview

Page 1: Elevate london dec 2014.pptx

Salesforce Developer Workshop

Page 2: Elevate london dec 2014.pptx

Speakers

Keir BowdenCTO, BrightGen

@bob_buzzard

Peter ChittumDeveloper Evangelist

@pchittum

Page 3: Elevate london dec 2014.pptx

Safe Harbor

Safe harbor statement under the Private Securities Litigation Reform Act of 1995:

This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.

The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of intellectual property and other litigation, risks associated with possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-Q for the most recent fiscal quarter ended July 31, 2012. This documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site.

Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.

Page 4: Elevate london dec 2014.pptx

A nationwide network of volunteer-led after school coding clubs for children aged 9-11

Find how to get involved and what resources are available during the lunch break from Michael Mentessi Code Clubs community manager

Page 5: Elevate london dec 2014.pptx

Salesforce University Promo

• EMEA Region only•• 15% Discount to all ELEVATE attendees.

• For any public Salesforce University developer workshop

• Must book and attend by week commencing 12 Jan, 2015

http://developer.salesforce.com

Page 6: Elevate london dec 2014.pptx

Go Social!

@salesforcedevs

Salesforce Developers

+Salesforce Developers

Salesforce Developers

Salesforce Developers

Page 7: Elevate london dec 2014.pptx

▪ SSID: elevate

▪ Password: Salesforce1

WIFI

Page 8: Elevate london dec 2014.pptx

▪ Platform Overview

▪ Creating a Data Model

▪ Creating an Application

▪ Writing Apex Classes

▪ Accessing Data using SOQL

▪ Writing Triggers

▪ Writing Visualforce Pages

▪ Writing Controller Extensions

▪ Using JavaScript in VF Pages

▪ Using the REST APIs

▪ Unit Testing

▪ Batching and Scheduling

Agenda

Page 10: Elevate london dec 2014.pptx

Salesforce is a Platform Company. Period.-Alex Williams, TechCrunch

1BAPI Calls Per

Day6B

Lines of Apex4M+

Apps Built on the Platform

72BRecords Stored

Salesforce1 Platform

Page 11: Elevate london dec 2014.pptx

Salesforce Platform is the Fastest Path from Idea to App

IdeaBuild App

Idea

buy & setup hardware

install complex software

define user access

build & test security

make it mobile &

social

setup reporting & analytics

build app

Traditional Platforms6-12 Months?

App

App

Page 12: Elevate london dec 2014.pptx

Salesforce1 Platform Services

Salesforce1 Platform

Force.com Heroku Exact Target

Salesforce1 Platform APIs

Salesforce1 App

SalesCloud

ServiceCloud

MarketingCloud AppExchange Custom

AppsPartnerApps

Page 13: Elevate london dec 2014.pptx

Platform Services

CoreServices

ChatterMulti-

language

Translation Workbench

Email Service

sAnalytics

CloudDatabase

ScheemaBuilder Search

Visualforce

MonitoringMulti-tenant

Apex

Data-levelSecurity

Workflows

APIs

Mobile Services

Social APIs

Analytics APIs

Bulk APIs

Rest APIs

Metadata APIs

Soap APIs

Private AppExchange

Custom Actions

Identity Mobile Notifications

Tooling APIs

Mobile Packs

Mobile SDK

Offline Support

Streaming APIs

Geolocation

ET 1:1 ET Fuel

Heroku1

Heroku Add-Ons

Sharing Model

ET API

Multi Tenant Architecture

Page 14: Elevate london dec 2014.pptx

Salesforce1 Mobile App

▪ Salesforce on your phone

▪ Customizable by– Users

– Admins

– Developers

▪ Supports– Objects

– Visualforce

– Canvas

Page 15: Elevate london dec 2014.pptx

Two Approaches to Development

Visualforce PagesVisualforce Components

Apex ControllersApex Triggers

Metadata APIREST APIBulk API

Formula FieldsValidation Rules

Workflows and Approvals

Custom ObjectsCustom FieldsRelationships

Page LayoutsRecord Types

User Interface

Business Logic

Data Model

Declarative Approach Programmatic Approach

Page 16: Elevate london dec 2014.pptx

Customers Have Built Apps Across Every Department

Employee Collaboration

Employee Intranet

Recruiting & Stock Plans

Recruiting

Healthy Workplace

Employee Intranet

60 HR Apps + Intranet

Employee Intranet

Asset Management

Product Lifecycle Management

Inventory Management

Field Services

Field Services

Field Inspections

Brand Auditing

Customer Facing Site

Digital Magazine

Franchise Websites

Website

Deliveries

Budgeting

Marketing Collaboration

Franchise Management

Event Management

Human Resources Operations Marketing

Page 17: Elevate london dec 2014.pptx

The Conference App▪ Manage sessions and speakers

▪ Automatically send confirmation emails

▪ Customized user interface with Visualforce Pages

▪ Upload speaker pictures

▪ Flickr integration (Apex) to show conference pictures

▪ Google Maps integration (JS) to show conference hotels

▪ Companion app (JS + REST) for conference attendees

Page 18: Elevate london dec 2014.pptx

Free Developer Environment

http://developer.salesforce.com/signup

Page 19: Elevate london dec 2014.pptx

Lab 1: Creating a Developer Edition Account

http://developer.salesforce.com/signup

Page 20: Elevate london dec 2014.pptx

Module 2a:

Creating the Data Model

Page 21: Elevate london dec 2014.pptx

Salesforce Objects

▪ Similar to Tables (with more metadata)▪ Standard objects out-of-the-box

– Account, Contact, Opportunity, …

▪ You can add custom fields to standard objects– Rating__c, Twitter__c, …

▪ You can create custom objects– i.e. Speaker__c, Session__c, Hotel__c

▪ Custom objects have standard fields– Id, Owner, LastModifiedDate, LastModifiedBy, …

Page 22: Elevate london dec 2014.pptx

Rich Data Types

▪ Auto Number

▪ Formula

▪ Roll-Up Summary

▪ Lookup

▪ Master-Detail

▪ Checkbox

▪ Currency

▪ Date

▪ Picklist (multi select)

▪ Text

▪ Text Area

▪ Text Area (Long)

▪ Text Area (Rich)

▪ Text (Encrypted)

▪ URL

▪ Date/Time

▪ Email

▪ Geolocation

▪ Number

▪ Percent

▪ Phone

▪ Picklist

Page 23: Elevate london dec 2014.pptx

Modeling One-to-Many Relationships

An expense has one expense report

An expense report has many expenses

Page 24: Elevate london dec 2014.pptx

Modeling Many-to-Many Relationships

A speaker can have many session assignments

A session can have many speaker assignments

Page 25: Elevate london dec 2014.pptx

Id

▪ All objects are given an Id field

▪ Globally unique Id is assigned at record creation

▪ "Primary key" used to access records

Page 26: Elevate london dec 2014.pptx

Record Name

▪ Human readable / logical identifier

▪ Text or Auto Number ("Intro to Apex" or SP-00002)

▪ Uniqueness not enforced

Page 27: Elevate london dec 2014.pptx

When you create an Object, you get…

▪ Security for Entity▪ A CRUD user interface

▪ Instant Mobile App access (Salesforce1)

▪ REST/SOAP/Bulk/Push APIs

▪ Rich Metadata

▪ Apex Class

▪ Indexed Search

▪ Reporting and Analytics

Page 28: Elevate london dec 2014.pptx

Module 2b:

Creating the Application

Page 29: Elevate london dec 2014.pptx

What's an Application?

▪ Group of tabs that provide easy access to related features

▪ Salesforce comes with standards apps– Sales, Call Center, Marketing, …

▪ You can create your own apps

▪ Tabs can be:– Object pages, Visualforce pages, Canvas app

Page 30: Elevate london dec 2014.pptx

Page Layouts

Let you customize all aspects of the layout, related lists, …

Page 31: Elevate london dec 2014.pptx

Lab 2: Importing Workshop Assets

Page 32: Elevate london dec 2014.pptx

Module 3:

Writing Apex Classes

Page 33: Elevate london dec 2014.pptx

What is Apex?

▪ Salesforce platform language

▪ Similar to Java

▪ Object-oriented

▪ Strongly typed

▪ Classes and Interfaces

▪ Cloud based compiling, debugging and unit testing

Page 34: Elevate london dec 2014.pptx

Apex and Java

Same

▪ Primitive data types

▪ Flow control (if, for, while, …)

▪ Exception handling

▪ Collections: Lists, Sets, …

Different

▪ Case insensitive

▪ Single quote strings: 'Joe'

▪ Id data type

▪ Built-in support for data access

Page 35: Elevate london dec 2014.pptx

Apex Classpublic class MortgageCalculator {

}

public Double amount { get; set; }public Double rate { get; set; }public Integer years { get; set; }

public Double calculateMonthlyPayment() { Integer months = years * 12; Double monthlyRate = rate / (12 * 100); return amount * (monthlyRate/ (1 - Math.pow(1 + monthlyRate, -months)));}

Page 36: Elevate london dec 2014.pptx

Development Tools

▪ Developer Console

▪ Force.com IDE (Eclipse Plugin)

▪ Mavens Mate (Sublime Plugin)

▪ Force CLI

Page 37: Elevate london dec 2014.pptx

Developer Console

▪ Browser Based IDE

▪ Create Classes, Triggers, Pages

▪ Execute Apex Anonymously

▪ Execute SOQL Queries

▪ Run Unit Tests

▪ Review Debug Logs

Page 38: Elevate london dec 2014.pptx

Lab 3: Creating an Apex Class

▪ Create the EmailManager class

▪ Send emails from the developer console

http://bit.ly/sf-dev-quick

Page 39: Elevate london dec 2014.pptx

Module 4:

Accessing Data with SOQL and DML

Page 40: Elevate london dec 2014.pptx

What's SOQL?

▪ Salesforce Object Query language

▪ Similar to SQL

▪ Streamlined syntax to traverse object relationships

▪ Built into Apex

Page 41: Elevate london dec 2014.pptx

SELECT Id, Name, Phone

FROM Contact

Page 42: Elevate london dec 2014.pptx

SELECT Id, Name, Phone

FROM Contact

WHERE Phone <> null

Page 43: Elevate london dec 2014.pptx

SELECT Id, Name, Phone

FROM Contact

WHERE Phone <> null

AND Name LIKE '%rose%'

Page 44: Elevate london dec 2014.pptx

SELECT Id, Name, Phone

FROM Contact

WHERE Phone <> null

AND Name LIKE '%rose%'

ORDER BY Name

Page 45: Elevate london dec 2014.pptx

SELECT Id, Name, Phone

FROM Contact

WHERE Phone <> null

AND Name LIKE '%rose%'

ORDER BY Name

LIMIT 50

Page 46: Elevate london dec 2014.pptx

Details to Master

SELECT Id, Name, Phone, Account.Name

FROM Contact

WHERE Phone <> null

AND Name LIKE '%rose%'

ORDER BY Name

LIMIT 50

Page 47: Elevate london dec 2014.pptx

Master to Details

SELECT Name,

(SELECT FirstName, LastName, Phone

FROM Contacts)

FROM Account

Page 48: Elevate london dec 2014.pptx

Executing SOQL in the Developer Console

Page 49: Elevate london dec 2014.pptx

Inlining SOQL in Apex

Integer i = [SELECT Count() FROM Session__c];

Page 50: Elevate london dec 2014.pptx

Inlining SOQL in Apex

String level = 'Advanced';

List<Session__c> sessions =

[SELECT Name, Level__c FROM Session__c

WHERE Level__c = :level];

Page 51: Elevate london dec 2014.pptx

Inlining SOQL in Apex

List<String> levels = new List<String>();

levels.add('Intermediate');

levels.add('Advanced');

List<Session__c> sessions =

[SELECT Name, Level__c FROM Session__c

WHERE Level__c IN :levels];

Page 52: Elevate london dec 2014.pptx

Inlining SOQL in Apex

for (Speaker__c s : [SELECT Email__c FROM Speaker__c])

{

System.debug(s.email__c);

}

Page 53: Elevate london dec 2014.pptx

What's DML?

▪ Data Manipulation Language

▪ Language used to create, update, delete records

Page 54: Elevate london dec 2014.pptx

insert

Session__c session = new Session__c();

session.name = 'Apex 101';

session.level__c = 'Beginner';

insert session;

Page 55: Elevate london dec 2014.pptx

insert

Session__c session = new Session__c(

name = 'Apex 201',

level__c = 'Intermediate'

);

insert session;

Page 56: Elevate london dec 2014.pptx

update

String oldName = 'Apex 101';

String newName = 'Apex for Beginners';

Session__c session = [SELECT Id, Name FROM Session__c

WHERE Name=:oldName];

session.name = newName;

update session;

Page 57: Elevate london dec 2014.pptx

delete

String name = 'Testing 501';

Session__c session =

[SELECT Name FROM Session__c

WHERE Name=:name];

delete session;

Page 58: Elevate london dec 2014.pptx

Lab 4: Accessing Data using SOQL and DML

▪ Execute SOQL statements in the Query Editor

▪ Execute DML statements in the Anonymous Window

http://bit.ly/sf-dev-quick

Page 59: Elevate london dec 2014.pptx

Module 5:

Writing Triggers

Page 60: Elevate london dec 2014.pptx

What's a Trigger?

▪ Apex code executed on database events

▪ Before or after:– Insert

– Update

– Delete

– Undelete

Page 61: Elevate london dec 2014.pptx

Before or After?

▪ Before– Update values before they are saved to the database

– Example: Prevent double-booking of a speaker

▪ After– Validate values before they are saved

– Access values set by the database (Id, lastUpdated, …)

– Example: Send speaker confirmation email

Page 62: Elevate london dec 2014.pptx

Bulk Mode

▪ Triggers work on lists of records, not single records

▪ This is to support bulk operations– Data Import, Bulk API, etc.

▪ Context variables provide access to old and new values:– Trigger.old and Trigger.new (List)

– Trigger.oldMap and Trigger.newMap (Map)

Page 63: Elevate london dec 2014.pptx

Example 1trigger WelcomeKit on Account (after insert) {

List<Case> cases = new List<Case>();

for (Account account : Trigger.new) {

Case case = new Case();

case.Subject = 'Mail Welcome Kit';

case.Account.Id = account.Id;

cases.add(case);

}

insert cases;

}

Page 64: Elevate london dec 2014.pptx

Example 2trigger on Account (before update) {

for (Account acc: Trigger.New) {

// Compare new value with old value

if (acc.Rating != Trigger.oldMap.get(acc.Id).Rating) {

// Your Logic

}

}

}

Page 65: Elevate london dec 2014.pptx

Workflow vs Trigger

Workflow Trigger

Created with Clicks Code

What can it do • Update field• Send email• Create task• Send outbound message• Launch flow (flow trigger)

~ Anything (e.g. create/delete records, REST callout, etc.)

Cross-object field updates Limited (detail -> master) Any

Page 66: Elevate london dec 2014.pptx

Lab 5: Writing Triggers

▪ Write the SendConfirmationEmail trigger

▪ Write the RejectDoubleBooking trigger

http://bit.ly/sf-dev-quick

Page 67: Elevate london dec 2014.pptx

Module 6:

Writing Visualforce Pages

Page 68: Elevate london dec 2014.pptx

What's a Visualforce Page?

▪ HTML page with tags executed at the server-side to generate dynamic content

▪ Similar to JSP and ASP

▪ Can leverage JavaScript and CSS libraries

▪ The View in MVC architecture

Page 69: Elevate london dec 2014.pptx

Model-View-Controller

ModelData + Rules

ControllerView-Modelinteractions

ViewUI code

▪ Separation of concerns– No data access code in view

– No view code in controller

▪ Benefits– Minimize impact of changes

– More reusable components

Page 70: Elevate london dec 2014.pptx

Model-View-Controller in Salesforce

View• Standard Pages• Visualforce Pages• External apps

Controller• Standard Controllers• Controller Extensions• Custom Controllers

Model• Objects• Triggers (Apex)• Classes (Apex)

Page 71: Elevate london dec 2014.pptx

Component Library

▪ Presentation tags– <apex:pageBlock title="My Account Contacts">

▪ Fine grained data tags– <apex:outputField value="{!contact.firstname}">– <apex:inputField value="{!contact.firstname}">

▪ Coarse grained data tags– <apex:detail>– <apex:pageBlockTable>

▪ Action tags– <apex:commandButton action="{!save}" >

Page 72: Elevate london dec 2014.pptx

Expression Language

▪ Anything inside of {! } is evaluated as an expression

▪ Same expression language as Formulas

▪ $ provides access to global variables (Resource, Label, User, RemoteAction, …)– {! $Resource.JSLib }

– {! $Label.MyCustomLabel }

Page 73: Elevate london dec 2014.pptx

Example: Expressions <apex:page> <apex:stylesheet value=”{!URLFOR($Resource.files,’style.css’)}”/>

<h1>Hello, {!$User.FirstName}</h1>

</apex:page>

Important Note: Normally Visualforce tags do not support line breaks!

Page 74: Elevate london dec 2014.pptx

Standard Controller

▪ A standard controller is available for all objects– You don't have to write it!

▪ Provides standard CRUD operations– Create, Update, Delete, Field Access, etc.

▪ Can be extended with more capabilities (next module)

▪ Uses id query string parameter in URL to access object

Page 75: Elevate london dec 2014.pptx

Example: Standard Controller

<apex:page standardController="Contact">

<apex:form>

<apex:inputField value="{!contact.firstname}"/>

<apex:inputField value="{!contact.lastname}"/>

<apex:commandButton action="{!save}" value="Save"/>

</apex:form>

</apex:page>Method in standard

controller

Standard controllerobject

Standard controllerfield

Page 76: Elevate london dec 2014.pptx

Email Templates Embedded in Page Layouts Generate PDFs

Custom Tabs

Mobile Interfaces

Page Overrides

Where can I use Visualforce?

Page 77: Elevate london dec 2014.pptx

Lab 6: Writing Visualforce Pages

▪ Write the SpeakerForm Visualforce page

▪ Set it as default for creating and editing speakers

http://bit.ly/sf-dev-quick

Page 78: Elevate london dec 2014.pptx

Module 7:

Writing Controller Extensions and Custom Controllers

Page 79: Elevate london dec 2014.pptx

What's a Controller Extension?

▪ Custom class written in Apex

▪ Implements constructor with controller parameter

▪ Works on the same object as the standard controller

▪ Used to extend or override standard controller behavior

Page 80: Elevate london dec 2014.pptx

Defining a Controller Extension in Markup

<apex:page standardController="Speaker__c" extensions="SpeakerCtrlExt">

Provides basic CRUD

Overrides standard actions and/or provide additional capabilities

Page 81: Elevate london dec 2014.pptx

Anatomy of a Controller Extension in Apexpublic class SpeakerCtrlExt {

private final Speaker__c speaker;

private ApexPages.StandardController stdController;

public SpeakerCtrlExt (ApexPages.StandardController ctrl) {

this.stdController = ctrl;

this.speaker = (Speaker__c)ctrl.getRecord();

}

// method overrides

// custom methods

}

Page 82: Elevate london dec 2014.pptx

What's a Custom Controller?

▪ Custom class written in Apex

▪ Doesn't work on a specific object

▪ Provides custom data

▪ Provides custom behaviors

▪ Can also work with an extension

Page 83: Elevate london dec 2014.pptx

Defining a Custom Controller

<apex:page controller="FlickrController">

Page 84: Elevate london dec 2014.pptx

Custom Controller Examplepublic with sharing class FlickrController {

public FlickrList getPictures() {

HttpRequest req = new HttpRequest();

req.setMethod('GET');

req.setEndpoint('http://api.flickr.com/services/feeds/');

HTTP http = new HTTP();

HTTPResponse res = http.send(req);

return (FlickrList) JSON.deserialize(res.getBody(),

FlickrList.class);

}

}

Page 85: Elevate london dec 2014.pptx

Lab 7: Writing a Controller Extension

▪ Write a Controller Extension that supports Picture Upload

Page 87: Elevate london dec 2014.pptx

Module 8:

Using JavaScript in Visualforce Pages

Page 88: Elevate london dec 2014.pptx

Why Use JavaScript?

▪ Build Engaging User Experiences

▪ Leverage JavaScript Libraries

▪ Build Custom Applications

Page 89: Elevate london dec 2014.pptx

JavaScript in Visualforce Pages

JavaScript RemotingRemote Objects

(REST)

Visualforce Page

Page 90: Elevate london dec 2014.pptx

Examples

Page 91: Elevate london dec 2014.pptx

JavaScript Remoting - Server-Sideglobal with sharing class HotelRemoter {

@RemoteAction global static List<Hotel__c> findAll() { return [SELECT Id,

Name, Location__Latitude__s, Location__Longitude__s

FROM Hotel__c]; }

}

Page 92: Elevate london dec 2014.pptx

"global with sharing"?

▪ global– Available from outside of the application

▪ with sharing– Run code with current user permissions. (Apex code runs in

system context by default -- with access to all objects and fields)

Page 93: Elevate london dec 2014.pptx

JavaScript Remoting - Visualforce Page<script>Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.HotelRemoter.findAll}', function (result, event) { if (event.status) { for (var i = 0; i < result.length; i++) {

var lat = result[i].Location__Latitude__s; var lng = result[i].Location__Longitude__s; addMarker(lat, lng); } } else { alert(event.message); } });</script>

Page 94: Elevate london dec 2014.pptx

Using JavaScript and CSS Libraries

▪ Hosted elsewhere<script src="https://maps.googleapis.com/maps/api/js"></script>

▪ Hosted in Salesforce– Upload individual file or Zip file as Static Resource

– Reference asset using special tags

– Covered in Module 10

Page 95: Elevate london dec 2014.pptx

Lab 8: Using JavaScript in Visualforce Pages(Workbook Module 3)

▪ Write the HotelMap Visualforce Page

http://bit.ly/sf-dev-adv

Page 96: Elevate london dec 2014.pptx

Module 9:

Using the REST APIs

Page 97: Elevate london dec 2014.pptx

When?

Get access to Salesforce data from outside Salesforce:

▪ Integrate Salesforce in existing apps

▪ Build consumer apps

▪ Device integration (Internet of Things)

Page 98: Elevate london dec 2014.pptx

Mobile SDK Example

REST APIs

OAuth

Page 99: Elevate london dec 2014.pptx

Browser Cross-Origin Restrictions

REST APIs

app.jsindex.html

OAuth

HTTP Server

Cross Origin Policy

Page 100: Elevate london dec 2014.pptx

Using a Proxy

app.jsindex.html

OAuth

REST APIs

HTTP Server

Proxy

Page 101: Elevate london dec 2014.pptx

http://bit.ly/trysoql

Page 102: Elevate london dec 2014.pptx

https://contact-force.herokuapp.com

Page 103: Elevate london dec 2014.pptx

https://conference-force.herokuapp.com

Page 104: Elevate london dec 2014.pptx

Connected App

Page 105: Elevate london dec 2014.pptx

Salesforce REST Toolkit

https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit

Page 106: Elevate london dec 2014.pptx

Lab 9: Using the REST APIs(Workbook Module 4)

▪ Create a consumer app hosted outside Salesforce

http://bit.ly/sf-dev-adv

Page 107: Elevate london dec 2014.pptx

Windows Users

After installing Node.js:

1. Add c:\Program Files\Nodejs to your pathorRun "C:\Program Files\Nodejs\npm" install

2. Create an "npm" directory in C:\Users\[yourname]\Appdata\Roaming

Page 108: Elevate london dec 2014.pptx

Module 10:

Using Static Resources

Page 109: Elevate london dec 2014.pptx

What are Static Resources?

▪ Files uploaded to Salesforce instance for use in Visualforce pages– .js

– .css

– .jpg, .png, .gif, etc.

▪ Can be uploaded individually or as archive (.zip or .jar)

Page 110: Elevate london dec 2014.pptx

Static Resources

Page 111: Elevate london dec 2014.pptx

Referencing Static Resources// Single file

<apex:stylesheet value="{!$Resource.bootstrap}"/>

<apex:includeScript value="{!$Resource.jquery}"/>

<apex:image url="{!$Resource.logo}"/>

// ZIP file

<apex:stylesheet value="{!URLFOR($Resource.assets, 'css/main.css')}"/>

<apex:image url="{!URLFOR($Resource.assets, 'img/logo.png')}"/>

<apex:includeScript value="{!URLFOR($Resource.assets, 'js/app.js')}"/>

Page 112: Elevate london dec 2014.pptx

Visualforce and HTML Page Generation

▪ By default, Visualforce generates HTML page elements:– <html>

– <head>

– <body>

▪ <apex:> tags ensure corresponding HTML elements are inserted at the right place– <apex:stylesheet>

– <apex:includeScript>

Page 113: Elevate london dec 2014.pptx

Controlling HTML Page Generation

▪ You can also take full control over HTML elements generation and position:

<apex:page docType="html" applyHtmlTag="false"

applyBodyTag="false">

▪ … and use standard HTML tags– <link rel="stylesheet" href="…">

– <script src="…">

Page 114: Elevate london dec 2014.pptx

Lab 10: Static Resources(Workbook Module 5)

▪ Host single page application in Visualforce page

http://bit.ly/sf-dev-adv

Page 115: Elevate london dec 2014.pptx

Module 11:

Using Canvas Applications

Page 116: Elevate london dec 2014.pptx

What is a Canvas App?

▪ A web app integrated in your Salesforce environment

▪ Can be written in any language– Java, .NET, PHP, Ruby on Rails, Node.js, etc.

▪ Transparently authenticated

▪ Context aware (logged in user, current object, etc.)

Page 117: Elevate london dec 2014.pptx

Use Cases

▪ Internal App

▪ Third-Party / Partner App

▪ External systems with web facade

Page 118: Elevate london dec 2014.pptx

Where Can It Be Integrated?

▪ Publisher

▪ Page Layouts

▪ Visualforce Pages

▪ Tabs

▪ Mobile Cards

Page 119: Elevate london dec 2014.pptx

Defining a Canvas App

Page 120: Elevate london dec 2014.pptx

Transparent Authentication

▪ When loading Canvas app, Salesforce instance posts Base64 encoded data to app endpoint including:– Authenticated token

– Context (logged in user, current object, etc)

▪ App decodes data using client secret

▪ Can use authenticated token to make REST API calls

Page 121: Elevate london dec 2014.pptx

Node.js examplevar decode = require('salesforce-signed-request');

var secret = process.env.CONSUMER_SECRET;

app.post('/signedrequest', function(req, res) {

var signedRequest = req.body.signed_request;

var decodedRequest = decode(signedRequest, secret);

var oauthToken = decodedRequest.client.oauthToken;

var instanceUrl = decodedRequest.client.instanceUrl;

var context = decodedRequest.context;

});

Page 122: Elevate london dec 2014.pptx

Lab 11: Canvas(Workbook module 6)

▪ Deploy Node.js web app to Heroku

▪ Integrate app in Contact page layout

http://bit.ly/sf-dev-adv

Page 123: Elevate london dec 2014.pptx

Module 12:

Writing Unit Tests

Page 124: Elevate london dec 2014.pptx

Unit Testing

▪ Code to test code

▪ Increases quality and predictability

▪ Unit test coverage is required to move code to production– Must have at least 75% of code covered

– Coverage = lines of code exercised by tests / total line of code

Page 125: Elevate london dec 2014.pptx

Anatomy of a Test Class@isTest

private class myClass {

static testMethod void myTest() {

// 1. Prepare temporary data

// 2. Start Test

// 3. Execute some code

// 4. Stop Test

// 5. Assert

}

}

Page 126: Elevate london dec 2014.pptx

Create Temporary DataDatetime now = System.now();

// Create speaker

Speaker__c sp = new Speaker__c(First_Name__c='Al', Last_Name__c='Smith');

insert sp;

// Create two sessions starting at the same time

Session__c s1 = new Session__c(Name='Session1', Session_Date__c=now);

insert s1;

Session__c s2 = new Session__c(Name='Session2', Session_Date__c=now);

insert s2;

// Book speaker for session1

Session_Speaker__c booking1 =

new Session_Speaker__c(Session__c=s1.Id, Speaker__c=sp.Id);

insert booking1;

Page 127: Elevate london dec 2014.pptx

Test and AssertTest.startTest();

// Try to book speaker for session2

Session_Speaker__c booking2=

new Session_Speaker__c(Session__c=s2.Id, Speaker__c=sp.Id);

Database.SaveResult result = Database.insert(booking2, false);

Test.stopTest();

// Insert should fail: can't book same speaker for 2 sessions happening

// at same time

System.assert(!result.isSuccess());

Page 128: Elevate london dec 2014.pptx

Running Tests

Page 129: Elevate london dec 2014.pptx

Lab 12: Unit Testing(Workbook Module 7)

▪ Write the TestDoubleBooking class

▪ Run the test

http://bit.ly/sf-dev-adv

Page 130: Elevate london dec 2014.pptx

Module 13:

Batch and Schedule

Page 131: Elevate london dec 2014.pptx

What's a Batch?

▪ Long-running process that runs without manual intervention

▪ Started programmatically

Page 132: Elevate london dec 2014.pptx

Defining a Batch Jobglobal class SendReminderEmail implements Database.Batchable {

global SendReminderEmail(String query, String subject, String body) {

// Constructor: accept parameters

}

global Database.QueryLocator start(Database.BatchableContext bc) {

// Select scope (records to process)

}

global void execute(Database.BatchableContext bc, List<Speaker__c> scope) {

// Process data

}

global void finish(Database.BatchableContext bc) {

// Post processing operations

}

}

Page 133: Elevate london dec 2014.pptx

Running the Batch JobString q = 'SELECT First_Name__c, Last_Name__c, Email__c ' +

'FROM Speaker__c WHERE Email__c != null';

SendReminderEmail batch = new SendReminderEmail(q,

'Final Reminder', 'The conference starts next Monday');

Database.executeBatch(batch);

Page 134: Elevate london dec 2014.pptx

What's Scheduled Job?

▪ Unattended background program execution

▪ Occurs at a specified time

▪ Optionally repeated at a specified interval

Page 135: Elevate london dec 2014.pptx

Defining a Scheduled Jobglobal class ScheduledEmail implements Schedulable {

global void execute(SchedulableContext sc) {

String q = 'SELECT First_Name__c, Last_Name__c, Email__c ' +

'FROM Speaker__c WHERE Email__c != null';

SendReminderEmail batch = new SendReminderEmail(q,

'Final Reminder', 'The conference starts next Monday');

Database.executeBatch(batch);

}

}

Page 136: Elevate london dec 2014.pptx

Scheduling the Job (using Code)ScheduledEmail job = new ScheduledEmail();

// Run at 8AM on February 10th// (Seconds Minutes Hours Day_of_month Month Day_of_week Years)// Can use wildcards String schedule = '0 0 8 10 2 ?';

String jobId = System.schedule('Final reminder', schedule, job);

Page 137: Elevate london dec 2014.pptx

Scheduling the Job (using Clicks)

Page 138: Elevate london dec 2014.pptx

Monitoring Scheduled Jobs

Page 139: Elevate london dec 2014.pptx

Lab 13: Batching and Scheduling(Workbook Module 8)

▪ Write the SendReminderEmail class

▪ Run the batch

http://bit.ly/sf-dev-adv

Page 140: Elevate london dec 2014.pptx

Survey

Your feedback is crucial to the successof our workshops. Thank you!

http://bit.ly/sf1-london-track2

#forcewebinar

Page 141: Elevate london dec 2014.pptx

Upcoming London Events

• December 11th: Next London Meetup with Salesforce developer and admin user groups

• January 6th: London Meetup on Lightning Components!

http://developer.salesforce.com

Page 142: Elevate london dec 2014.pptx

Lab 2: Creating the Data Model

Page 143: Elevate london dec 2014.pptx

Libraries

▪ ForceTK– Salesforce REST API Toolkit

▪ Nforce– node.js a REST API wrapper

▪ ngForce– Visualforce Remoting integration in AngularJS

▪ JSForce