Elevate workshop programmatic_2014

Preview:

DESCRIPTION

 

Citation preview

Salesforce1 Platformfor Programmers

@forcedotcom

@joshbirk

@metadaddy

#forcedotcom

#askforce

David Scruggs Principal Platform Engineer@davescruggsIn/dscruggsdscruggs@salesforce.com

Stewart Loewen Solution Strategist/in/stewartloewensloewen@salesforce.com

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.

Login and get ready

UofM WirelessInternet Instructions

On Each Table

Be interactive

For the Eclipse fans in the room

Use the Editor of Your Choice

http://developer.force.com/join

Free Developer Environment

Online Workbook

http://bit.ly/force_apex_book

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

500MAPI Calls Per Day6BLines of

Apex4M+

Apps Built on the Platform

72BRecords Stored

Salesforce1 Platform

1.4 million…and growing

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

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

Your App

Every Object, Every Field: API Enabled

GET

POST

PATCH

DELETE

OAuth 2.0HTTPS

Every Object, Every Field: Apex and Visualforce Enabled

Visualforce PagesVisualforce Components

Apex ControllersApex Triggers

Custom UICustom UI

Custom LogicCustom Logic

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

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

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

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

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?

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

Hands On Tutorials#1: Setup your Environment

ApexCloud-based programming language on Salesforce1

Introduction to Apex

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

testing• “First Class” Citizen on the Platform

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

Developer Console

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

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

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

Unit TestingCode which asserts that existing logic is operating correctly

• Code to test code

• Tests can mirror user expecations

• System Asserts increase predictability

• Line Coverage increase predictability

Unit Testing

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?

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());

}

}

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

}

Static Resource Data

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

update invoices;

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

Apex Triggers

• Event Based Logic

• Associated with Object Types

• Before or After:• Insert

• Update

• Delete

• Undelete

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);

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;

}

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;

}

}

}

Hands On Tutorials#4: Apex Triggers

#5: Apex Unit Tests

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

LUNCHLunchDown the hall

Scheduled ApexInterface for scheduling Apex jobs

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();

}

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

Via Web UI

Schedulable Interface

Batch ApexApex interface for processing large datasets asynchronously

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

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 }

}

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

Apex IntegrationUsing Apex with third party systems

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);

}

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/

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;

}

}

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);

}

}

Hands On Tutorials#6: Apex Batch Processing

#7: Apex REST

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

VisualforceComponent-based user interface framework on Salesforce1

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

Hashed information block to track server side transports

Viewstate

Apex Forms– Visualforce component bound to an Apex Method

Javascript Remoting– Annotated Apex methods exposed to JavaScript

Interacting with Apex

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

Sample Success Message

{

"statusCode":200,

"type":"rpc",

"ref":false,

"action":"IncidentReport",

"method":"createIncidentReport",

"result":"a072000000pt1ZLAAY",

"status":true

}

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

}

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

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

Hands On Tutorials#8: Salesforce1 Visualforce

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

CanvasFramework for embedding third party apps into Salesforce

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

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"}

});

API Leveraging industry standard HTTP

REST API

OAuthIndustry standard for authenticating users for third party apps

RemoteApplication

Salesforce1Platform

Sends App Credentials

User logs in,Token sent to callback

Confirms token

Send access token

Maintain session withrefresh token

OAuth2 Authentication Flow

Hands On Tutorials#9: Salesforce1 Canvas

Recess:bit.ly/Forcecraft

Double-click to enter title

Double-click to enter text

The Wrap Up

Survey: http://bit.ly/MSP_Survey

Slides: http://bit.ly/apex_workshop_slides

Double-click to enter title

Double-click to enter text

http://developer.force.com

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 <anassi@salesforce.com>

LUNCHSalesforce1 APIsFamily of APIs on the Salesforce1 Platform

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

LUNCHAppExchangeEnterprise marketplace for Salesforce1 Apps

LUNCHHerokuPolyglot framework for hosting applications

@forcedotcom

@joshbirk

@metadaddy

#forcedotcom

#askforce

Joshua BirkDeveloper Evangelist@joshbirkjoshua.birk@salesforce.co

m

Matthew ReiserSolution Architect@Matthew_Reisermreiser@salesforce.com

simplicity is the ultimate form ofsophistication

- Da Vinci

Thank You

Recommended