hca advanced developer workshop
DESCRIPTION
Advanced Force.com Workshop slides for HCATRANSCRIPT
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.
Agenda
Introduction to the Salesforce1 Platform
Salesforce1 + Visualforce
Salesforce1 + Canvas
Apex + APIs
Wrap-Up
Introduction to the Salesforce1 Platform
Salesforce1 Platform
Salesforce is a Platform Company. Period.-Alex Williams, TechCrunch
500MAPI Calls Per Day6BLines of
Apex4M+Apps Built on the Platform
72BRecords Stored
Salesforce1 Platform
Core Services
Chatter
Multi-languag
e
Translation
Workbench
Email Service
s
Analytics
CloudDatabas
e
SchemaBuilder
Search
Visualforce1
MonitoringMulti-tenant
Apex
Data-level
Security
Workflows
APIs
Mobile Services
Social
APIs
Analytics
APIs
Bulk APIsREST 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
Program Materials
Free Developer
Environment
http://developer.force.com/join
Workbookhttp://bit.ly/dfc_adv_workbook
Slideshttp://www.slideshare.net/davescruggs/hca
-advanced-developer-workshop
Program Materials
Warehouse Data Model
Merchandise
Name Price Inventory
Pinot $20 15
Cabernet $30 10
Malbec $20 20
Invoice
Number Status Count Total
INV-01 Shipped 16 $370
INV-02 New 20 $400
Invoice Line Items
Invoice Line Merchandise Units Sold
Value
INV-01 1 Pinot 1 $20
INV-01 2 Cabernet 5 $150
INV-01 3 Malbec 10 $200
INV-02 1 Pinot 20 $400
Install in your org: bit.ly/1hFwqaDI
APEX
ApexCloud based programming language
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; }}
Class and Interface based
Scoped Variables
Inline SOQL
Inline DML
Apex Anatomy
Salesforce1 + Visualforce
Standard ControllersCustom ControllersCustom Extensions
Data bound components
Controller Callbacks
Visualforce Anatomy
<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>
@RemoteAction public static String updateMerchandiseItem(String productId, Integer newInventory) { List<Merchandise__c> m = [SELECT Id, Total_Inventory__c from Merchandise__c
WHERE Id =: productId LIMIT 1]; if (m.size() > 0) { m[0].Total_Inventory__c = newInventory; try { update m[0]; return 'Item Updated'; } catch (Exception e) { return e.getMessage(); } } else { return 'No item found with that ID'; } } }
JavaScript Remoting Access Apex from JavaScript
Asynchronous Responses
$(".updateBtn").click(function() { var id = j$(this).attr('data-id'); var inventory = parseInt(j$("#inventory"+id).val()); $.mobile.showPageLoadingMsg();
MobileInventoryExtension.updateMerchandiseItem(id, inventory,handleUpdate);});
Apex
JavaScript in
Visualforce
<apex:component controller="GeoComponentController">
<apex:attribute name="lat" type="Decimal" description="Latitude for geolocation query" assignTo="{!lat}” />
<apex:attribute name="lon" type="Decimal" description="Longitude for geolocation query" assignTo="{!lon}” />
<c:GeoComponent lat=”8.9991" lon=”10.0019" />
Custom Components
<apex:page > <apex:insert name="detail" /> <div style="position:relative; clear:all;"> <apex:insert name="footer" /> </div></apex:page>
<apex:page StandardController="Invoice__c" > <apex:composition template="WarehouseTemplate"> <apex:define name="detail"> <apex:detail subject="{!Invoice__c.Id}" /> </apex:define>
Page Templates
<chatter:follow/>
<chatter:newsfeed/>
<chatter:feed/>
<chatter:followers/>
<chatter:feedAndFollowers/>
Chatter Components
Email Templates Generate PDFsEmbed in Page Layouts
Mobile Interfaces Page Overrides
Common Use Cases
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”
Extending Salesforce1 with Visualforce Pagesbit.ly/1f7feZNTime: 60 Minutes
Salesforce1 + Canvas
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
Integrating Your Web Applications in Salesforce1 with Force.com Canvashttp://bit.ly/1n8C4WK Time: 45 Minutes
Apex + APIs
“Universal Connectors”
http://makezine.com/2012/03/19/universal-adapter-set-for-construction-toys/
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){ //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
Test.StartTest(); System.schedule('testSchedule','0 0 13 * * ?',new,WarehouseUtil()); ID batchprocessid = Database.executeBatch(new WarehouseUtil());Test.StopTest();
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 EndpointsExposing Apex methods via SOAP and REST
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
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
Tutorial 472 – Create an Apphttp://bit.ly/dfc_adv_workbook
Time: 30 MinutesNote: use bit.ly/1b1Runu as the Gist.
Double-click to enter title
Double-click to enter text
The Wrap Up