Transcript
Page 1: Salesforce1 Platform for programmers

Salesforce1 Platformfor Programmers

Page 2: Salesforce1 Platform for programmers

Hervé MalevilleSolution Engineer - Platform

@[email protected]

Page 3: Salesforce1 Platform for programmers

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: Salesforce1 Platform for programmers

Be interactive

Page 5: Salesforce1 Platform for programmers

http://developer.force.com/join

Free Developer Environment

Page 6: Salesforce1 Platform for programmers

Online Workbook

http://bit.ly/force_apex_book

Page 7: Salesforce1 Platform for programmers

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

1B+API Calls Per Day6BLines of

Apex4M+

Apps Built on the Platform

72BRecords Stored

Salesforce1 Platform

Page 8: Salesforce1 Platform for programmers

1.4 million…and growing

Page 9: Salesforce1 Platform for programmers

CoreServices

Chatter

Multi-languag

e

Translation

Workbench

Email Service

s

Analytics

CloudDatabas

e

SchemaBuilder

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 10: Salesforce1 Platform for programmers

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 11: Salesforce1 Platform for programmers

Your App

Every Object, Every Field: API Enabled

GET

POST

PATCH

DELETE

OAuth 2.0HTTPS

Page 12: Salesforce1 Platform for programmers

Every Object, Every Field: Apex and Visualforce Enabled

Visualforce PagesVisualforce Components

Apex ControllersApex Triggers

Custom UICustom UI

Custom LogicCustom Logic

Page 13: Salesforce1 Platform for programmers

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 14: Salesforce1 Platform for programmers

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 15: Salesforce1 Platform for programmers

ApexCloud-based programming language on Salesforce1

Page 16: Salesforce1 Platform for programmers

Introduction to Apex

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

unit testing

Page 17: Salesforce1 Platform for programmers

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 18: Salesforce1 Platform for programmers

Developer Console

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

Page 19: Salesforce1 Platform for programmers

Unit TestingCode which asserts that existing logic is operating correctly

Page 20: Salesforce1 Platform for programmers

• Code to test code

• Tests can mirror user expectations

• System Asserts increase predictability

• Line Coverage increase predictability

Unit Testing

Page 21: Salesforce1 Platform for programmers

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 22: Salesforce1 Platform for programmers

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 23: Salesforce1 Platform for programmers

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 24: Salesforce1 Platform for programmers

ProTip: Load Static Resource Data from CSV

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

update invoices;

Page 25: Salesforce1 Platform for programmers

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

Test.StopTest();

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

Page 26: Salesforce1 Platform for programmers

Apex Triggers

• Event Based Logic

• Associated with Object Types

• Before or After:• Insert

• Update

• Delete

• Undelete

Page 27: Salesforce1 Platform for programmers

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 28: Salesforce1 Platform for programmers

Scheduled ApexInterface for scheduling Apex jobs

Page 29: Salesforce1 Platform for programmers

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 30: Salesforce1 Platform for programmers

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

Via Web UI

Schedulable Interface

Page 31: Salesforce1 Platform for programmers

Batch ApexApex interface for processing large datasets asynchronously

Page 32: Salesforce1 Platform for programmers

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 33: Salesforce1 Platform for programmers

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 34: Salesforce1 Platform for programmers

ProTip: 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 35: Salesforce1 Platform for programmers

Apex IntegrationUsing Apex with third party systems

Page 36: Salesforce1 Platform for programmers

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 37: Salesforce1 Platform for programmers

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 38: Salesforce1 Platform for programmers

ProTip: Unit Tests: Mock HTTP Endpoints

@isTest

global class MyMockHttp 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 39: Salesforce1 Platform for programmers

Unit Tests: Mock HTTP Endpoints

@isTest

private class CalloutClassTest {

static void testCallout() {

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

HttpResponse res = CalloutClass.getInfoFromExternalService();

// Verify response received contains fake values

String actualValue = res.getBody();

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

System.assertEquals(actualValue, expectedValue);

}

}

Page 40: Salesforce1 Platform for programmers

VisualforceComponent-based user interface framework on Salesforce1

Page 41: Salesforce1 Platform for programmers

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 42: Salesforce1 Platform for programmers

Hashed information block to track server side transports

Viewstate

Page 43: Salesforce1 Platform for programmers

Apex Forms– Visualforce component bound to an Apex Method

Javascript Remoting– Annotated Apex methods exposed to JavaScript

Interacting with Apex

Page 44: Salesforce1 Platform for programmers

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 45: Salesforce1 Platform for programmers

Sample Success Message

{

"statusCode":200,

"type":"rpc",

"ref":false,

"action":"IncidentReport",

"method":"createIncidentReport",

"result":"a072000000pt1ZLAAY",

"status":true

}

Page 46: Salesforce1 Platform for programmers

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 47: Salesforce1 Platform for programmers

Remote Objects<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 48: Salesforce1 Platform for programmers

Summary: 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 49: Salesforce1 Platform for programmers

CanvasFramework for embedding third party apps into Salesforce

Page 50: Salesforce1 Platform for programmers

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 51: Salesforce1 Platform for programmers

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 52: Salesforce1 Platform for programmers

API Leveraging industry standard HTTP

REST API

Page 53: Salesforce1 Platform for programmers

OAuthIndustry standard for authenticating users for third party apps

Page 54: Salesforce1 Platform for programmers

Double-click to enter title

Double-click to enter text

The Wrap Up

Page 55: Salesforce1 Platform for programmers

Double-click to enter title

Double-click to enter text

http://developer.force.com

Page 56: Salesforce1 Platform for programmers

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

Page 57: Salesforce1 Platform for programmers

LUNCHAppExchangeEnterprise marketplace for Salesforce1 Apps

Page 58: Salesforce1 Platform for programmers

LUNCHHerokuPolyglot framework for hosting applications

Page 59: Salesforce1 Platform for programmers

developer.salesforce.com/trailhead

Page 60: Salesforce1 Platform for programmers

Salesforce World Tour - Paris 2015

Le 25 Juin, 2015 Paris Porte de Versailles

Rejoignez l’Espace Développeurswww.salesforce.com/paris

Démos de la Plateforme Salesforce

Quick Start et Mini Hack avec Salesforce1 Lightning

Théâtre des développeurs

Librairie technique

Page 61: Salesforce1 Platform for programmers

Hervé MalevillePlatform Solution [email protected]@salesforc

e.com

Thank You