elevate advanced workshop

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

Author: joshua-birk

Post on 11-May-2015

1.703 views

Category:

Technology


3 download

Embed Size (px)

TRANSCRIPT

2. 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. 3. Interactive Questions? Current projects? Feedback? 4. 1,000,000 Salesforce Platform Developers 5. 9 Billion API calls last month 6. 2.5x Increased demand for Force.com developers 7. YOU are the makers 8. BETA TESTING Warning: Were trying something new 9. Editor Of Choice For the Eclipse fans in the room 10. 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 11. http://developer.force.com/join 12. Apex Unit Testing Platform level support for unit testing 13. 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 14. Test Driven Development 15. Testing Context // this is where the context of your test begins Test.StartTest(); //execute future calls, batch apex, scheduled apex // this is where the context ends Text.StopTest(); System.assertEquals(a,b); //now begin assertions 16. 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 } 17. Static Resource Data List invoices = Test.loadData(Invoice__c.sObjectType, 'InvoiceData'); update invoices; 18. Mock HTTP @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; } } 19. Mock HTTP @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); } } 20. Unit Testing Tutorial http://bit.ly/dfc_adv_workbook 21. SOQL Salesforce Object Query Language 22. 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 23. SOQL + Maps Map accountFormMap = new Map(); 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 m = new Map( [SELECT Id, LastName FROM Contact] ); 24. Child Relationships List invoices = [SELECT Name, (SELECT Merchandise__r.Name from Line_Items__r) FROM Invoice__c]; List invoices = [SELECT Name, (SELECT Child_Field__c from Child_Relationship__r) FROM Invoice__c]; 25. SOQL Loops public void massUpdate() { for (List contacts: [SELECT FirstName, LastName FROM Contact]) { for(Contact c : contacts) { if (c.FirstName == 'Barbara' && c.LastName == 'Gordon') { c.LastName = 'Wayne'; } } update contacts; } } 26. ReadOnly

Here is a statistic: {!veryLargeSummaryStat}

public class SummaryStatsController { public Integer getVeryLargeSummaryStat() { Integer closedOpportunityStats = [SELECT COUNT() FROM Opportunity WHERE Opportunity.IsClosed = true]; return closedOpportunityStats; } } 27. SOQL Polymorphism List events = [SELECT Subject, TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN Opportunity THEN Amount, CloseDate END FROM Event]; 28. Offset SELECT Name FROM Merchandise__c WHERE Price__c > 5.0 ORDER BY Name LIMIT 10 OFFSET 0 SELECT Name FROM Merchandise__c WHERE Price__c > 5.0 ORDER BY Name LIMIT 10 OFFSET 10 29. AggregateResult List 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 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 ]; 30. 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); 31. SOSL List> 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]; 32. Visualforce Controllers Apex for constructing dynamic pages 33. Viewstate Hashed information block to track server side transports 34. Reducing Viewstate //Transient data that does not get sent back, //reduces viewstate transient String userName {get; set;} //Static and/or private vars //also do not become part of the viewstate static private integer VERSION_NUMBER = 1; 35. Reducing Viewstate //Asynchronous JavaScript callback. No viewstate. //RemoteAction is static, so has no access to Controller context @RemoteAction public 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; } } 36. Handling Parameters //check the existence of the query parameter if(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; } } 37. SOQL Injection String account_name = ApexPages.currentPage().getParameters().get('name'); account_name = String.escapeSingleQuotes(account_name); List accounts = Database.query('SELECT ID FROM Account WHERE Name = '+account_name); 38. 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(); } 39. Inheritance and Construction public with sharing class PageController implements SiteController { public PageController() { } public PageController(ApexPages.StandardController stc) { } 40. Controlling Redirect //Stay on same page return null; //New page, no Viewstate PageReference newPage = new Page.NewPage(); newPage.setRedirect(true); return newPage; //New page, retain Viewstate PageReference newPage = new Page.NewPage(); newPage.setRedirect(false); return newPage; 41. Unit Testing Pages //Set test page Test.setCurrentPage(Page.VisualforcePage); //Set test data Account a = new Account(Name='TestCo'); insert a; //Set test params ApexPages.currentPage().getParameters().put('id',a.Id); //Instatiate Controller SomeController controller = new SomeController(); //Make assertion System.assertEquals(controller.AccountId,a.Id) 42. Visualforce Components Embedding content across User Interfaces 43. Visualforce Dashboards {!contactName}s Cases Custom Controller Dashboard Widget 44. Page Overrides Select Override Define Override 45. Templates
Layout inserts Define with Composition Page Content 46. Custom Components Define Attributes Assign to Apex public with sharing class WarehouseAccountsCont public Decimal lat {get; set;} public Decimal lng {get; set;} private List accounts; public WarehouseAccountsController() {} 47. Page Embeds Standard Controller Embed in Layout j$ = jQuery.noConflict(); j$(document).ready(function() { //initialize our interface }); Keeps jQuery out of the $ function Resolves conflicts with existing libs Ready event = DOM is Ready 54. jQuery Functions j$('#accountDiv').html('New HTML'); Call Main jQuery function Define DOM with CSS selectors Perform actions via base jQuery methods or plugins 55. 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 56. 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 57. 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 58. Streaming API Tutorial http://bit.ly/dfc_adv_workbook 59. LUNCH: Room 119 To the left, down the stairs 60. Apex Triggers Event based programmatic logic 61. 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); // 62. Delegates public class BlacklistFilterDelegate { public static Integer FEED_POST = 1; public static Integer FEED_COMMENT = 2; public static Integer USER_STATUS = 3; List patterns {set; get;} Map matchedPosts {set; get;} public BlacklistFilterDelegate() { patterns = new List(); matchedPosts = new Map(); preparePatterns(); } 63. 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; } 64. 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); } } 65. Scheduled Apex Cron-like functionality to schedule Apex tasks 66. 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(); } 67. Schedulable Interface System.schedule('testSchedule','0 0 13 * * ?', new WarehouseUtil()); Via Apex Via Web UI 68. Batch Apex Functionality for Apex to run continuously in the background 69. Batchable Interface global with sharing class WarehouseUtil implements Database.Batchable { //Batch execute interface global Database.QueryLocator start(Database.BatchableContext BC){ //setup SOQL for scope } global void execute(Database.BatchableContext BC, List scope) { //Execute on current scope } global void finish(Database.BatchableContext BC) { //Finish and clean up context } 70. Unit Testing Test.StartTest(); ID batchprocessid = Database.executeBatch(new WarehouseUtil()); Test.StopTest(); 71. Asynchronous Apex Tutorial De-duplication Trigger Tutorial http://bit.ly/dfc_adv_workbook 72. Apex Endpoints Exposing Apex methods via SOAP and REST 73. OAuth Industry standard method of user authentication 74. Remote Application Salesforce Platform Sends App Credentials User logs in, Token sent to callback Confirms token Send access token Maintain session with refresh token OAuth2 Flow 75. 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; } } 76. 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/ 77. Apex Email Classes to handle both incoming and outgoing email 78. Outgoing Email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String body = count+' closed records older than 90 days have been deleted'; //Set addresses based on label mail.setToAddresses(Label.emaillist.split(',')); mail.setSubject ('[Warehouse] Dated Invoices'); mail.setPlainTextBody(body); //Send the email Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail}); 79. 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; } 80. Incoming Email Define Service Limit Accepts 81. Custom Endpoint Tutorial http://bit.ly/dfc_adv_workbook 82. Team Development Tools for teams and build masters 83. Metadata API API to access customizations to the Force.com platform 84. Migration Tool Ant based tool for deploying Force.com applications 85. Continuous Integration Source Control Sandbox CI Tool DE Fail Notifications Development Testing 86. Tooling API Access, create and edit Force.com application code 87. Polyglot Framework PaaS allowing for the deployment of multiple languages 88. Heroku Integration Tutorial http://bit.ly/dfc_adv_workbook 89. Double-click to enter title Double-click to enter text The Wrap Up 90. check inbox || http://bit.ly/elevatela13 91. Double-click to enter title Double-click to enter text @forcedotcom @joshbirk @metadaddy #forcedotcom 92. 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 93. Double-click to enter title Double-click to enter text Become A Developer User Group Leader Email: April Nassi 94. Double-click to enter title Double-click to enter text http://developer.force.com http://www.slideshare.net/inkless/ elevate-advanced-workshop 95. simplicity is the ultimate form of sophistication Da Vinci 96. Thank You Joshua Birk Developer Evangelist @joshbirk [email protected] Matthew Reiser Solution Architect @Matthew_Reiser [email protected]