102
Advanced Developer Workshop Joshua Birk Developer Evangelist @joshbirk [email protected] Gordon Jackson Solution Architect [email protected]

Detroit ELEVATE Track 2

Embed Size (px)

DESCRIPTION

Advanced Workshop

Citation preview

Page 1: Detroit ELEVATE Track 2

Advanced Developer Workshop

Joshua BirkDeveloper [email protected]@salesforce.com

Gordon JacksonSolution [email protected]

Page 2: Detroit ELEVATE Track 2

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: Detroit ELEVATE Track 2

ETHERNETON

TABLE

Promo code:salesforce13

http://bit.ly/elevate_adv

Page 4: Detroit ELEVATE Track 2

InteractiveQuestions? Current projects? Feedback?

Page 5: Detroit ELEVATE Track 2

1,000,000Salesforce Platform Developers

Page 6: Detroit ELEVATE Track 2

9 BillionAPI calls last month

Page 7: Detroit ELEVATE Track 2

2.5xIncreased demand for Force.com developers

Page 8: Detroit ELEVATE Track 2

YOUare the makers

Page 9: Detroit ELEVATE Track 2

BETA TESTINGWarning: We’re trying something new

Page 10: Detroit ELEVATE Track 2

Editor Of ChoiceFor the Eclipse fans in the room

Page 11: Detroit ELEVATE Track 2

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 12: Detroit ELEVATE Track 2

http://developer.force.com/join

Page 13: Detroit ELEVATE Track 2

Apex Unit TestingPlatform level support for unit testing

Page 14: Detroit ELEVATE Track 2

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 15: Detroit ELEVATE Track 2

Test Driven Development

Page 16: Detroit ELEVATE Track 2

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 17: Detroit ELEVATE Track 2

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 18: Detroit ELEVATE Track 2

Static Resource Data

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

Page 19: Detroit ELEVATE Track 2

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 20: Detroit ELEVATE Track 2

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 21: Detroit ELEVATE Track 2

Unit Testing Tutorial

http://bit.ly/elevate_adv

Page 22: Detroit ELEVATE Track 2

SOQLSalesforce Object Query Language

Page 23: Detroit ELEVATE Track 2

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 24: Detroit ELEVATE Track 2

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 25: Detroit ELEVATE Track 2

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 26: Detroit ELEVATE Track 2

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 27: Detroit ELEVATE Track 2

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 28: Detroit ELEVATE Track 2

SOQL Polymorphism

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

Page 29: Detroit ELEVATE Track 2

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 30: Detroit ELEVATE Track 2

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 31: Detroit ELEVATE Track 2

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 32: Detroit ELEVATE Track 2

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 33: Detroit ELEVATE Track 2

Visualforce ControllersApex for constructing dynamic pages

Page 34: Detroit ELEVATE Track 2

ViewstateHashed information block to track server side transports

Page 35: Detroit ELEVATE Track 2

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 36: Detroit ELEVATE Track 2

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 37: Detroit ELEVATE Track 2

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 38: Detroit ELEVATE Track 2

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 39: Detroit ELEVATE Track 2

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 40: Detroit ELEVATE Track 2

Inheritance and Construction

public with sharing class PageController implements SiteController {

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

Page 41: Detroit ELEVATE Track 2

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 42: Detroit ELEVATE Track 2

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 43: Detroit ELEVATE Track 2

Non-HTML Visualforce Tutorial

http://bit.ly/elevate_advhttp://bit.ly/elevate_demos_adv

Page 44: Detroit ELEVATE Track 2

Visualforce ComponentsEmbedding content across User Interfaces

Page 45: Detroit ELEVATE Track 2

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 46: Detroit ELEVATE Track 2

Page Overrides

Select Override

Define Override

Page 47: Detroit ELEVATE Track 2

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 48: Detroit ELEVATE Track 2

<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 49: Detroit ELEVATE Track 2

Page Embeds

Standard Controller

Embed in Layout

<apex:page StandardController=”Account”

showHeader=“false”<apex:canvasApp

developerName=“warehouseDev”

applicationName=“procure”

Page 50: Detroit ELEVATE Track 2

CanvasFramework for using third party apps within Salesforce

Page 51: Detroit ELEVATE Track 2
Page 52: Detroit ELEVATE Track 2

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 53: Detroit ELEVATE Track 2

Geolocation Component Tutorial

http://bit.ly/elevate_adv

Page 54: Detroit ELEVATE Track 2

jQuery IntegrationVisualforce with cross-browser DOM and event control

Page 55: Detroit ELEVATE Track 2

jQuery Projects

DOM ManipulationEvent Control

UI Plugins

Mobile Interfaces

Page 56: Detroit ELEVATE Track 2

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 57: Detroit ELEVATE Track 2

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 58: Detroit ELEVATE Track 2

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 59: Detroit ELEVATE Track 2

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 60: Detroit ELEVATE Track 2

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 61: Detroit ELEVATE Track 2

Streaming API Tutorial

http://bit.ly/elevate_adv

Page 62: Detroit ELEVATE Track 2

LUNCH:

Room 119

To the left, down the stairs

Page 63: Detroit ELEVATE Track 2

Apex TriggersEvent based programmatic logic

Page 64: Detroit ELEVATE Track 2

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 65: Detroit ELEVATE Track 2

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 66: Detroit ELEVATE Track 2

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 67: Detroit ELEVATE Track 2

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 68: Detroit ELEVATE Track 2

De-duplication Trigger Tutorial

http://bit.ly/elevate_adv

Page 69: Detroit ELEVATE Track 2

Scheduled ApexCron-like functionality to schedule Apex tasks

Page 70: Detroit ELEVATE Track 2

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 71: Detroit ELEVATE Track 2

Schedulable Interface

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

Via Web UI

Page 72: Detroit ELEVATE Track 2

Batch ApexFunctionality for Apex to run continuously in the background

Page 73: Detroit ELEVATE Track 2

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 74: Detroit ELEVATE Track 2

Unit Testing

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

Page 75: Detroit ELEVATE Track 2

Asynchronous Apex Tutorial

Page 76: Detroit ELEVATE Track 2

Apex EndpointsExposing Apex methods via SOAP and REST

Page 77: Detroit ELEVATE Track 2

OAuthIndustry standard method of user authentication

Page 78: Detroit ELEVATE Track 2

RemoteApplication

SalesforcePlatform

Sends App Credentials

User logs in,Token sent to callback

Confirms token

Send access token

Maintain session withrefresh token

OAuth2 Flow

Page 79: Detroit ELEVATE Track 2

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 80: Detroit ELEVATE Track 2

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 81: Detroit ELEVATE Track 2

Apex EmailClasses to handle both incoming and outgoing email

Page 82: Detroit ELEVATE Track 2

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 83: Detroit ELEVATE Track 2

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 84: Detroit ELEVATE Track 2

Incoming Email

Define Service

Limit Accepts

Page 85: Detroit ELEVATE Track 2

Custom Endpoint Tutorial

http://bit.ly/elevate_adv

Page 86: Detroit ELEVATE Track 2

Team DevelopmentTools for teams and build masters

Page 87: Detroit ELEVATE Track 2

Metadata API

API to access customizations to the Force.com platform

Page 88: Detroit ELEVATE Track 2

Migration Tool

Ant based tool for deploying Force.com applications

Page 89: Detroit ELEVATE Track 2

Continuous Integration

SourceControl

Sandbox

CI ToolDE

FailNotifications

Development Testing

Page 90: Detroit ELEVATE Track 2

Tooling API

Access, create and edit Force.com application code

Page 91: Detroit ELEVATE Track 2
Page 92: Detroit ELEVATE Track 2

Polyglot FrameworkPaaS allowing for the deployment of multiple languages

Page 93: Detroit ELEVATE Track 2
Page 94: Detroit ELEVATE Track 2

Heroku Integration Tutorial

http://bit.ly/elevate_adv

Page 95: Detroit ELEVATE Track 2

Double-click to enter title

Double-click to enter text

The Wrap Up

Page 96: Detroit ELEVATE Track 2

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

Page 97: Detroit ELEVATE Track 2

Double-click to enter title

Double-click to enter text

@forcedotcom@joshbirk

@metadaddy

#forcedotcom#askforce

Page 98: Detroit ELEVATE Track 2

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 99: Detroit ELEVATE Track 2

Double-click to enter title

Double-click to enter text

Become A Developer User Group Leader

Email:April Nassi

<[email protected]>

Page 100: Detroit ELEVATE Track 2

Double-click to enter title

Double-click to enter text

http://developer.force.com

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

workshop

Page 101: Detroit ELEVATE Track 2

simplicity is the ultimate form ofsophistication

Da Vinci

Page 102: Detroit ELEVATE Track 2

Thank You

Joshua BirkDeveloper [email protected]@salesforce.com

Matthew ReiserSolution Architect@[email protected]