You are on page 1of 26

Apex Code

An Introduction to Programming on the Force.com Platform

Pat Patterson Principal Developer Evangelist @metadaddy Taggart Matthiesen Director of Product Management @tmatthiesensfdc

Join the conversation on Twitter: #forcewebinar @forcedotcom

Got Twitter? @forcedotcom / #forcewebinar Facebook? facebook.com/forcedotcom


Like us in the month of March and enter to win an iPod Touch

Join the conversation on Twitter: #forcewebinar @forcedotcom

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, 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, 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 filed on February 24, 2011 and in other filings with the Securities and Exchange Commission. These documents 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.
P Join the conversation on Twitter: #forcewebinar @forcedotcom

Agenda

What is Apex Code? When should I use Apex, and when shouldnt I?
Database Triggers UI Controllers Web Services

The Apex Development Lifecycle Resources Q & A

P Join the conversation on Twitter: #forcewebinar @forcedotcom

Force.com Technologies
Declarative Logic (point and click)
Required/Unique Fields Audit History Tracking Workflows Rules & Approval Processes

Formula-Based Logic (spreadsheet-like)


Formula Fields Data Validation Rules Workflows Rules & Approval Processes

Procedural Logic (code)


Apex Triggers Apex Classes

P Join the conversation on Twitter: #forcewebinar @forcedotcom

What is Apex Code?

Object-oriented programming language


Strongly typed Compiled Syntax similar to Java and C#

P Join the conversation on Twitter: #forcewebinar @forcedotcom

Created for the Cloud

Executes on the Force.com platform Designed for multi-tenancy


Governor limits

Code must have unit test coverage before going live Augments the Declarative (point-and-click) UI
But doesnt replace it!

Can write code in the browser or the Force.com IDE


Eclipse plug-in

P Join the conversation on Twitter: #forcewebinar @forcedotcom

A Major Milestone

T Join the conversation on Twitter: #forcewebinar @forcedotcom

An Apex Class
public class StoreFront { DisplayMerchandise[] products;
Class Definition Member Variable

public String message { get; set; }

Automatic Property

public DisplayMerchandise[] getProducts() { if (products == null) { List Iteration products = new DisplayMerchandise[]{}; Instance for Loop Method for (Merchandise__c item : [SELECT id, name, description__c, price__c FROM Merchandise__c WHERE Total_Inventory__c > 0]) { products.add(new DisplayMerchandise(item)); SOQL Query } } return products; } }

Join the conversation on Twitter: #forcewebinar @forcedotcom

When to Use Apex Code


Declarative first
Formula fields Rollup summaries Validation rules Workflows

Programmatic second
Complex transactions Integrations (email, web services) Asynchronous processing Custom controllers (custom UI & logic)

T Join the conversation on Twitter: #forcewebinar @forcedotcom

Apex Triggers

Triggers execute before or after database events


insert, update, delete, undelete

before
Can update or validate data, or even abort event

after
Can create links to newly created fields, records

Trigger code can access new and old record lists

P Join the conversation on Twitter: #forcewebinar @forcedotcom

An Apex Trigger

Trigger Events

trigger HandleProductPriceChange on Merchandise__c (after update) { List<Line_Item__c> openLineItems = SOQL Query [SELECT j.Unit_Price__c, j.Merchandise__r.Price__c FROM Line_Item__c j Trigger Definition WHERE j.Invoice_Statement__r.Status__c = 'Negotiating' AND j.Merchandise__r.id IN :Trigger.new Trigger FOR UPDATE]; Context
Variable

for (Line_Item__c li: openLineItems) { if ( li.Merchandise__r.Price__c < li.Unit_Price__c ){ li.Unit_Price__c = li.Merchandise__r.Price__c; } } update openLineItems; }
P Join the conversation on Twitter: #forcewebinar @forcedotcom DML Operation

The MVC Pattern in Force.com

Model

View
P Join the conversation on Twitter: #forcewebinar @forcedotcom

Controller

An Apex Controller
Visualforce page the view
<apex:page standardStylesheets="false" showHeader="false"
sidebar="false" controller="StoreFront" > <apex:stylesheet value="{!URLFOR($Resource.styles, 'styles.css')}"/> <h1>Store Front</h1>
Custom Controller Reference

Apex class the controller


public class StoreFront { Action public PageReference shop() { Method message = 'You bought: '; for (DisplayMerchandise p: products) { if (p.count > 0) { message += p.merchandise.name + ' (' + p.count + ') } } return null; }
Join the conversation on Twitter: #forcewebinar @forcedotcom

';

Web Services in Apex Code

Inbound
Currently SOAP only Use webService keyword Generate WSDL for web service consumer

Outbound
SOAP
Import WSDL, Apex stubs generated

HTTP
Developer responsible for creating request, parsing response Apex JSON parser available via open source project
P Join the conversation on Twitter: #forcewebinar @forcedotcom

An Apex Web Service


global class OrderControl { webService static Boolean dispatchOrder(String invoiceNumber) { Invoice_Statement__c invoice = [SELECT Status__c FROM Invoice_Statement__c SOQL Query WHERE Name = :invoiceNumber Web Service FOR UPDATE]; if (invoice.Status__c == 'Dispatched') { return false; } invoice.Status__c = 'Dispatched'; update invoice; return true; } }
Join the conversation on Twitter: #forcewebinar @forcedotcom DML Operation

Apex Development Lifecycle

Develop in Developer Edition, Force.com Free Edition or a Sandbox


Writing code in a production system is not permitted!

Deployment from Sandbox to production requires 75% test coverage


Implement test classes, methods Use System.assert() method family to check results Create test data it will be discarded at the end of the test

T Join the conversation on Twitter: #forcewebinar @forcedotcom

An Apex Test Class


Test Method @isTest private class TestHandleProductPriceChange { static testMethod void testPriceChange() { Invoice_Statement__c invoice = new Invoice_Statement__c(Status__c = 'Negotiating'); Entire Class insert invoice; is Test Code Create Test Data // more setup code

products[0].price__c = 20; // raise price products[1].price__c = 5; // lower price Test.startTest(); update products; Test.stopTest();

Run the Test!

Verify the Results

lineItems = [SELECT id, unit_price__c FROM Line_Item__c WHERE id IN :lineItems]; System.assert(lineItems[0].unit_price__c == 10); // unchanged System.assert(lineItems[1].unit_price__c == 5); // changed!! } }
P Join the conversation on Twitter: #forcewebinar @forcedotcom

Governor Limits

Runtime limits protect the multi-tenant environment from runaway code 18 limits covering database access, execution environment, callouts Follow best practice to get the most out of your code
Example batch DML operations to minimize consumption of DML statement resource

T Join the conversation on Twitter: #forcewebinar @forcedotcom

Get Started With All the Right Tools

Your Resource

to Unleash the Power of Force.com


Over 340,000 Developers Developer Discussion Boards Force.com Blog Documentation Tools, Code Samples and more

http://developer.force.com/

Join the conversation on Twitter: #forcewebinar @forcedotcom

Build Your First Cloud-based Apps

Force.com Workbook
Basic Visualforce, Apex

Chatter Workbook
Get Started with the Collaboration Cloud

Visualforce Workbook
Focus on the UI

http://developer.force.com/workbook

Join the conversation on Twitter: #forcewebinar @forcedotcom

Force.com Developer Discussion Forums

Tens of thousands of members 62k+ posts in 2010

Boards for Apex, Visualforce, Chatter, Integration with Java, .NET, Ruby, Jobs, and more.

http://boards.developerforce.com/

Join the conversation on Twitter: #forcewebinar @forcedotcom

Force.com MVP Program


We are recognizing individuals for outstanding technical leadership, platform evangelism and community stewardship Key benefits:
Access to feature previews, networking opportunities, promotion to leadership roles

Congratulations to March 2011 inductees!


Abhinav Gupta Jason Ouellette Jeff Douglas Joel Dietz Mike Leach Muhammad Imran Ahmed Richard Vanhook Tim Inman Wes Nolte

Terms:
Selection process three times/year MVPs will have a one year term, at which point they are re-evaluated

For more information, and to nominate candidates, please visit

http://developer.force.com/mvp
P Join the conversation on Twitter: #forcewebinar @forcedotcom

Get Trained and Certified


DEV-531 Introduction to Object Oriented Programming with Apex Code Take 15% off any DEV-531 registration. Minimal OOP experience Enter promo code ACW15 when registering DEV-501 Apex Codebefore and May 1st, 2011. and attend Visualforce Page Controllers Cannot be combined with other special offers or discounts.
Experience in Java/C#

Advanced Developer Certification

http://salesforce.com/training

Join the conversation on Twitter: #forcewebinar @forcedotcom

Apex Code Testing and Coverage Best Practices

Apex Testing and Coverage


Best practices Tips and tricks Patterns and anti-patterns

Wed March 30 2011


7am and 10am PST

http://bit.ly/apex_testing
P Join the conversation on Twitter: #forcewebinar @forcedotcom

Question & Answer Session


Please submit questions via the Questions window in the GoToWebinar console
Join the conversation on Twitter: @forcedotcom #forcewebinar

Fill out the webinar survey: http://bit.ly/10am_apex

Join the conversation on Twitter: #forcewebinar @forcedotcom

You might also like