ELEVATE Advanced Workshop

99
Advanced Developer Workshop Joshua Birk Developer Evangelist @joshbirk [email protected] Sanjay Savani Solutions Engineer @efxfan [email protected]

Transcript of ELEVATE Advanced Workshop

Page 1: ELEVATE Advanced Workshop

Advanced Developer Workshop

Joshua BirkDeveloper [email protected]@salesforce.com

Sanjay SavaniSolutions Engineer@[email protected]

Page 2: ELEVATE Advanced Workshop

Safe HarborSafe 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 3: ELEVATE Advanced Workshop

InteractiveQuestions? Current projects? Feedback?

Page 4: ELEVATE Advanced Workshop

1,000,000Salesforce Platform Developers

Page 5: ELEVATE Advanced Workshop

9 BillionAPI calls last month

Page 6: ELEVATE Advanced Workshop

2.5xIncreased demand for Force.com developers

Page 7: ELEVATE Advanced Workshop

YOUare the makers

Page 8: ELEVATE Advanced Workshop

BETA TESTINGWarning: We’re trying something new

Page 9: ELEVATE Advanced Workshop

Editor Of ChoiceFor the Eclipse fans in the room

Page 10: ELEVATE Advanced Workshop

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 11: ELEVATE Advanced Workshop

http://developer.force.com/join

Page 12: ELEVATE Advanced Workshop

Apex Unit TestingPlatform level support for unit testing

Page 13: ELEVATE Advanced Workshop

Unit Testing

Assert all use cases

Maximize code coverage

Test early, test often

o Logic without assertions

o 75% is the target

o Test right before deployment

Page 14: ELEVATE Advanced Workshop

Test Driven Development

Page 15: ELEVATE Advanced Workshop

Testing Context

// this is where the context of your test beginsTest.StartTest();

//execute future calls, batch apex, scheduled apex // this is where the context endsText.StopTest(); System.assertEquals(a,b); //now begin assertions

Page 16: ELEVATE Advanced Workshop

Testing Permissions

//Set up userUser u1 = [SELECT Id FROM User WHERE Alias='auser']; //Run As U1System.RunAs(u1){ //do stuff only u1 can do}

Page 17: ELEVATE Advanced Workshop

Static Resource Data

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

Page 18: ELEVATE Advanced Workshop

Mock HTTP

@isTestglobal 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 19: ELEVATE Advanced Workshop

Mock HTTP

@isTestprivate 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 20: ELEVATE Advanced Workshop

Unit Testing Tutorial

http://bit.ly/dfc_adv_workbook

Page 21: ELEVATE Advanced Workshop

SOQLSalesforce Object Query Language

Page 22: ELEVATE Advanced Workshop

Indexed Fields

• Primary Keys• Id• Name• OwnerId

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

• Audit Dates• Created Date• Last Modified Date

• Foreign Keys• Lookups• Master-Detail• CreatedBy• LastModifiedBy

• External ID fields• Unique fields• Fields indexed by

Saleforce

Page 23: ELEVATE Advanced Workshop

SOQL + Maps

Map<Id,Id> accountFormMap = new Map<Id,Id>();for (Client_Form__c form : [SELECT ID, Account__c FROM

Client_Form__c WHERE Account__c

in :accountFormMap.keySet()]) { accountFormMap.put(form.Account__c, form.Id);}

Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM

Contact]);

Page 24: ELEVATE Advanced Workshop

Child Relationships

List<Invoice__c> invoices = [SELECT Name, (SELECT

Merchandise__r.Name from Line_Items__r)

FROM Invoice__c];

List<Invoice__c> invoices = [SELECT Name, (SELECT Child_Field__c

from Child_Relationship__r) FROM Invoice__c];

Page 25: ELEVATE Advanced Workshop

SOQL Loops

public void massUpdate() { for (List<Contact> contacts: [SELECT FirstName, LastName

FROM Contact]) {

for(Contact c : contacts) { if (c.FirstName == 'Barbara' && c.LastName == 'Gordon') { c.LastName = 'Wayne'; } } update contacts; }}

Page 26: ELEVATE Advanced Workshop

ReadOnly

<apex:page controller="SummaryStatsController" readOnly="true"> <p>Here is a statistic: {!veryLargeSummaryStat}</p></apex:page>

public class SummaryStatsController { public Integer getVeryLargeSummaryStat() { Integer closedOpportunityStats = [SELECT COUNT() FROM Opportunity WHERE

Opportunity.IsClosed = true]; return closedOpportunityStats; }}

Page 27: ELEVATE Advanced Workshop

SOQL Polymorphism

List<EVENT> events = [SELECT Subject, TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN Opportunity THEN Amount, CloseDate ENDFROM Event];

Page 28: ELEVATE Advanced Workshop

Offset

SELECT NameFROM Merchandise__cWHERE Price__c > 5.0ORDER BY NameLIMIT 10OFFSET 0

SELECT NameFROM Merchandise__cWHERE Price__c > 5.0ORDER BY NameLIMIT 10OFFSET 10

Page 29: ELEVATE Advanced Workshop

AggregateResult

List<AggregateResult> res = [SELECT SUM(Line_Item_Total__c) total, Merchandise__r.Name name from Line_Item__c where Invoice__c = :id Group By Merchandise__r.Name

];

List<AggregateResult> res = [SELECT SUM(INTEGER FIELD) total, Child_Relationship__r.Name name from Parent__c where Related_Field__c = :id Group By Child_Relationship__r.Name

];

Page 30: ELEVATE Advanced Workshop

Geolocation

String q = 'SELECT ID, Name, ShippingStreet, ShippingCity from Account ';q+= 'WHERE DISTANCE(Location__c, GEOLOCATION('+String.valueOf(lat)';

q+= ','+String.valueOf(lng)+'), \'mi\')';q+= ' < 100';accounts = Database.query(q);

Page 31: ELEVATE Advanced Workshop

SOSL

List<List<SObject>> allResults = [FIND 'Tim' IN Name Fields RETURNING lead(id, name, LastModifiedDate WHERE LastModifiedDate > :oldestDate), contact(id, name, LastModifiedDate WHERE LastModifiedDate > :oldestDate), account(id, name, LastModifiedDate WHERE LastModifiedDate > :oldestDate), user(id, name, LastModifiedDate WHERE LastModifiedDate > :oldestDate) LIMIT 5];

Page 32: ELEVATE Advanced Workshop

Visualforce ControllersApex for constructing dynamic pages

Page 33: ELEVATE Advanced Workshop

ViewstateHashed information block to track server side transports

Page 34: ELEVATE Advanced Workshop

Reducing Viewstate

//Transient data that does not get sent back, //reduces viewstatetransient String userName {get; set;}

//Static and/or private vars //also do not become part of the viewstatestatic private integer VERSION_NUMBER = 1;

Page 35: ELEVATE Advanced Workshop

Reducing Viewstate

//Asynchronous JavaScript callback. No viewstate.//RemoteAction is static, so has no access to Controller context@RemoteActionpublic static Account retrieveAccount(ID accountId) { try { Account a = [SELECT ID, Name from ACCOUNT WHERE Id =:accountID LIMIT 1]; return a; } catch (DMLException e) { return null; }}

Page 36: ELEVATE Advanced Workshop

Handling Parameters

//check the existence of the query parameterif(ApexPages.currentPage().getParameters().containsKey(‘id’)) { try {

Id aid = ApexPages.currentPage().getParameters().get(‘id’); Account a =

[SELECT Id, Name, BillingStreet FROM Account WHERE ID =: aid]; } catch(QueryException ex) { ApexPages.addMessage(new ApexPages.Message( ApexPages.Severity.FATAL, ex.getMessage())); return; } }

Page 37: ELEVATE Advanced Workshop

SOQL Injection

String account_name = ApexPages.currentPage().getParameters().get('name');

account_name = String.escapeSingleQuotes(account_name);

List<Account> accounts = Database.query('SELECT ID FROM Account WHERE Name

= '+account_name);

Page 38: ELEVATE Advanced Workshop

Cookies

//Cookie = //new Cookie(String name, String value, String path, // Integer milliseconds, Boolean isHTTPSOnly)public PageReference setCookies() {Cookie companyName =

new Cookie('accountName','TestCo',null,315569260,false); ApexPages.currentPage().setCookies(new Cookie[]

{companyName}); return null; } public String getCookieValue() { return ApexPages.currentPage().

getCookies().get('accountName').getValue(); }

Page 39: ELEVATE Advanced Workshop

Inheritance and Construction

public with sharing class PageController implements SiteController {

public PageController() { } public PageController(ApexPages.StandardController stc) { }

Page 40: ELEVATE Advanced Workshop

Controlling Redirect

//Stay on same pagereturn null;

//New page, no ViewstatePageReference newPage = new Page.NewPage();newPage.setRedirect(true);return newPage;

//New page, retain ViewstatePageReference newPage = new Page.NewPage();newPage.setRedirect(false);return newPage;

Page 41: ELEVATE Advanced Workshop

Unit Testing Pages

//Set test pageTest.setCurrentPage(Page.VisualforcePage);

//Set test dataAccount a = new Account(Name='TestCo');insert a;

//Set test paramsApexPages.currentPage().getParameters().put('id',a.Id);

//Instatiate ControllerSomeController controller = new SomeController();

//Make assertionSystem.assertEquals(controller.AccountId,a.Id)

Page 42: ELEVATE Advanced Workshop

Visualforce ComponentsEmbedding content across User Interfaces

Page 43: ELEVATE Advanced Workshop

Visualforce Dashboards<apex:page controller="retrieveCase"

tabStyle="Case"> <apex:pageBlock> {!contactName}s Cases<apex:pageBlockTable value="{!cases}" var="c"> <apex:column value="{!c.status}"/><apex:column value="{!c.subject}"/> </apex:pageBlockTable> </apex:pageBlock></apex:page>

Custom Controller

Dashboard Widget

Page 44: ELEVATE Advanced Workshop

Page Overrides

Select Override

Define Override

Page 45: ELEVATE Advanced Workshop

Templates<apex:page controller="compositionExample"> <apex:form > <apex:insert name=”header" /> <br /> <apex:insert name=“body" />

Layout inserts

Define withComposition

<apex:composition template="myFormComposition"> <apex:define name=”header"> <apex:outputLabel value="Enter your favorite meal: " for="mealField"/> <apex:inputText id=”title" value="{!mealField}"/> </apex:define><h2>Page Content</h2>

Page 46: ELEVATE Advanced Workshop

<apex:component controller="WarehouseAccountsController"><apex:attribute name="lat" type="Decimal" description="Latitude for Geolocation Query" assignTo="{!lat}"/><apex:attribute name="long" type="Decimal" description="Longitude for Geolocation Query" assignTo="{!lng}"/><apex:pageBlock >

Custom Components

Define Attributes

Assign to Apex

public with sharing class WarehouseAccountsController {

public Decimal lat {get; set;} public Decimal lng {get; set;} private List<Account> accounts; public WarehouseAccountsController() {}

Page 47: ELEVATE Advanced Workshop

Page Embeds

Standard Controller

Embed in Layout

<apex:page StandardController=”Account”

showHeader=“false”<apex:canvasApp

developerName=“warehouseDev”

applicationName=“procure”

Page 48: ELEVATE Advanced Workshop

CanvasFramework for using third party apps within Salesforce

Page 49: ELEVATE Advanced Workshop
Page 50: ELEVATE Advanced Workshop

Any Language, Any Platform

• 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

Canvas Anatomy

Page 51: ELEVATE Advanced Workshop

Non-HTML Visualforce Tutorial

http://bit.ly/dfc_adv_workbook

Geolocation Component Tutorial

Page 52: ELEVATE Advanced Workshop

jQuery IntegrationVisualforce with cross-browser DOM and event control

Page 53: ELEVATE Advanced Workshop

jQuery Projects

DOM ManipulationEvent Control

UI Plugins

Mobile Interfaces

Page 54: ELEVATE Advanced Workshop

noConflict() + ready

<script>j$ = jQuery.noConflict();j$(document).ready(function() { //initialize our interface });</script>

Keeps jQuery out of the $ function

Resolves conflicts with existing libs

Ready event = DOM is Ready

Page 55: ELEVATE Advanced Workshop

jQuery Functions

j$('#accountDiv').html('New HTML');

Call Main jQuery function

Define DOM with CSS selectors

Perform actions via base jQuery methods or plugins

Page 56: ELEVATE Advanced Workshop

DOM Control

accountDiv = j$(id*=idname); accountDiv.hide(); accountDiv.hide.removeClass('bDetailBlock'); accountDiv.hide.children().show();//make this make sense

Call common functions

Manipulate CSS Directly

Interact with siblings and children

Partial CSS Selectors

Page 57: ELEVATE Advanced Workshop

Event Control

j$(".pbHeader").click(function() { j$(".pbSubsection”).toggle(); });

Add specific event handles bound to CSS selectors

Handle specific DOM element via this

Manipulate DOM based on current element, siblings or children

Page 58: ELEVATE Advanced Workshop

jQuery Plugins

iCanHaz

jqPlot

cometD

SlickGrid, jqGrid

Moustache compatible client side templates

Free charting library

Flexible and powerful grid widgets

Bayeux compatible Streaming API client

Page 59: ELEVATE Advanced Workshop

Streaming API Tutorial

http://bit.ly/dfc_adv_workbook

Page 60: ELEVATE Advanced Workshop

LUNCH:

Room 119

To the left, down the stairs

Page 61: ELEVATE Advanced Workshop

Apex TriggersEvent based programmatic logic

Page 62: ELEVATE Advanced Workshop

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 63: ELEVATE Advanced Workshop

Delegates

public class BlacklistFilterDelegate{ public static Integer FEED_POST = 1; public static Integer FEED_COMMENT = 2; public static Integer USER_STATUS = 3; List<PatternHelper> patterns {set; get;} Map<Id, PatternHelper> matchedPosts {set; get;} public BlacklistFilterDelegate() { patterns = new List<PatternHelper>(); matchedPosts = new Map<Id, PatternHelper>(); preparePatterns(); }

Page 64: ELEVATE Advanced Workshop

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 65: ELEVATE Advanced Workshop

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; } else f.RegexValue__c = RegexHelper.toRegex(f.Word__c, f.Match_Whole_Words_Only__c); } }

Page 66: ELEVATE Advanced Workshop

Scheduled ApexCron-like functionality to schedule Apex tasks

Page 67: ELEVATE Advanced Workshop

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 68: ELEVATE Advanced Workshop

Schedulable Interface

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

Via Web UI

Page 69: ELEVATE Advanced Workshop

Batch ApexFunctionality for Apex to run continuously in the background

Page 70: ELEVATE Advanced Workshop

Batchable Interface

global with sharing class WarehouseUtil implements Database.Batchable<sObject> {

//Batch execute interface global Database.QueryLocator start(Database.BatchableContext BC){ //setup SOQL for scope } 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 71: ELEVATE Advanced Workshop

Unit Testing

Test.StartTest(); ID batchprocessid = Database.executeBatch(new WarehouseUtil());Test.StopTest();

Page 72: ELEVATE Advanced Workshop

Asynchronous Apex Tutorial

De-duplication Trigger Tutorial

http://bit.ly/dfc_adv_workbook

Page 73: ELEVATE Advanced Workshop

Apex EndpointsExposing Apex methods via SOAP and REST

Page 74: ELEVATE Advanced Workshop

OAuthIndustry standard method of user authentication

Page 75: ELEVATE Advanced Workshop

RemoteApplication

SalesforcePlatform

Sends App Credentials

User logs in,Token sent to callback

Confirms token

Send access token

Maintain session withrefresh token

OAuth2 Flow

Page 76: ELEVATE Advanced Workshop

Apex SOAP

global class MyWebService { webService static Id makeContact(String lastName, Account a) { Contact c = new Contact(lastName = 'Weissman',

AccountId = a.Id); insert c; return c.id; }}

Page 77: ELEVATE Advanced Workshop

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 78: ELEVATE Advanced Workshop

Apex EmailClasses to handle both incoming and outgoing email

Page 79: ELEVATE Advanced Workshop

Outgoing Email

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String body = count+' closed records older than 90 days have been deleted';

//Set addresses based on labelmail.setToAddresses(Label.emaillist.split(','));mail.setSubject ('[Warehouse] Dated Invoices'); mail.setPlainTextBody(body); //Send the emailMessaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Page 80: ELEVATE Advanced Workshop

Incoming Email

global class PageHitsController implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail( Messaging.inboundEmail email, Messaging.InboundEnvelope env) { if(email.textAttachments.size() > 0) { Messaging.InboundEmail.TextAttachment csvDoc =

email.textAttachments[0]; PageHitsController.uploadCSVData(csvDoc.body); } Messaging.InboundEmailResult result = new

Messaging.InboundEmailResult(); result.success = true; return result; }

Page 81: ELEVATE Advanced Workshop

Incoming Email

Define Service

Limit Accepts

Page 82: ELEVATE Advanced Workshop

Custom Endpoint Tutorial

http://bit.ly/dfc_adv_workbook

Page 83: ELEVATE Advanced Workshop

Team DevelopmentTools for teams and build masters

Page 84: ELEVATE Advanced Workshop

Metadata API

API to access customizations to the Force.com platform

Page 85: ELEVATE Advanced Workshop

Migration Tool

Ant based tool for deploying Force.com applications

Page 86: ELEVATE Advanced Workshop

Continuous Integration

SourceControl

Sandbox

CI ToolDE

FailNotifications

Development Testing

Page 87: ELEVATE Advanced Workshop

Tooling API

Access, create and edit Force.com application code

Page 88: ELEVATE Advanced Workshop
Page 89: ELEVATE Advanced Workshop

Polyglot FrameworkPaaS allowing for the deployment of multiple languages

Page 90: ELEVATE Advanced Workshop
Page 91: ELEVATE Advanced Workshop

Heroku Integration Tutorial

http://bit.ly/dfc_adv_workbook

Page 92: ELEVATE Advanced Workshop

Double-click to enter title

Double-click to enter text

The Wrap Up

Page 93: ELEVATE Advanced Workshop

check inbox ||http://bit.ly/elevatela13

Page 94: ELEVATE Advanced Workshop

Double-click to enter title

Double-click to enter text

@forcedotcom@joshbirk

@metadaddy

#forcedotcom#askforce

Page 95: ELEVATE Advanced Workshop

Double-click to enter title

Double-click to enter text

Join A Developer User Group

http://bit.ly/fdc-dugs

LA DUG:http://www.meetup.com/Los-Angeles-

Force-com-Developer-Group/

Leader: Nathan Pepper

Page 96: ELEVATE Advanced Workshop

Double-click to enter title

Double-click to enter text

Become A Developer User Group Leader

Email:April Nassi

<[email protected]>

Page 97: ELEVATE Advanced Workshop

Double-click to enter title

Double-click to enter text

http://developer.force.com

http://www.slideshare.net/inkless/elevate-advanced-

workshop

Page 98: ELEVATE Advanced Workshop

simplicity is the ultimate form ofsophistication

Da Vinci

Page 99: ELEVATE Advanced Workshop

Thank You

Joshua BirkDeveloper [email protected]@salesforce.com

Matthew ReiserSolution Architect@[email protected]