hca advanced developer workshop

71
HCA Advanced Developer Workshop David Scruggs Platform Architect [email protected] 770-837-0241

Upload: david-scruggs

Post on 23-Jan-2015

891 views

Category:

Technology


1 download

DESCRIPTION

Advanced Force.com Workshop slides for HCA

TRANSCRIPT

Page 1: Hca advanced developer workshop

HCA Advanced Developer Workshop

David ScruggsPlatform [email protected]

Page 2: Hca advanced developer workshop

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.

Page 3: Hca advanced developer workshop

Agenda

Introduction to the Salesforce1 Platform

Salesforce1 + Visualforce

Salesforce1 + Canvas

Apex + APIs

Wrap-Up

Page 4: Hca advanced developer workshop

Introduction to the Salesforce1 Platform

Page 5: Hca advanced developer workshop

Salesforce1 Platform

Salesforce is a Platform Company. Period.-Alex Williams, TechCrunch

500MAPI Calls Per Day6BLines of

Apex4M+Apps Built on the Platform

72BRecords Stored

Page 6: Hca advanced developer workshop

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

Page 7: Hca advanced developer workshop

Program Materials

Page 8: Hca advanced developer workshop

Free Developer

Environment

http://developer.force.com/join

Page 10: Hca advanced developer workshop

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

Page 11: Hca advanced developer workshop

APEX

Page 12: Hca advanced developer workshop

ApexCloud based programming language

Page 13: Hca advanced developer workshop

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

Page 14: Hca advanced developer workshop

Salesforce1 + Visualforce

Page 15: Hca advanced developer workshop

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>

Page 16: Hca advanced developer workshop

@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

Page 17: Hca advanced developer workshop

<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

Page 18: Hca advanced developer workshop

<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

Page 19: Hca advanced developer workshop

<chatter:follow/>

<chatter:newsfeed/>

<chatter:feed/>

<chatter:followers/>

<chatter:feedAndFollowers/>

Chatter Components

Page 20: Hca advanced developer workshop

Email Templates Generate PDFsEmbed in Page Layouts

Mobile Interfaces Page Overrides

Common Use Cases

Page 21: Hca advanced developer workshop

Visualforce ControllersApex for constructing dynamic pages

Page 22: Hca advanced developer workshop

ViewstateHashed information block to track server side transports

Page 23: Hca advanced developer 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 24: Hca advanced developer 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 25: Hca advanced developer 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 26: Hca advanced developer 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 27: Hca advanced developer 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 28: Hca advanced developer workshop

Inheritance and Construction

public with sharing class PageController implements SiteController {

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

Page 29: Hca advanced developer 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 30: Hca advanced developer 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 31: Hca advanced developer workshop

Visualforce ComponentsEmbedding content across User Interfaces

Page 32: Hca advanced developer 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 33: Hca advanced developer workshop

Page Overrides

Select Override

Define Override

Page 34: Hca advanced developer 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 35: Hca advanced developer 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 36: Hca advanced developer workshop

Page Embeds

Standard Controller

Embed in Layout

<apex:page StandardController=”Account”

showHeader=“false”<apex:canvasApp

developerName=“warehouseDev”

applicationName=“procure”

Page 37: Hca advanced developer workshop

Extending Salesforce1 with Visualforce Pagesbit.ly/1f7feZNTime: 60 Minutes

Page 38: Hca advanced developer workshop

Salesforce1 + Canvas

Page 39: Hca advanced developer workshop

CanvasFramework for using third party apps within Salesforce

Page 40: Hca advanced developer workshop
Page 41: Hca advanced developer 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 42: Hca advanced developer workshop

Integrating Your Web Applications in Salesforce1 with Force.com Canvashttp://bit.ly/1n8C4WK Time: 45 Minutes

Page 43: Hca advanced developer workshop

Apex + APIs

Page 44: Hca advanced developer workshop

“Universal Connectors”

http://makezine.com/2012/03/19/universal-adapter-set-for-construction-toys/

Page 45: Hca advanced developer workshop

Apex TriggersEvent based programmatic logic

Page 46: Hca advanced developer 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 47: Hca advanced developer 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 48: Hca advanced developer 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 49: Hca advanced developer 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 50: Hca advanced developer workshop

Scheduled ApexCron-like functionality to schedule Apex tasks

Page 51: Hca advanced developer 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 52: Hca advanced developer workshop

Schedulable Interface

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

Via Web UI

Page 53: Hca advanced developer workshop

Batch ApexFunctionality for Apex to run continuously in the background

Page 54: Hca advanced developer workshop

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 }

}

Page 55: Hca advanced developer workshop

Unit Testing

Test.StartTest(); System.schedule('testSchedule','0 0 13 * * ?',new,WarehouseUtil()); ID batchprocessid = Database.executeBatch(new WarehouseUtil());Test.StopTest();

Page 56: Hca advanced developer workshop

OAuthIndustry standard method of user authentication

Page 57: Hca advanced developer 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 58: Hca advanced developer workshop

Apex EndpointsExposing Apex methods via SOAP and REST

Page 59: Hca advanced developer 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 60: Hca advanced developer 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 61: Hca advanced developer workshop

Apex EmailClasses to handle both incoming and outgoing email

Page 62: Hca advanced developer 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 63: Hca advanced developer 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 64: Hca advanced developer workshop

Incoming Email

Define Service

Limit Accepts

Page 65: Hca advanced developer workshop

Team DevelopmentTools for teams and build masters

Page 66: Hca advanced developer workshop

Metadata API

API to access customizations to the Force.com platform

Page 67: Hca advanced developer workshop

Migration Tool

Ant based tool for deploying Force.com applications

Page 68: Hca advanced developer workshop

Continuous Integration

SourceControl

Sandbox

CI ToolDE

FailNotifications

Development Testing

Page 69: Hca advanced developer workshop

Tooling API

Access, create and edit Force.com application code

Page 70: Hca advanced developer workshop

Tutorial 472 – Create an Apphttp://bit.ly/dfc_adv_workbook

Time: 30 MinutesNote: use bit.ly/1b1Runu as the Gist.

Page 71: Hca advanced developer workshop

Double-click to enter title

Double-click to enter text

The Wrap Up