Upload
salesforce-developers
View
233
Download
0
Tags:
Embed Size (px)
Citation preview
Salesforce1 Platformfor Programmers
Hervé MalevilleSolution Engineer - Platform
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.
Be interactive
http://developer.force.com/join
Free Developer Environment
Online Workbook
http://bit.ly/force_apex_book
Salesforce is a Platform Company. Period. -Alex Williams, TechCrunch
1B+API Calls Per Day6BLines of
Apex4M+
Apps Built on the Platform
72BRecords Stored
Salesforce1 Platform
1.4 million…and growing
CoreServices
Chatter
Multi-languag
e
Translation
Workbench
Email Service
s
Analytics
CloudDatabas
e
SchemaBuilder
Search
Visualforce
MonitoringMulti-tenant
Apex
Data-level
Security
Workflows
APIs
Mobile Services
Social
APIs
Analytics
APIs
Bulk APIs
Rest 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
Salesforce1 Platform
Every Object, Every Field: Salesforce1 Mobile Accessible
AppExchange Apps:
Dropbox Concur Evernote ServiceMax More
Custom Apps and Integrations:
SAP Oracle Everything Custom More
Sales, Service and Marketing
Accounts Cases CampaignsDashboards More
Your App
Every Object, Every Field: API Enabled
GET
POST
PATCH
DELETE
OAuth 2.0HTTPS
Every Object, Every Field: Apex and Visualforce Enabled
Visualforce PagesVisualforce Components
Apex ControllersApex Triggers
Custom UICustom UI
Custom LogicCustom Logic
Two Approaches to Development
Visualforce PagesVisualforce Components
Apex ControllersApex Triggers
Metadata APIREST APIBulk API
Formula FieldsValidation Rules
Workflows and Approvals
Custom ObjectsCustom FieldsRelationships
Page LayoutsRecord Types
User Interface
Business Logic
Data Model
Declarative Approach Programmatic Approach
Declarative before Programmatic
Use declarative features when possible:• Quicker to build• Easier to maintain and debug• Possible addition of new features• Do not count against governor limits
For example:• Will a workflow suffice instead of a trigger?• Will a custom layout work instead of
Visualforce?
ApexCloud-based programming language on Salesforce1
Introduction to Apex
• Object-Oriented Language• Dot Notation Syntax• Cloud based compiling, debugging and
unit testing
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; }
}
Apex Anatomy
Class and Interface based Scoped Variables Inline SOQL Inline DML
Developer Console
• Browser Based IDE• Create and Edit Classes• Create and Edit Triggers• Run Unit Tests• Review Debug Logs
Unit TestingCode which asserts that existing logic is operating correctly
• Code to test code
• Tests can mirror user expectations
• System Asserts increase predictability
• Line Coverage increase predictability
Unit Testing
Unit Testing in Apex
Built in support for testing– Test Utility Class Annotation
– Test Method Annotation
– Test Data build up and tear down
Unit test coverage is required– Must have at least 75% of code covered
Why is it required?
Basic Unit Test Structure@isTest
public class TestClase{
@isTest static void testCase(){
//setup test data
List<Contact> contacts = ContactFactory.createTestContacts();
//process / perform logic
EvaluateContacts.process(contacts);
//assert outcome
System.assertEquals(EvaluateContacts.processed.size(),contacts.size());
}
}
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
}
ProTip: Load Static Resource Data from CSV
List<Invoice__c> invoices = Test.loadData(Invoice__c.sObjectType, 'InvoiceData');
update invoices;
Testing Context and Asynchronous Behavior
// this is where the context of your test begins
Test.StartTest();
//execute future calls, batch apex, scheduled apex
UtilityRESTClass.performCallout();
// this is where the context ends
Test.StopTest();
System.assertEquals(a,b); //now begin assertions
Apex Triggers
• Event Based Logic
• Associated with Object Types
• Before or After:• Insert
• Update
• Delete
• Undelete
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);
Scheduled ApexInterface for scheduling Apex jobs
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();
}
}
System.schedule('testSchedule','0 0 13 * * ?',new WarehouseUtil());Via Apex
Via Web UI
Schedulable Interface
Batch ApexApex interface for processing large datasets asynchronously
Apex Batch Processing
Governor Limits– Various limitations around resource usage
Asynchronous processing– Send your job to a queue and we promise to run it
Can be scheduled to run later– Kind of like a cron job
Batchable Interface
global with sharing class WHUtil implements Database.Batchable<sObject>
{
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 }
}
ProTip: Unit Testing Asynchronous Apex
//setup test data
Test.StartTest();
System.schedule('testSchedule','0 0 13 * * ?',new WarehouseUtil());
ID batchprocessid = Database.executeBatch(new WarehouseUtil());
Test.StopTest();
//assert outcomes
Apex IntegrationUsing Apex with third party systems
Apex HTTPpublic FlickrList getFlickrData(string tag) {
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('http://api.flickr.com/services/feeds/photos_public.gne?
nojsoncallback=1&format=json&tags='+tag);
HTTP http = new HTTP();
HTTPResponse res = http.send(req);
return
(FlickrList)JSON.deserialize(res.getBody().replace('\\\'',''),FlickrList.class);
}
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/
ProTip: Unit Tests: Mock HTTP Endpoints
@isTest
global class MyMockHttp 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;
}
}
Unit Tests: Mock HTTP Endpoints
@isTest
private class CalloutClassTest {
static void testCallout() {
Test.setMock(HttpCalloutMock.class, new MyMockHttp());
HttpResponse res = CalloutClass.getInfoFromExternalService();
// Verify response received contains fake values
String actualValue = res.getBody();
String expectedValue = '{"foo":"bar"}';
System.assertEquals(actualValue, expectedValue);
}
}
VisualforceComponent-based user interface framework on Salesforce1
Visualforce Components<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>
Standard & Custom ControllersCustom Extensions
Data bound components
Controller Callbacks
Hashed information block to track server side transports
Viewstate
Apex Forms– Visualforce component bound to an Apex Method
Javascript Remoting– Annotated Apex methods exposed to JavaScript
Interacting with Apex
Using JavaScript Remoting
Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.ContactExtension.makeContact}', “003i000000cxdHP”, “Barr” function(result, event) { //...callback to handle result
alert(result.LastName); });
@RemoteActionglobal static Contact makeContact
(String cid, String lname) {return new Contact(id=cid,Last_Name=lname);
}
Ap
ex
Vis
ualforc
e
Sample Success Message
{
"statusCode":200,
"type":"rpc",
"ref":false,
"action":"IncidentReport",
"method":"createIncidentReport",
"result":"a072000000pt1ZLAAY",
"status":true
}
Sample Error Message
{
"statusCode":400,
"type":"exception",
"action":"IncidentReport",
"method":"createIncidentReport",
"message":"List has more than 1 row for assignment to SObject",
"data": {"0":{"Merchandise__c":"a052000000GUgYgAAL",
"Type__c":"Accident",
"Description__c":"This is an accident report"}},
"result":null,
"status":false
}
Remote Objects<apex:jsSObjectBase shortcut="tickets"> <apex:jsSObjectModel name="Ticket__c" /> <apex:jsSObjectModel name="Contact" fields="Email" /> <script> var contact = new tickets.Contact(); contact.retrieve({ where: { Email: { like: query + '%' } } }, function(err, data) {
//handle query results here
CRUD/Q Functionality Data Model Components JavaScript Framework Friendly
Summary: Interacting with Apex
• ActionFunction allows direct binding of variables
• ActionFunction requires ViewState
• JavaScript Remoting binds to static methods
• JavaScript Remoting uses no ViewState
• Transient, Private and Static reduce Viewstate
CanvasFramework for embedding third party apps into Salesforce
How Canvas Works
• 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
Any Language, Any Platform
Using publisher.js
Sfdc.canvas.publisher.subscribe({
name: "publisher.post",
onData: function(e) {
// fires when the user hits 'Submit'
postToFeed();
}
});
Sfdc.canvas.publisher.publish({
name: "publisher.close",
payload: { refresh:"true"}
});
API Leveraging industry standard HTTP
REST API
OAuthIndustry standard for authenticating users for third party apps
Double-click to enter title
Double-click to enter text
The Wrap Up
Double-click to enter title
Double-click to enter text
http://developer.force.com
LUNCHMobile SDKDevelopment Kit for building hybrid and native iOS and Android apps
LUNCHAppExchangeEnterprise marketplace for Salesforce1 Apps
LUNCHHerokuPolyglot framework for hosting applications
developer.salesforce.com/trailhead
Salesforce World Tour - Paris 2015
Le 25 Juin, 2015 Paris Porte de Versailles
Rejoignez l’Espace Développeurswww.salesforce.com/paris
Démos de la Plateforme Salesforce
Quick Start et Mini Hack avec Salesforce1 Lightning
Théâtre des développeurs
Librairie technique