Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to Code (Apex)


Published on

Understanding the basics of code (Apex) is essential for developing on the platform. 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 platform.

Introduction to Code (Apex)

  1. 1. Introduction to Code (Apex)<br />Developers<br />Mark Sivill:<br />Doug Merrett:<br />
  2. 2. Safe Harbor<br />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, 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.<br />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 products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of, 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. <br />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., inc. assumes no obligation and does not intend to update these forward-looking statements.<br />
  3. 3. What we are going to cover<br />What is Apex<br />Common use cases<br />Development lifecycle<br />Options<br />
  4. 4. What is Apex<br />
  5. 5. What’s it similar to<br />Programming languages – COBOL, Pascal, etc<br />Syntax close to C# and Java<br />Compiled<br />Strongly typed ( Integer, String, etc )<br />Can be used like database stored procedures / triggers<br />
  6. 6. How it is different<br />Runs natively on salesforce servers<br />Multi-tenant programming language<br />Governors<br />Testing required for production<br />Augment ‘point and click’<br />Can build code directly in browser<br />
  7. 7. Integer NUM = 10; <br />Account[] accs; <br />// Clean up old data <br />accs = [select id from account where name like 'test%']; <br />delete accs; <br />accs = new Account[NUM]; <br />for (Integer i = 0; i < NUM; i++)<br />{ <br />accs[i] = new Account(name='test ' + i, numberofemployees=i); <br />} <br />insert accs; <br />Contact[] cons = new Contact [0]; <br />for (Account acc : accs)<br />{ <br />cons.add(new Contact( + '1',; <br />cons.add(new Contact( + '2',; <br />} <br />insert cons;<br />Variable<br />Declaration<br />SOQL Query<br />Control Structure<br />Array<br />Data Operation<br />Apex Code – what it looks like<br />
  8. 8. Demonstration<br />
  9. 9. Common use cases<br />
  10. 10. Common use cases when to use Apex Code <br />Data integrity ( over multiple objects / records )<br />custom transactional logic<br />complex validation<br />Custom logic behind web pages<br />Process incoming emails<br />Communicating with external systems via ‘web services’<br />
  11. 11. Implementing Triggers<br />Apex Code that executes before or after a DML event<br />Work in same way as database triggers<br />DML events include: insert, update, delete, undelete<br />Before and After events<br />Before triggers can update or validate values before they are saved<br />After triggers can access field values to affect changes in other records<br />Access to “old” & “new” lists of records<br />Docs -<br />
  12. 12. Example: Prevent Opportunity Deletion<br />Scenario: Prevent a user from deleting an opportunity if an active quote exists against the opportunity<br />trigger oppTrigger on Opportunity (before delete)<br />{<br /> Opportunity o;<br /> for (Quote__c q : [select Opportunity__c from Quote__c<br /> where Opportunity__c in :Trigger.oldMap.keySet()])<br /> {<br /> o = Trigger.oldMap.get(q.Opportunity__c);<br /> o.addError('Cannot delete an opportunity with active quote');<br /> }<br />}<br />Execute code before delete<br />Reference old values<br />Validation Error<br />
  13. 13. Demonstration<br />
  14. 14. Logic for web pages - Visualforce controller<br />Separates presentation from logic<br />Provide custom logic behind web page<br />Deliveries data to Visualforce<br />Receives actions from Visualforce (for example button click)<br />Look for /apex/page_name in URL<br />Appexchange - Employee Directory<br />
  15. 15. Demonstration<br />
  16. 16. Process incoming emails - Email Services<br />Associate Salesforce-generated email addresses to a automated process<br /><ul><li>e.g. creates contact record based on email address and associate new case record to it
  17. 17. Email Service can process contents, headers, and attachments of inbound email</li></ul>Generated email address <br /><br />Example -<br />
  18. 18. Email Service Example: Create New Contact<br />global class CreateNewContactEmail implements Messaging.InboundEmailHandler<br />{<br /> global Messaging.InboundEmailResulthandleInboundEmail<br /> (Messaging.inboundEmail email, Messaging.inboundEnvelopeenv)<br /> {<br />Messaging.inboundEmailResult result = new Messaging.inboundEmailResult ();<br /> Contact Con;<br /> try<br /> {<br /> Con = [select Name from Contact where Email = :email.fromAddress<br /> limit 1];<br /> }<br /> catch (QueryException e)<br /> {<br /> String Name = email.fromName;<br />if (Name == '' || Name == null)<br /> {<br /> Name = email.fromAddress;<br /> }<br /> Con = new Contact (LastName = Name, eMail = email.fromAddress);<br /> insert Con;<br /> } <br />result.success = true;<br /> return result;<br /> }<br />}<br />Bootstrap to inbound email<br />Reference From Address<br />Reference From Name<br />Was processing successful?<br />
  19. 19. Demonstration<br />
  20. 20. Consume external Web Services<br />SOAP<br />‘Generate from WSDL’ creates Apex stub classes from WSDL. Similar to<br />WSDL2Java (Java)<br />Svcutil.exe (Microsoft)<br />Build your own<br />Using HTTPRequest<br />REST<br />JSON<br />Example -<br />
  21. 21. Send SMS message<br />Send text message details from Salesforceto third party SMS gateway which sends message to phone<br />
  22. 22. Demonstration<br />
  23. 23. Development lifecycle<br />
  24. 24. Governors<br />Protect tenants from monopolizing resources<br />Database ( number of database statements – 20 )<br />Callouts ( HTTP request of Web service calls – 10 )<br />Creates responsive applications<br />‘Bulk’ the code – e.g. queries in loops is bad<br />Use test classes to find code that breaks limits<br />Test processing more than 200 records<br />More info -<br />
  25. 25. Test Coverage<br />Promoting Apex from sandboxes / developer accounts<br />75 percent of code must be covered<br />Use System Asserts to check expected results<br />Tests are run on both development and live environments<br />Can’t assume what data exists so create it<br />Test Data only exists for period of testing<br />More info -<br />
  26. 26. Test class for opportunity trigger<br />@isTest<br />private class OpportunityBeforeDeleteTest<br />{ <br /> static testMethod void BeforeDeleteTest()<br /> {<br /> Account acc = new Account(name = 'Dreamforce test');<br /> insert acc;<br /> List<Opportunity> opps = new List<Opportunity>();<br /> for (Integer i=0; i<201; i++)<br /> {<br />opps.add(new Opportunity (name='Opportunity' ...));<br /> }<br /> insert opps;<br />Test.StartTest(); <br /> delete opps; <br />Test.StopTest(); <br /> }<br />}<br />Test Class declaration<br />Create test data<br />Governor limit reset for test<br />
  27. 27. Demonstration<br />
  28. 28. Options<br />
  29. 29. Sign up for free developer account<br />Set up a free Salesforce Developer account<br />Visit<br />Fill out the form<br />Wait for the email with user credentials<br />Click link in email<br />
  30. 30. Useful resources<br />Dreamforce sessions<br />Fireside Chat: Code (Apex)<br />Hands-On: Introduction to Code (Apex) for Developers<br />Training courses<br /><br />iTunes<br /><br />Source code scanner<br /><br />
  31. 31. More useful resources<br />On the web<br /><br /><br /><br />iTunes<br /><br /> Labs on Appexchange<br /><br />Code Share<br /><br />
  32. 32. Introduction to Force.comCode (Apex)<br />
  33. 33. Visit the Developer Training and Support Booth in Zone<br />D I S C O V E R<br />Developer training, certification and support resources <br />that help you achieve<br />S U C C E S S<br />Find us in the Partner Demo Area of <br /> Zone 2nd Floor Moscone West<br />Learn about Developer Certifications<br />Discover Developer Learning Paths<br />
  34. 34. Remember. . .<br /><ul><li>Check Chatter for additional session information
  35. 35. Get your developer Workbooks and Cheat Sheets in the Zone
  36. 36. Visit for more information related to this topic</li></ul>Don’t forget the survey!<br />
  37. 37. How Could Dreamforce Be Better? Tell Us!<br />Log in to the Dreamforce app to submit<br />surveys for the sessions you attended<br />Use the Dreamforce Mobile app to submit surveys<br />OR<br />Every session survey you submit is a chance to win an iPod nano!<br />