Elevate workshop programmatic_2014

82
Salesforce1 Platform for Programmers
  • date post

    21-Oct-2014
  • Category

    Technology

  • view

    389
  • download

    1

description

 

Transcript of Elevate workshop programmatic_2014

Page 1: Elevate workshop programmatic_2014

Salesforce1 Platformfor Programmers

Page 2: Elevate workshop programmatic_2014

@forcedotcom

@joshbirk

@metadaddy

#forcedotcom

#askforce

David Scruggs Principal Platform Engineer@davescruggsIn/[email protected]

Stewart Loewen Solution Strategist/in/[email protected]

Page 3: Elevate workshop programmatic_2014

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 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, 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, 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-K for the most recent fiscal quarter ended July 31, 2011. This document and others 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 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 workshop programmatic_2014

Login and get ready

UofM WirelessInternet Instructions

On Each Table

Page 5: Elevate workshop programmatic_2014

Be interactive

Page 6: Elevate workshop programmatic_2014

For the Eclipse fans in the room

Use the Editor of Your Choice

Page 7: Elevate workshop programmatic_2014

http://developer.force.com/join

Free Developer Environment

Page 8: Elevate workshop programmatic_2014

Online Workbook

http://bit.ly/force_apex_book

Page 9: Elevate workshop programmatic_2014

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

500MAPI Calls Per Day6BLines of

Apex4M+

Apps Built on the Platform

72BRecords Stored

Salesforce1 Platform

Page 10: Elevate workshop programmatic_2014

1.4 million…and growing

Page 11: Elevate workshop programmatic_2014

CoreServices

Chatter

Multi-languag

e

Translation

Workbench

Email Service

s

Analytics

CloudDatabas

e

Scheema

Builder

Search

Visualforce

MonitoringMulti-tenant

Apex

Data-level

Security

Workflows

APIs

Mobile Services

Social

APIs

Analytics

APIs

Bulk APIs

Rest APIs

Metadata

APIs

Soap APIs

Private App

Exchange

Custom Actions

Identity

Mobile Notificatio

ns

Tooling

APIs

Mobile Packs

Mobile SDK

Offline Support

Streaming

APIs

Geolocation

ET 1:1 ET Fuel

Heroku1

Heroku Add-Ons

Sharing Model

ET API

Salesforce1 Platform

Page 12: Elevate workshop programmatic_2014

Every Object, Every Field: Salesforce1 Mobile Accessible

AppExchange Apps:

Dropbox Concur Evernote ServiceMax More

Custom Apps and Integrations:

SAP Oracle Everything Custom More

Sales, Service and Marketing

Accounts Cases CampaignsDashboards More

Page 13: Elevate workshop programmatic_2014

Your App

Every Object, Every Field: API Enabled

GET

POST

PATCH

DELETE

OAuth 2.0HTTPS

Page 14: Elevate workshop programmatic_2014

Every Object, Every Field: Apex and Visualforce Enabled

Visualforce PagesVisualforce Components

Apex ControllersApex Triggers

Custom UICustom UI

Custom LogicCustom Logic

Page 15: Elevate workshop programmatic_2014
Page 16: Elevate workshop programmatic_2014

Warehouse Application Requirements

• Track price and inventory on hand for all merchandise

• Create invoices containing one or more merchandise items as a line items

• Present total invoice amount and current shipping status

Page 17: Elevate workshop programmatic_2014

Warehouse Data Model

Merchandise

Name Price Inventory

Pinot $20 15

Cabernet $30 10

Malbec $20 20

Zinfandel $10 50

Invoice

Number Status Count Total

INV-01 Shipped 16 $370

INV-02 New 20 $200

Invoice Line Items

Invoice Line Merchandise Units Sold

Unit Price

Value

INV-01 1 Pinot 1 15 $20

INV-01 2 Cabernet 5 10 $150

INV-01 3 Malbec 10 20 $200

INV-02 1 Pinot 20 50 $200

Page 18: Elevate workshop programmatic_2014

Indexed Field

• Primary Keys• Id• Name• OwnerId

• Audit Dates• Created Date• Last Modified Date

• Foreign Keys• Lookups• Master-Detail• CreatedBy

• External ID Fields• External ID Fields• Unique Fields• Fields indexed by

Salesforce

Using a query with two or more indexed filters greatly increases performance

Page 19: Elevate workshop programmatic_2014

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 20: Elevate workshop programmatic_2014

Declarative before Programmatic

Use declarative features when possible:• Quicker to build• Easier to maintain and debug• Possible addition of new features• Do not count against governor limits

For example:• Will a workflow suffice instead of a trigger?• Will a custom layout work instead of

Visualforce?

Page 21: Elevate workshop programmatic_2014

Warehouse Data Model

Merchandise

Name Price Inventory

Pinot $20 15

Cabernet $30 10

Malbec $20 20

Zinfandel $10 50

Invoice

Number Status Count Total

INV-01 Shipped 16 $370

INV-02 New 20 $200

Invoice Line Items

Invoice Line Merchandise Units Sold

Unit Price

Value

INV-01 1 Pinot 1 20 $20

INV-01 2 Cabernet 5 10 $150

INV-01 3 Malbec 10 20 $200

INV-02 1 Pinot 20 50 $200

Workflow RuleWhen inserted, if unit price is blank then fill it withthe Merchandise price value

Page 22: Elevate workshop programmatic_2014

Hands On Tutorials#1: Setup your Environment

Page 23: Elevate workshop programmatic_2014

ApexCloud-based programming language on Salesforce1

Page 24: Elevate workshop programmatic_2014

Introduction to Apex

• Object-Oriented Language• Dot Notation Syntax• Cloud based compiling, debugging and unit

testing• “First Class” Citizen on the Platform

Page 25: Elevate workshop programmatic_2014

public with sharing class myControllerExtension implements Util {

private final Account acct; public Contact newContact {get; set;} public myControllerExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord(); }

public PageReference associateNewContact(Id cid) { newContact = [SELECT Id, Account from Contact WHERE Id =: cid LIMIT 1]; newContact.Account = acct; update newContact; }

}

Apex Anatomy

Class and Interface based Scoped Variables Inline SOQL Inline DML

Page 26: Elevate workshop programmatic_2014

Developer Console

• Browser Based IDE• Create and Edit Classes• Create and Edit Triggers• Run Unit Tests• Review Debug Logs

Page 27: Elevate workshop programmatic_2014

Hands On Tutorials#2: Using the Dev Console#3: Creating Apex Classes

Extra Credit:http://bit.ly/ELEVATE-Apex-Email-EC

Page 28: Elevate workshop programmatic_2014

Unit TestingCode which asserts that existing logic is operating correctly

Page 29: Elevate workshop programmatic_2014

• Code to test code

• Tests can mirror user expecations

• System Asserts increase predictability

• Line Coverage increase predictability

Unit Testing

Page 30: Elevate workshop programmatic_2014

Unit Testing in Apex

Built in support for testing– Test Utility Class Annotation

– Test Method Annotation

– Test Data build up and tear down

Unit test coverage is required– Must have at least 75% of code covered

Why is it required?

Page 31: Elevate workshop programmatic_2014

Basic Unit Test Structure@isTest

public class TestClase{

@isTest static void testCase(){

//setup test data

List<Contact> contacts = ContactFactory.createTestContacts();

//process / perform logic

EvaluateContacts.process(contacts);

//assert outcome

System.assertEquals(EvaluateContacts.processed.size(),contacts.size());

}

}

Page 32: Elevate workshop programmatic_2014

Testing Permissions

//Set up user

User u1 = [SELECT Id FROM User WHERE Alias='auser'];

//Run As U1

System.RunAs(u1){

//do stuff only u1 can do

}

Page 33: Elevate workshop programmatic_2014

Static Resource Data

List<Invoice__c> invoices = Test.loadData(Invoice__c.sObjectType, 'InvoiceData');

update invoices;

Page 34: Elevate workshop programmatic_2014

Testing Context and Asynchronous Behavior

// this is where the context of your test begins

Test.StartTest();

//execute future calls, batch apex, scheduled apex

UtilityRESTClass.performCallout();

// this is where the context ends

Text.StopTest();

System.assertEquals(a,b); //now begin assertions

Page 35: Elevate workshop programmatic_2014

Apex Triggers

• Event Based Logic

• Associated with Object Types

• Before or After:• Insert

• Update

• Delete

• Undelete

Page 36: Elevate workshop programmatic_2014

Controlling Flow

trigger LineItemTrigger on Line_Item__c

(before insert, before update) {

//separate before and after

if(Trigger.isBefore) {

//separate events

if(Trigger.isInsert) {

System.debug(‘BEFORE INSERT’);

DelegateClass.performLogic(Trigger.new);

Page 37: Elevate workshop programmatic_2014

Static Flags

public with sharing class AccUpdatesControl {

// This class is used to set flag to prevent multiple calls

public static boolean calledOnce = false;

public static boolean ProdUpdateTrigger = false;

}

Page 38: Elevate workshop programmatic_2014

Chatter Triggers

trigger AddRegexTrigger on Blacklisted_Word__c (before insert, before update)

{

for (Blacklisted_Word__c f : trigger.new)

{

if(f.Custom_Expression__c != NULL)

{

f.Word__c = '';

f.Match_Whole_Words_Only__c = false;

f.RegexValue__c = f.Custom_Expression__c;

}

}

}

Page 39: Elevate workshop programmatic_2014

Hands On Tutorials#4: Apex Triggers

#5: Apex Unit Tests

Extra Credit: http://bit.ly/ELEV-triggershttp://bit.ly/ELEVATE-Mock-Endpoint-EC

Page 40: Elevate workshop programmatic_2014

LUNCHLunchDown the hall

Page 41: Elevate workshop programmatic_2014

Scheduled ApexInterface for scheduling Apex jobs

Page 42: Elevate workshop programmatic_2014

Schedulable Interface

global with sharing class WarehouseUtil implements Schedulable {

//General constructor

global WarehouseUtil() {}

//Scheduled execute

global void execute(SchedulableContext ctx) {

//Use static method for checking dated invoices

WarehouseUtil.checkForDatedInvoices();

}

Page 43: Elevate workshop programmatic_2014

System.schedule('testSchedule','0 0 13 * * ?',new WarehouseUtil());Via Apex

Via Web UI

Schedulable Interface

Page 44: Elevate workshop programmatic_2014

Batch ApexApex interface for processing large datasets asynchronously

Page 45: Elevate workshop programmatic_2014

Apex Batch Processing

Governor Limits– Various limitations around resource usage

Asynchronous processing– Send your job to a queue and we promise to run it

Can be scheduled to run later– Kind of like a cron job

Page 46: Elevate workshop programmatic_2014

Batchable Interface

global with sharing class WHUtil implements Database.Batchable<sObject>

{

global Database.QueryLocator start(Database.BatchableContext BC)

{ //Start on next context }

global void execute(Database.BatchableContext BC,

List<sObject>scope)

{ //Execute on current scope }

global void finish(Database.BatchableContext BC)

{ //Finish and clean up context }

}

Page 47: Elevate workshop programmatic_2014

Unit Testing Asynchronous Apex

//setup test data

Test.StartTest();

System.schedule('testSchedule','0 0 13 * * ?',new,WarehouseUtil());

ID batchprocessid = Database.executeBatch(new WarehouseUtil());

Test.StopTest();

//assert outcomes

Page 48: Elevate workshop programmatic_2014

Apex IntegrationUsing Apex with third party systems

Page 49: Elevate workshop programmatic_2014

Apex HTTPpublic FlickrList getFlickrData(string tag) {

HttpRequest req = new HttpRequest();

req.setMethod('GET');

req.setEndpoint('http://api.flickr.com/services/feeds/photos_public.gne?

nojsoncallback=1&format=json&tags='+tag);

HTTP http = new HTTP();

HTTPResponse res = http.send(req);

return

(FlickrList)JSON.deserialize(res.getBody().replace('\\\'',''),FlickrList.class);

}

Page 50: Elevate workshop programmatic_2014

Apex REST

@RestResource(urlMapping='/CaseManagement/v1/*')

global with sharing class CaseMgmtService

{

@HttpPost

global static String attachPic(){

RestRequest req = RestContext.request;

RestResponse res = Restcontext.response;

Id caseId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

Blob picture = req.requestBody;

Attachment a = new Attachment (ParentId = caseId,

Body = picture,

ContentType = 'image/

Page 51: Elevate workshop programmatic_2014

Unit Tests: Mock HTTP Endpoints

@isTest

global class MockHttp implements HttpCalloutMock {

global HTTPResponse respond(HTTPRequest req) {

// Create a fake response

HttpResponse res = new HttpResponse();

res.setHeader('Content-Type', 'application/json');

res.setBody('{"foo":"bar"}');

res.setStatusCode(200);

return res;

}

}

Page 52: Elevate workshop programmatic_2014

Unit Tests: Mock HTTP Endpoints

@isTest

private class CalloutClassTest {

static void testCallout() {

Test.setMock(HttpCalloutMock.class, new MockHttp());

HttpResponse res = CalloutClass.getInfoFromExternalService();

// Verify response received contains fake values

String actualValue = res.getBody();

String expectedValue = '{"foo":"bar"}';

System.assertEquals(actualValue, expectedValue);

}

}

Page 53: Elevate workshop programmatic_2014

Hands On Tutorials#6: Apex Batch Processing

#7: Apex REST

Extra Credit:http://bit.ly/ELEVATE-REST-Response-EC

Page 54: Elevate workshop programmatic_2014

VisualforceComponent-based user interface framework on Salesforce1

Page 55: Elevate workshop programmatic_2014

Visualforce Components<apex:page StandardController="Contact” extensions="duplicateUtility”

action="{!checkPhone}”>

<apex:form>

<apex:outputField var="{!Contact.FirstName}” />

<apex:outputField var="{!Contact.LastName}" />

<apex:inputField var="{!Contact.Phone}" />

<apex:commandButton value="Update" action="{!quicksave}" />

</apex:form>

</apex:page>

Standard & Custom ControllersCustom Extensions

Data bound components

Controller Callbacks

Page 56: Elevate workshop programmatic_2014

Hashed information block to track server side transports

Viewstate

Page 57: Elevate workshop programmatic_2014

Apex Forms– Visualforce component bound to an Apex Method

Javascript Remoting– Annotated Apex methods exposed to JavaScript

Interacting with Apex

Page 58: Elevate workshop programmatic_2014

Using JavaScript Remoting

Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.ContactExtension.makeContact}', “003i000000cxdHP”, “Barr” function(result, event) { //...callback to handle result

alert(result.LastName); });

@RemoteActionglobal static Contact makeContact

(String cid, String lname) {return new Contact(id=cid,Last_Name=lname);

}

Ap

ex

Vis

ualforc

e

Page 59: Elevate workshop programmatic_2014

Sample Success Message

{

"statusCode":200,

"type":"rpc",

"ref":false,

"action":"IncidentReport",

"method":"createIncidentReport",

"result":"a072000000pt1ZLAAY",

"status":true

}

Page 60: Elevate workshop programmatic_2014

Sample Error Message

{

"statusCode":400,

"type":"exception",

"action":"IncidentReport",

"method":"createIncidentReport",

"message":"List has more than 1 row for assignment to SObject",

"data": {"0":{"Merchandise__c":"a052000000GUgYgAAL",

"Type__c":"Accident",

"Description__c":"This is an accident report"}},

"result":null,

"status":false

}

Page 61: Elevate workshop programmatic_2014

Remote Objects (Preview in Spring ’14)<apex:jsSObjectBase shortcut="tickets"> <apex:jsSObjectModel name="Ticket__c" /> <apex:jsSObjectModel name="Contact" fields="Email" /> <script> var contact = new tickets.Contact(); contact.retrieve({ where: { Email: { like: query + '%' } } }, function(err, data) {

//handle query results here

CRUD/Q Functionality Data Model Components JavaScript Framework Friendly

Page 62: Elevate workshop programmatic_2014

Interacting with Apex

• ActionFunction allows direct binding of variables

• ActionFunction requires ViewState

• JavaScript Remoting binds to static methods

• JavaScript Remoting uses no ViewState

• Transient, Private and Static reduce Viewstate

Page 63: Elevate workshop programmatic_2014

Hands On Tutorials#8: Salesforce1 Visualforce

Extra Credit:http://bit.ly/ELEVATE-Streaming-EC

Page 64: Elevate workshop programmatic_2014

CanvasFramework for embedding third party apps into Salesforce

Page 65: Elevate workshop programmatic_2014

How Canvas Works

• Only has to be accessible from the user’s browser

• Authentication via OAuth or Signed Response

• JavaScript based SDK can be associated with any language

• Within Canvas, the App can make API calls as the current user

• apex:CanvasApp allows embedding via Visualforce

Any Language, Any Platform

Page 66: Elevate workshop programmatic_2014

Using publisher.js

Sfdc.canvas.publisher.subscribe({

name: "publisher.post",

onData: function(e) {

// fires when the user hits 'Submit'

postToFeed();

}

});

Sfdc.canvas.publisher.publish({

name: "publisher.close",

payload: { refresh:"true"}

});

Page 67: Elevate workshop programmatic_2014

API Leveraging industry standard HTTP

REST API

Page 68: Elevate workshop programmatic_2014

OAuthIndustry standard for authenticating users for third party apps

Page 69: Elevate workshop programmatic_2014

RemoteApplication

Salesforce1Platform

Sends App Credentials

User logs in,Token sent to callback

Confirms token

Send access token

Maintain session withrefresh token

OAuth2 Authentication Flow

Page 70: Elevate workshop programmatic_2014

Hands On Tutorials#9: Salesforce1 Canvas

Recess:bit.ly/Forcecraft

Page 71: Elevate workshop programmatic_2014

Double-click to enter title

Double-click to enter text

The Wrap Up

Page 72: Elevate workshop programmatic_2014

Survey: http://bit.ly/MSP_Survey

Slides: http://bit.ly/apex_workshop_slides

Page 73: Elevate workshop programmatic_2014

Double-click to enter title

Double-click to enter text

http://developer.force.com

Page 74: Elevate workshop programmatic_2014

Developer Groups

Join a Salesforce Developer Grouphttp://bit.ly/fdc-dugs

Twin Cities Developer Grouphttp://www.meetup.com/SFTCDUG/

Become a User Group LeaderEmail: April Nassi <[email protected]>

Page 75: Elevate workshop programmatic_2014

LUNCHSalesforce1 APIsFamily of APIs on the Salesforce1 Platform

Page 76: Elevate workshop programmatic_2014

LUNCHMobile SDKDevelopment Kit for building hybrid and native iOS and Android apps

Page 77: Elevate workshop programmatic_2014

LUNCHAppExchangeEnterprise marketplace for Salesforce1 Apps

Page 78: Elevate workshop programmatic_2014

LUNCHHerokuPolyglot framework for hosting applications

Page 79: Elevate workshop programmatic_2014

@forcedotcom

@joshbirk

@metadaddy

#forcedotcom

#askforce

Page 80: Elevate workshop programmatic_2014

Joshua BirkDeveloper [email protected]@salesforce.co

m

Matthew ReiserSolution Architect@[email protected]

Page 81: Elevate workshop programmatic_2014

simplicity is the ultimate form ofsophistication

- Da Vinci

Page 82: Elevate workshop programmatic_2014

Thank You