Hands-on Workshop: Intermediate Development with Heroku and Force.com

download Hands-on Workshop: Intermediate Development with Heroku and Force.com

If you can't read please download the document

Transcript of Hands-on Workshop: Intermediate Development with Heroku and Force.com

Welcome to the Dreamforce 14 Presentation Template

Show FlowDreamforce 2104 Breakout Session Show Flow TemplateNotesIntroduction to Development on Force.com for Developers2hr 30minPresentation Device:Customer Speaker:Demo DeviceDeck Owner/Filename:0:00Doors open0:00Start4 min0:04Welcome and Intros 6 min0:10Agenda/Workbook/Conference AppCall out We might not have time to get to Extra Credit but well try! If we dont you can optionally do it as homework 5 min0:13Hands-On: Sign up for DE& Install PKGPlease encourage all attendees to sign up for a new DE so they dont run into any issues with disabled features or API naming issues22 min0:35Using JS in VF Pages15 min0:50Hands-On: JS in VFHere we only have slides, but feel free to show your own use case or demo if you have one15 min1:05Using the Salesforce1 Platform APIs15 min1:20Hands-On: Salesforce1 Platform APIs10 min1:30Using Static Resources5 min1:35Hands-On: Static Resources 10min1:45Using Canvas Applications25 min2:10Hands-On: Force.com Canvas20 min2:30Q&AUse this as necessary. If you finish way early, you can do the extra credit exercises (there are slides for unit testing and batch) or if you take the whole time, feel free to let the students out.

Intermediate Development on Heroku and Force.comFor DevelopersSamantha Ready, salesforce.comSenior Developer Evangelist@samantha_ready

What were going to do todayWho this class was intended for

2

Samantha ReadySenior Developer Evangelist@samantha_ready

3

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 product or service availability, 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, new products and services, 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, the outcome of intellectual property and other litigation, 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-Q for the most recent fiscal quarter ended July 31, 2012. This documents and others containing important disclosures 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 presentations, 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.

Go Social!@salesforcedevs

Salesforce Developers+Salesforce DevelopersSalesforce DevelopersSalesforce Developers

5

AgendaUsing JavaScript in VF PagesUsing the Salesforce1 Platform APIsUsing Static ResourcesUsing Canvas ApplicationsExtra Credit:Unit TestingBatching and Scheduling

Cover the agenda only as the use case will be described in a later slide.6

bit.ly/df14-intermediate-dev-workshop

Use to introduce a demo, video, Q&A, etc.

Salesforce Platform is the Fastest Path from Idea to App

Idea

Build App

Ideabuy & setup hardwareinstall complex softwaredefine user accessbuild & test securitymake it mobile & socialsetup reporting & analyticsbuild app

Traditional Platforms

6-12 Months?

App

App

Our platform is not merely a cloud hosting service, it is a series of tools and features that enable developers to be successful.

On our platform, as you building your data model you are getting a lot more than just a relational database. You get a mobile app, right out of the gate.

8

Salesforce1 Platform ServicesSalesforce1 PlatformForce.comHerokuExact TargetSalesforce1 Platform APIsSalesforce1 AppSalesCloudServiceCloudMarketingCloudAppExchangeCustomAppsPartnerApps

While Salesforce is often thought of as a CRM company, it is actually so much more than that. The platform encompasses our 3 core platform services: Force.com, for building web apps natively on top of Salesforce with a direct line of access into your data. Heroku for building public, consumer applications in any language. And Exact Target with a suite of advanced marketing and automation tools. On top of that we have all of our core platform APIs to extend and integrate your applications however you requirements demand, and the Salesforce1 mobile app that gives you an instant mobile solution for your internal organization.

The Conference AppWhat well buildFirst install schema for a Force.com event management app for sessions and speakersBuild a Google Maps integration (JS) to show conference hotelsCreate a companion app (JS + REST) for conference attendeesDeploy companion app in Visualforce with Static ResourcesCreate and deploy a Node.js app on Heroku and integrate with Force.com Canvas

Were going to go through adding in programmatic functionality to an installed schema for a conference management app. This demo app manages a conference in a similar way to how we run Dreamforceobjects for sessions, speakers, and automation for session management.

In this advanced track well create a Visualforce page to map conference hotels, create an app outside of Salesforce and access conference data for integrations, explore different deployment options using static resources, and deploy a Node.js app to Heroku and integrate it into the standard contact page layout.

Free Developer Environmenthttp://developer.salesforce.com/signup

They should create a brand new DE org if they have not done so recently. They should not use a Trial, Sandbox or Production org.

Emphasize our DE orgs are free and do not expire (they are not product trials)11

Lab 1 & 2: Setup Your Developer Org & Install PKG

http://developer.salesforce.com/signup

Using JavaScript in Visualforce Pages

Why Use JavaScript?Build Engaging User ExperiencesLeverage JavaScript LibrariesBuild Custom Applications

Design interactive sitesInteracts with HTML source code, the DOM, asynchronousFriendlier UXLanguage for the web, computers, laptops, tablets, smart phones, and more

JavaScript in Visualforce Pages

JavaScript RemotingRemote Objects(REST)

Visualforce Page

Salesforce loads a VF pageThe VF page loads the HTML and resourcesUses JS remoting (if using Apex otherwise you could use VF Remote objects or REST) to talk to the server and grab data >> VF Remote objects are kind of like a Standard Controller for JSThe result set of records is returned from the remote action and a result handler then parses that result set. In this case, it would create pins pased off of those records and locations

Demo Examples

Google Maps16

JavaScript RemotingAsynchronous page responsesMost responsive and fastest way to grab data and perform DMLAll static dataDecouples the page from the controllerLets you perform tasks on the page without reloading the entire pageCan help alleviate View State issuesCode still executes in the context of the user viewing the page

3 Parts:In Apex Class: static @RemoteAction in ApexOn Visualforce Page: calls Remote Action in JavaScript On Visualforce Page: response handler for result in JavaScript

Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript. Create pages with complex, dynamic behavior that isnt possible with the standard Visualforce AJAX components.

JavaScript remoting has three parts:The remote method invocation you add to the Visualforce page, written in JavaScript.The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few differences from normal action methods.The response handler callback function you add to or include in your Visualforce page, written in JavaScript.

The remote method call executes synchronously, but it doesnt wait for the response to return. When the response returns, the callback function handles it asynchronously.

Static variables aren't transmitted as part of the view state for a Visualforce page.

17

JavaScript Remoting - Server-Sideglobal with sharing class HotelRemoter {

@RemoteAction global static List findAll() { return [SELECT Id, Name, Location__Latitude__s, Location__Longitude__s FROM Hotel__c]; }

}

RemoteAction annotated methodIts global for Salesforce1Queries all hotels

"global with sharing"?globalAvailable from outside of the applicationwith sharingRun code with current user permissions. (Apex code runs in system context by default -- with access to all objects and fields)

Needs to be global in S1 because a VF page is ultimately a child of the parent window (S1 app container).

JavaScript Remoting - Visualforce Page

Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.HotelRemoter.findAll}', function (result, event) { if (event.status) { for (var i = 0; i < result.length; i++) { var lat = result[i].Location__Latitude__s; var lng = result[i].Location__Longitude__s; addMarker(lat, lng); } } else { alert(event.message); } });

Green highlights where the JS invokes the remote action method in ApexThe function is the handler for the result set, which in this case will plot markers on a map if the result returns a success (otherwise it will display an error message)

Using JavaScript and CSS LibrariesHosted elsewhere

Hosted in SalesforceUpload individual file or Zip file as Static ResourceReference asset using special tagsCovered in Static Resources Exercise later

How

Lab 3: Using JavaScript in Visualforce Pages

Write the HotelMap Visualforce Page

Using the REST APIs

When?Get access to Salesforce data from outside Salesforce:Integrate Salesforce in existing appsBuild consumer appsDevice integration (Internet of Things)

Mobile SDK Example

REST APIsOAuth

Browser Cross-Origin RestrictionsREST APIsapp.jsindex.html

OAuth

HTTP Server

Cross Origin Policy

Using a Proxy

app.jsindex.html

OAuthREST APIs

HTTP ServerProxy

http://bit.ly/trysoql

https://contact-force.herokuapp.com

Use to introduce a demo, video, Q&A, etc.

Connected App

Salesforce REST Toolkithttps://github.com/developerforce/Force.com-JavaScript-REST-Toolkit

LibrariesForceTKSalesforce REST API ToolkitNforcenode.js a REST API wrapper ngForceVisualforce Remoting integration in AngularJS JSForce

Lab 10: Using the REST APIs

Create a consumer app hosted outside Salesforce

Windows UsersAfter installing Node.js:Add c:\Program Files\Nodejs to your pathorRun "C:\Program Files\Nodejs\npm" installCreate an "npm" directory in C:\Users\[yourname]\Appdata\Roaming

Using Static Resources

What are Static Resources?Files uploaded to Salesforce instance for use in Visualforce pages.js.css.jpg, .png, .gif, etc.Can be uploaded individually or as archive (.zip or .jar)

Static Resources

Visualforce and HTML Page GenerationBy default, Visualforce generates HTML page elements:

tags ensure corresponding HTML elements are inserted at the right place

Visualforce elements when rendered at a run time are a composition of HTML elementsUse VF if you want validation on metadata and contents to be checked by SalesforceUse raw HTML if you want full control to put tags/resources wherever you want. Stylesheets/scripts will be placed in the header regardless of placement within a VF page if you use standard VF tags.

Referencing Static Resources// Single file

// ZIP file

Both show appropriate VF components per use caseAbove shows how to reference a single file static resourceBottom shows how to traverse a zipfile to get to an individual file within it

Controlling HTML Page GenerationYou can also take full control over HTML elements generation and position: Add arbitrary components to Visualforce components that will be passed through to rendered HTMLprefix the attribute with "html-used to improve usability with HTML5 features such as placeholder ghost text, pattern client-side validation, and title help text attributes. and use standard HTML tags

40

Referencing Static Resources// Single file

// ZIP file

Lab 11: Static Resources

Host single page application in Visualforce page

Using Canvas Applications

What is a Canvas App?A web app integrated in your Salesforce environmentCan be written in any languageJava, .NET, PHP, Ruby on Rails, Node.js, etc.Transparently authenticatedContext aware (logged in user, current object, etc.)

Use CasesInternal AppThird-Party / Partner AppExternal systems with web facade

Where Can It Be Integrated?PublisherPage LayoutsVisualforce PagesTabsMobile Cards

Defining a Canvas App

Transparent AuthenticationWhen loading Canvas app, Salesforce instance posts Base64 encoded data to app endpoint including:Authenticated tokenContext (logged in user, current object, etc)App decodes data using client secretCan use authenticated token to make REST API calls

Node.js examplevar decode = require('salesforce-signed-request');var secret = process.env.CONSUMER_SECRET;

app.post('/signedrequest', function(req, res) { var signedRequest = req.body.signed_request; var decodedRequest = decode(signedRequest, secret); var oauthToken = decodedRequest.client.oauthToken; var instanceUrl = decodedRequest.client.instanceUrl; var context = decodedRequest.context;});

Lab 12: Canvas

Deploy Node.js web app to HerokuIntegrate app in Contact page layout

Writing Unit Tests

Unit TestingCode to test codeIncreases quality and predictabilityUnit test coverage is required to move code to productionMust have at least 75% of code coveredCoverage = lines of code exercised by tests / total line of code

Anatomy of a Test Class@isTestprivate class myClass { static testMethod void myTest() { // 1. Prepare temporary data // 2. Start Test // 3. Execute some code // 4. Stop Test // 5. Assert }}

Create Temporary DataDatetime now = System.now();// Create speakerSpeaker__c sp = new Speaker__c(First_Name__c='Al', Last_Name__c='Smith');insert sp;

// Create two sessions starting at the same timeSession__c s1 = new Session__c(Name='Session1', Session_Date__c=now);insert s1;Session__c s2 = new Session__c(Name='Session2', Session_Date__c=now);insert s2;

// Book speaker for session1Session_Speaker__c booking1 = new Session_Speaker__c(Session__c=s1.Id, Speaker__c=sp.Id);insert booking1;

Test and AssertTest.startTest();// Try to book speaker for session2Session_Speaker__c booking2= new Session_Speaker__c(Session__c=s2.Id, Speaker__c=sp.Id);Database.SaveResult result = Database.insert(booking2, false);Test.stopTest();

// Insert should fail: can't book same speaker for 2 sessions happening// at same timeSystem.assert(!result.isSuccess());

Running Tests

Lab 13: Unit Testing

Write the TestDoubleBooking classRun the test

Batch and Schedule

What's a Batch?Long-running process that runs without manual interventionStarted programmatically

Defining a Batch Jobglobal class SendReminderEmail implements Database.Batchable { global SendReminderEmail(String query, String subject, String body) { // Constructor: accept parameters } global Database.QueryLocator start(Database.BatchableContext bc) { // Select scope (records to process) } global void execute(Database.BatchableContext bc, List scope) { // Process data } global void finish(Database.BatchableContext bc) { // Post processing operations }}

Running the Batch JobString q = 'SELECT First_Name__c, Last_Name__c, Email__c ' + 'FROM Speaker__c WHERE Email__c != null';

SendReminderEmail batch = new SendReminderEmail(q, 'Final Reminder', 'The conference starts next Monday');

Database.executeBatch(batch);

What's Scheduled Job?Unattended background program executionOccurs at a specified time Optionally repeated at a specified interval

Defining a Scheduled Jobglobal class ScheduledEmail implements Schedulable {

global void execute(SchedulableContext sc) { String q = 'SELECT First_Name__c, Last_Name__c, Email__c ' +'FROM Speaker__c WHERE Email__c != null';

SendReminderEmail batch = new SendReminderEmail(q, 'Final Reminder', 'The conference starts next Monday'); Database.executeBatch(batch); }

}

Scheduling the Job (using Code)ScheduledEmail job = new ScheduledEmail();

// Run at 8AM on February 10th// (Seconds Minutes Hours Day_of_month Month Day_of_week Years)// Can use wildcards String schedule = '0 0 8 10 2 ?';

String jobId = System.schedule('Final reminder', schedule, job);

Scheduling the Job (using Clicks)

Monitoring Scheduled Jobs

Lab 14: Batching and Scheduling

Write the SendReminderEmail classRun the batch

Surveybit.ly/df-how-intermediateSamantha ReadySenior Developer Evangelist@samantha_ready

Certification Logos for Speaker Intro Slides

For salesforce.com use onlyGuides for logo placement

Column titleColumn titleColumn titleColumn title0.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.00

Example of a TableTable subtitle

Column titleColumn titleColumn titleColumn title0.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.00

Example of a TableTable style and coloring

Device Family Without Screens