elevate advanced workshop
TRANSCRIPT
Advanced Developer Workshop
Joshua BirkDeveloper [email protected]@salesforce.com
Sanjay SavaniSolutions Engineer@[email protected]
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.
InteractiveQuestions? Current projects? Feedback?
1,000,000Salesforce Platform Developers
9 BillionAPI calls last month
2.5xIncreased demand for Force.com developers
YOUare the makers
BETA TESTINGWarning: We’re trying something new
Editor Of ChoiceFor the Eclipse fans in the room
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
http://developer.force.com/join
Apex Unit TestingPlatform level support for unit testing
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
Test Driven Development
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
Testing Permissions
//Set up userUser u1 = [SELECT Id FROM User WHERE Alias='auser']; //Run As U1System.RunAs(u1){ //do stuff only u1 can do}
Static Resource Data
List<Invoice__c> invoices = Test.loadData(Invoice__c.sObjectType, 'InvoiceData');update invoices;
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; }}
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); }
}
Unit Testing Tutorial
http://bit.ly/dfc_adv_workbook
SOQLSalesforce Object Query Language
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
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]);
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];
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; }}
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; }}
SOQL Polymorphism
List<EVENT> events = [SELECT Subject, TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN Opportunity THEN Amount, CloseDate ENDFROM Event];
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
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
];
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);
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];
Visualforce ControllersApex for constructing dynamic pages
ViewstateHashed information block to track server side transports
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;
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; }}
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; } }
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);
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(); }
Inheritance and Construction
public with sharing class PageController implements SiteController {
public PageController() { } public PageController(ApexPages.StandardController stc) { }
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;
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)
Visualforce ComponentsEmbedding content across User Interfaces
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 Overrides
Select Override
Define Override
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>
<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 Embeds
Standard Controller
Embed in Layout
<apex:page StandardController=”Account”
showHeader=“false”<apex:canvasApp
developerName=“warehouseDev”
applicationName=“procure”
CanvasFramework for using third party apps within Salesforce
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
Non-HTML Visualforce Tutorial
http://bit.ly/dfc_adv_workbook
Geolocation Component Tutorial
jQuery IntegrationVisualforce with cross-browser DOM and event control
jQuery Projects
DOM ManipulationEvent Control
UI Plugins
Mobile Interfaces
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
jQuery Functions
j$('#accountDiv').html('New HTML');
Call Main jQuery function
Define DOM with CSS selectors
Perform actions via base jQuery methods or plugins
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
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
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
Streaming API Tutorial
http://bit.ly/dfc_adv_workbook
LUNCH:
Room 119
To the left, down the stairs
Apex TriggersEvent based programmatic logic
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); //
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(); }
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; } else f.RegexValue__c = RegexHelper.toRegex(f.Word__c, f.Match_Whole_Words_Only__c); } }
Scheduled ApexCron-like functionality to schedule Apex tasks
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(); }
Schedulable Interface
System.schedule('testSchedule','0 0 13 * * ?',new WarehouseUtil());Via Apex
Via Web UI
Batch ApexFunctionality for Apex to run continuously in the background
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 }
}
Unit Testing
Test.StartTest(); ID batchprocessid = Database.executeBatch(new WarehouseUtil());Test.StopTest();
Asynchronous Apex Tutorial
De-duplication Trigger Tutorial
http://bit.ly/dfc_adv_workbook
Apex EndpointsExposing Apex methods via SOAP and REST
OAuthIndustry standard method of user authentication
RemoteApplication
SalesforcePlatform
Sends App Credentials
User logs in,Token sent to callback
Confirms token
Send access token
Maintain session withrefresh token
OAuth2 Flow
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; }}
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/
Apex EmailClasses to handle both incoming and outgoing email
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});
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; }
Incoming Email
Define Service
Limit Accepts
Custom Endpoint Tutorial
http://bit.ly/dfc_adv_workbook
Team DevelopmentTools for teams and build masters
Metadata API
API to access customizations to the Force.com platform
Migration Tool
Ant based tool for deploying Force.com applications
Continuous Integration
SourceControl
Sandbox
CI ToolDE
FailNotifications
Development Testing
Tooling API
Access, create and edit Force.com application code
Polyglot FrameworkPaaS allowing for the deployment of multiple languages
Heroku Integration Tutorial
http://bit.ly/dfc_adv_workbook
Double-click to enter title
Double-click to enter text
The Wrap Up
check inbox ||http://bit.ly/elevatela13
Double-click to enter title
Double-click to enter text
@forcedotcom@joshbirk
@metadaddy
#forcedotcom#askforce
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
Double-click to enter title
Double-click to enter text
Become A Developer User Group Leader
Email:April Nassi
Double-click to enter title
Double-click to enter text
http://developer.force.com
http://www.slideshare.net/inkless/elevate-advanced-
workshop
simplicity is the ultimate form ofsophistication
Da Vinci
Thank You
Joshua BirkDeveloper [email protected]@salesforce.com
Matthew ReiserSolution Architect@[email protected]