Introduction to Force.com Code (Apex)
Mark Sivill: salesforce.comDoug Merrett: salesforce.com
Developers
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.
What we are going to cover
What is Apex
Common use cases
Development lifecycle
Options
What is 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
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
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
Demonstration
Common use cases
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’
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
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
Demonstration
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
Demonstration
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
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
Reference From
Address
Reference From Name
Was processing successful?
Demonstration
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
Send SMS message
Send text message details from Salesforce to third party SMS
gateway which sends message to phone
Demonstration
Development lifecycle
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
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
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
Demonstration
Options
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
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
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
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
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!
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