34
Introduction to Force.com Code (Apex) Mark Sivill: salesforce.com Doug Merrett: salesforce.com Developers

Introduction to Force.com Code (Apex)

Embed Size (px)

DESCRIPTION

Understanding the basics of Force.com code (Apex) is essential for developing on the Force.com platform. Force.com code is used to add business logic to applications, write database triggers, and program controllers in the user interface layer. Join us to learn more about this fundamental building block of application development on the Force.com platform.

Citation preview

Page 1: Introduction to Force.com Code (Apex)

Introduction to Force.com Code (Apex)

Mark Sivill: salesforce.comDoug Merrett: salesforce.com

Developers

Page 2: Introduction to Force.com Code (Apex)

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 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 year ended January 31, 2010. 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: Introduction to Force.com Code (Apex)

What we are going to cover

What is Apex

Common use cases

Development lifecycle

Options

Page 4: Introduction to Force.com Code (Apex)

What is Apex

Page 5: Introduction to Force.com Code (Apex)

What’s it similar to

Programming languages – COBOL, Pascal, etc

Syntax close to C# and Java

Compiled

Strongly typed ( Integer, String, etc )

Can be used like database stored procedures / triggers

Page 6: Introduction to Force.com Code (Apex)

How it is different

Runs natively on salesforce servers

Multi-tenant programming language– Governors

Testing required for production

Augment ‘point and click’

Can build code directly in browser

Page 7: Introduction to Force.com Code (Apex)

Integer NUM = 10; Account[] accs; // Clean up old data accs = [select id from account where name like 'test%']; delete accs; accs = new Account[NUM]; for (Integer i = 0; i < NUM; i++){ accs[i] = new Account(name='test ' + i, numberofemployees=i); } insert accs; Contact[] cons = new Contact [0]; for (Account acc : accs){ cons.add(new Contact(lastName=acc.name + '1', accountid=acc.id)); cons.add(new Contact(lastName=acc.name + '2', accountid=acc.id)); } insert cons;

SOQL Query

VariableDeclaration

Control Structure

Array

Data Operation

Apex Code – what it looks like

Page 8: Introduction to Force.com Code (Apex)

Demonstration

Page 9: Introduction to Force.com Code (Apex)

Common use cases

Page 10: Introduction to Force.com Code (Apex)

Common use cases when to use Apex Code

Data integrity ( over multiple objects / records )– custom transactional logic

– complex validation

Custom logic behind web pages

Process incoming emails

Communicating with external systems via ‘web services’

Page 11: Introduction to Force.com Code (Apex)

Implementing Triggers

Apex Code that executes before or after a DML event– Work in same way as database triggers

– DML events include: insert, update, delete, undelete

– Before and After events• Before triggers can update or validate values before they are

saved

• After triggers can access field values to affect changes in other

records

– Access to “old” & “new” lists of records

Docs -

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_triggers.htm

Page 12: Introduction to Force.com Code (Apex)

Example: Prevent Opportunity Deletion

Scenario: Prevent a user from deleting an opportunity if

an active quote exists against the opportunity

trigger oppTrigger on Opportunity (before delete){ Opportunity o;

for (Quote__c q : [select Opportunity__c from Quote__c where Opportunity__c in :Trigger.oldMap.keySet()]) {

o = Trigger.oldMap.get(q.Opportunity__c);

o.addError('Cannot delete an opportunity with active quote');

}}

Validation Error

Reference old values

Execute code before

delete

Page 13: Introduction to Force.com Code (Apex)

Demonstration

Page 14: Introduction to Force.com Code (Apex)

Logic for web pages - Visualforce controller

Separates presentation from logic

Provide custom logic behind web page– Deliveries data to Visualforce

– Receives actions from Visualforce (for example button click)

Look for /apex/page_name in URL

Appexchange - Employee Directory

http://sites.force.com/appexchange/listingDetail?listingId=a0N300000016ck6EAA

Page 15: Introduction to Force.com Code (Apex)

Demonstration

Page 16: Introduction to Force.com Code (Apex)

Process incoming emails - Email Services

Associate Salesforce-generated email addresses to a

automated process e.g. creates contact record based on email address and associate new

case record to it

Email Service can process contents, headers, and

attachments of inbound email

Generated email address – [email protected]

Example - http://wiki.developerforce.com/index.php/Force.com_Email_Services

Page 17: Introduction to Force.com Code (Apex)

Email Service Example: Create New Contactglobal class CreateNewContactEmail implements Messaging.InboundEmailHandler{ global Messaging.InboundEmailResult handleInboundEmail (Messaging.inboundEmail email, Messaging.inboundEnvelope env) { Messaging.inboundEmailResult result = new Messaging.inboundEmailResult (); Contact Con; try { Con = [select Name from Contact where Email = :email.fromAddress limit 1]; } catch (QueryException e) { String Name = email.fromName; if (Name == '' || Name == null) { Name = email.fromAddress; } Con = new Contact (LastName = Name, eMail = email.fromAddress); insert Con; } result.success = true; return result; }}

Bootstrap to inbound

email

Reference From

Address

Reference From Name

Was processing successful?

Page 18: Introduction to Force.com Code (Apex)

Demonstration

Page 19: Introduction to Force.com Code (Apex)

Consume external Web Services

SOAP– ‘Generate from WSDL’ creates Apex stub classes from WSDL.

Similar to• WSDL2Java (Java)

• Svcutil.exe (Microsoft)

Build your own– Using HTTPRequest

• REST

• JSON

Example - http://wiki.developerforce.com/index.php/Apex_Web_Services_and_Callouts

Page 20: Introduction to Force.com Code (Apex)

Send SMS message

Send text message details from Salesforce to third party SMS

gateway which sends message to phone

Page 21: Introduction to Force.com Code (Apex)

Demonstration

Page 22: Introduction to Force.com Code (Apex)

Development lifecycle

Page 23: Introduction to Force.com Code (Apex)

Governors

Protect tenants from monopolizing resources– Database ( number of database statements – 20 )

– Callouts ( HTTP request of Web service calls – 10 )

Creates responsive applications

‘Bulk’ the code – e.g. queries in loops is bad

Use test classes to find code that breaks limits– Test processing more than 200 records

More info - http://wiki.developerforce.com/index.php/Governors_in_Apex_Code

Page 24: Introduction to Force.com Code (Apex)

Test Coverage

Promoting Apex from sandboxes / developer accounts

75 percent of code must be covered

Use System Asserts to check expected results

Tests are run on both development and live

environments

Can’t assume what data exists so create it

Test Data only exists for period of testing

More info -http://wiki.developerforce.com/index.php/An_Introduction_to_Apex_Code_Test_Methods

Page 25: Introduction to Force.com Code (Apex)

Test class for opportunity trigger@isTestprivate class OpportunityBeforeDeleteTest{ static testMethod void BeforeDeleteTest() { Account acc = new Account(name = 'Dreamforce test'); insert acc;

List<Opportunity> opps = new List<Opportunity>(); for (Integer i=0; i<201; i++) { opps.add(new Opportunity (name='Opportunity' ...)); }

insert opps; Test.StartTest(); delete opps; Test.StopTest(); }}

Governor limit reset for

test

Create test data

Test Class declaration

Page 26: Introduction to Force.com Code (Apex)

Demonstration

Page 27: Introduction to Force.com Code (Apex)

Options

Page 28: Introduction to Force.com Code (Apex)

Sign up for free developer account

Set up a free Salesforce Developer account

Visit http://developer.force.com/join

Fill out the form

Wait for the email with user credentials

Click link in email

Page 29: Introduction to Force.com Code (Apex)

Useful resources

Dreamforce sessions– Fireside Chat: Force.com Code (Apex)

– Hands-On: Introduction to Force.com Code (Apex) for Developers

Training courses– http://www.salesforce.com/services-training/training_certification/

iTunes– http://itunes.apple.com/us/podcast/salesforce-com-training-certific

ation

Source code scanner– http://security.force.com/sourcescanner

Page 30: Introduction to Force.com Code (Apex)

More useful resources

On the web– http://www.salesforce.com/us/developer/docs/apexcode/index.htm

– http://developer.force.com

– http://developer.force.com/workbook

iTunes– http://itunes.apple.com/us/podcast/salesforce-com-training-certific

ation

Force.com Labs on Appexchange– https://sites.secure.force.com/appexchange/home

Code Share– http://developer.force.com/codeshare

Page 31: Introduction to Force.com Code (Apex)

Introduction to Force.com Code (Apex)

Page 32: Introduction to Force.com Code (Apex)

D I S C O V E R

Visit the Developer Training and Support Booth in Force.com Zone

Discover

Developer

Learning Paths

Developer training, certification and support resources

S U C C E S SFind us in the Partner Demo Area of

Force.com Zone 2nd Floor Moscone West

that help you achieve

Learn about Developer

Certifications

Page 33: Introduction to Force.com Code (Apex)

Remember. . .

Check Chatter for additional session information

Get your developer Workbooks and Cheat Sheets in

the Force.com Zone

Visit for more information related

to this topicDon’t forget the survey!

Page 34: Introduction to Force.com Code (Apex)

How Could Dreamforce Be Better? Tell Us!

Log in to the Dreamforce app to submit

surveys for the sessions you attendedUse the

Dreamforce Mobile app to submit

surveysEvery session survey you submit is

a chance to win an iPod nano!

OR