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.

Hca advanced developer workshop


Published on

Advanced Workshop slides for HCA

Published in: Technology, Business
  • Be the first to comment

Hca advanced developer workshop

  1. 1. HCA Advanced Developer Workshop David Scruggs Platform Architect 770-837-0241
  2. 2. 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, 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 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 quarter ended July 31, 2011. 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., inc. assumes no obligation and does not intend to update these forward-looking statements.
  3. 3. Agenda  Introduction to the Salesforce1 Platform  Salesforce1 + Visualforce  Salesforce1 + Canvas  Apex + APIs  Wrap-Up
  4. 4. Introduction to the Salesforce1 Platform
  5. 5. Salesforce1 Platform 6B Lines of Apex 500M API Calls Per Day 4M+ Apps Built on the Platform 72B Records Stored Salesforce is a Platform Company. Period. -Alex Williams, TechCrunch
  6. 6. Salesforce1 Platform APIs REST APIs Bulk APIs Tooling APIs Metadata APIs Analytics APIs Social APIs ET API Streaming APIs Mobile SDK Mobile Packs Offline Support Geolocation Custom Actions Identity Private App Exchange Mobile Notifications Visualforce 1 Chatter Mobile Services SOAP APIs Workflows Analytics Apex Multilanguage Heroku Add-Ons Email Service s ET 1:1 ET Fuel Multi-tenant Cloud Database Data-level Security Schema Builder Sharing Model Translation Workbench Search Heroku1 Monitoring Core Services
  7. 7. Program Materials
  8. 8. Free Developer Environment
  9. 9. Program Materials Workbook Slides vescruggs/hca-advanceddeveloper-workshop
  10. 10. Warehouse Data Model Invoice Number Status Count Total INV-01 Shipped 16 $370 INV-02 New 20 $400 Merchandise Invoice Line Items Line Merchandise Units Sold Value INV-01 1 Pinot 1 $20 INV-01 2 Cabernet 5 $150 INV-01 3 Malbec 10 $200 INV-02 1 Pinot 20 $400 Install in your org: Name Price Inventory Pinot Invoice $20 15 Cabernet $30 10 Malbec $20 20
  11. 11. APEX
  12. 12. Apex Cloud based programming language
  13. 13. Apex Anatomy  Class and Interface based  Scoped Variables public with sharing class myControllerExtension implements Util { private final Account acct; public Contact newContact {get; set;} public myControllerExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord(); } public PageReference associateNewContact(Id cid) { newContact = [SELECT Id, Account from Contact WHERE Id =: cid LIMIT 1]; newContact.Account = acct; update newContact; Inline SOQL } }   Inline DML
  14. 14. Salesforce1 + Visualforce
  15. 15. Visualforce Anatomy Controllers  StandardControllers Custom Custom Extensions <apex:page StandardController="Contact" extensions="duplicateUtility" action="{!checkPhone}"> <apex:form>  Data bound components  Controller Callbacks <apex:outputField var="{!Contact.FirstName}” /> <apex:outputField var="{!Contact.LastName}" /> <apex:inputField var="{!Contact.Phone}" /> <apex:commandButton value="Update" action="{!quicksave}" /> </apex:form> </apex:page>
  16. 16. } JavaScript Remoting @RemoteAction public static String updateMerchandiseItem(String productId, Integer newInventory) { List<Merchandise__c> m = [SELECT Id, Total_Inventory__c from Merchandise__c WHERE Id =: productId LIMIT 1]; if (m.size() > 0) { m[0].Total_Inventory__c = newInventory; try { update m[0]; return 'Item Updated'; } catch (Exception e) { return e.getMessage(); $(".updateBtn").click(function() { } var id = j$(this).attr('data-id'); } var inventory = parseInt(j$("#inventory"+id).val()); else { $.mobile.showPageLoadingMsg(); return 'No item found with that ID'; } MobileInventoryExtension.updateMerchandiseItem(id, inventory,handleUpdate); } });  Access Apex from JavaScript  Asynchronous Responses Apex JavaScript in Visualforce
  17. 17. Custom Components <apex:component controller="GeoComponentController"> <apex:attribute name="lat" type="Decimal" description="Latitude for geolocation query" assignTo="{!lat}” /> <apex:attribute name="lon" type="Decimal" description="Longitude for geolocation query" assignTo="{!lon}” /> <c:GeoComponent lat=”8.9991" lon=”10.0019" />
  18. 18. Page Templates <apex:page > <apex:insert name="detail" /> <div style="position:relative; clear:all;"> <apex:insert name="footer" /> </div> </apex:page> <apex:page StandardController="Invoice__c" > <apex:composition template="WarehouseTemplate"> <apex:define name="detail"> <apex:detail subject="{!Invoice__c.Id}" /> </apex:define>
  19. 19. Chatter Components <chatter:follow/> <chatter:newsfeed/> <chatter:feed/> <chatter:followers/> <chatter:feedAndFollowers/>
  20. 20. Common Use Cases Email Templates Embed in Page Layouts Mobile Interfaces Generate PDFs Page Overrides
  21. 21. Visualforce Controllers Apex for constructing dynamic pages
  22. 22. Viewstate Hashed information block to track server side transports
  23. 23. Reducing Viewstate //Transient data that does not get sent back, //reduces viewstate transient String userName {get; set;} //Static and/or private vars //also do not become part of the viewstate static private integer VERSION_NUMBER = 1;
  24. 24. Reducing Viewstate //Asynchronous JavaScript callback. No viewstate. //RemoteAction is static, so has no access to Controller context @RemoteAction public static Account retrieveAccount(ID accountId) { try { Account a = [SELECT ID, Name from ACCOUNT WHERE Id =:accountID LIMIT 1]; return a; } catch (DMLException e) { return null; } }
  25. 25. Handling Parameters //check the existence of the query parameter if(ApexPages.currentPage().getParameters().containsKey(„id‟)) { try { Id aid = ApexPages.currentPage().getParameters().get(„id‟); Account a = [SELECT Id, Name, BillingStreet FROM Account WHERE ID =: aid]; } catch(QueryException ex) { ApexPages.addMessage(new ApexPages.Message( ApexPages.Severity.FATAL, ex.getMessage())); return; } }
  26. 26. SOQL Injection String account_name = ApexPages.currentPage().getParameters().get('name'); account_name = String.escapeSingleQuotes(account_name); List<Account> accounts = Database.query('SELECT ID FROM Account WHERE Name = '+account_name);
  27. 27. Cookies //Cookie = //new Cookie(String name, String value, String path, // Integer milliseconds, Boolean isHTTPSOnly) public PageReference setCookies() { Cookie companyName = new Cookie('accountName','TestCo',null,315569260,false); ApexPages.currentPage().setCookies(new Cookie[]{companyName}); return null; } public String getCookieValue() { return ApexPages.currentPage(). getCookies().get('accountName').getValue(); }
  28. 28. Inheritance and Construction public with sharing class PageController implements SiteController { public PageController() { } public PageController(ApexPages.StandardController stc) { }
  29. 29. Controlling Redirect //Stay on same page return null; //New page, no Viewstate PageReference newPage = new Page.NewPage(); newPage.setRedirect(true); return newPage; //New page, retain Viewstate PageReference newPage = new Page.NewPage(); newPage.setRedirect(false); return newPage;
  30. 30. Unit Testing Pages //Set test page Test.setCurrentPage(Page.VisualforcePage); //Set test data Account a = new Account(Name='TestCo'); insert a; //Set test params ApexPages.currentPage().getParameters().put('id',a.Id); //Instatiate Controller SomeController controller = new SomeController(); //Make assertion System.assertEquals(controller.AccountId,a.Id)
  31. 31. Visualforce Components Embedding content across User Interfaces
  32. 32. Visualforce Dashboards Custom Controller Dashboard Widget <apex:page controller="retrieveCase" tabStyle="Case"> <apex:pageBlock> {!contactName}s Cases <apex:pageBlockTable value="{!cases}" var="c"> <apex:column value="{!c.status}"/> <apex:column value="{!c.subject}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
  33. 33. Page Overrides Select Override Define Override
  34. 34. Templates Layout inserts Define with Composition <apex:page controller="compositionExample"> <apex:form > <apex:insert name=”header" /> <br /> <apex:insert name=“body" /> <apex:composition template="myFormComposition <apex:define name=”header"> <apex:outputLabel value="Enter your favorite m <apex:inputText id=”title" value="{!mealField}" </apex:define> <h2>Page Content</h2>
  35. 35. Custom Components Define Attributes <apex:component controller="WarehouseAccounts <apex:attribute name="lat" type="Decimal" descrip Query" assignTo="{!lat}"/> <apex:attribute name="long" type="Decimal" desc Geolocation Query" assignTo="{!lng}"/> <apex:pageBlock > public with sharing class WarehouseAccountsCont Assign to Apex public Decimal lat {get; set;} public Decimal lng {get; set;} private List<Account> accounts; public WarehouseAccountsController() {}
  36. 36. Page Embeds Standard Controller Embed in Layout <apex:page StandardController=”Account” showHeader=“false” <apex:canvasApp developerName=“warehouseDev” applicationName=“procure”
  37. 37. Extending Salesforce1 with Visualforce Pages Time: 60 Minutes
  38. 38. Salesforce1 + Canvas
  39. 39. Canvas Framework for using third party apps within Salesforce
  40. 40. Canvas Anatomy Any Language, Any Platform • • • • • Only has to be accessible from the user’s browser Authentication via OAuth or Signed Response JavaScript based SDK can be associated with any language Within Canvas, the App can make API calls as the current user apex:CanvasApp allows embedding via Visualforce
  41. 41. Integrating Your Web Applications in Salesforce1 with Canvas Time: 45 Minutes
  42. 42. Apex + APIs
  43. 43. “Universal Connectors”
  44. 44. Apex Triggers Event based programmatic logic
  45. 45. Controlling Flow trigger LineItemTrigger on Line_Item__c (before insert, before update) { //separate before and after if(Trigger.isBefore) { //separate events if(Trigger.isInsert) { System.debug(„BEFORE INSERT‟); DelegateClass.performLogic(; //
  46. 46. Delegates public class BlacklistFilterDelegate { public static Integer FEED_POST = 1; public static Integer FEED_COMMENT = 2; public static Integer USER_STATUS = 3; List<PatternHelper> patterns {set; get;} Map<Id, PatternHelper> matchedPosts {set; get;} public BlacklistFilterDelegate() { patterns = new List<PatternHelper>(); matchedPosts = new Map<Id, PatternHelper>(); preparePatterns(); }
  47. 47. Static Flags public with sharing class AccUpdatesControl { // This class is used to set flag to prevent multiple calls public static boolean calledOnce = false; public static boolean ProdUpdateTrigger = false; }
  48. 48. Chatter Triggers trigger AddRegexTrigger on Blacklisted_Word__c (before insert, before update) { for (Blacklisted_Word__c f : { if(f.Custom_Expression__c != NULL) { f.Word__c = ''; f.Match_Whole_Words_Only__c = false; f.RegexValue__c = f.Custom_Expression__c; } else f.RegexValue__c = RegexHelper.toRegex(f.Word__c, f.Match_Whole_Words_Only__c); } }
  49. 49. Scheduled Apex Cron-like functionality to schedule Apex tasks
  50. 50. Schedulable Interface global with sharing class WarehouseUtil implements Schedulable { //General constructor global WarehouseUtil() {} //Scheduled execute global void execute(SchedulableContext ctx) { //Use static method for checking dated invoices WarehouseUtil.checkForDatedInvoices(); }
  51. 51. Schedulable Interface Via Apex Via Web UI System.schedule('testSchedule','0 0 13 * * ?', new WarehouseUtil());
  52. 52. Batch Apex Functionality for Apex to run continuously in the background
  53. 53. Batchable Interface global with sharing class WarehouseUtil implements Database.Batchable<sObject> { //Batch execute interface global Database.QueryLocator start(Database.BatchableContext BC){ //Start on next context } global void execute(Database.BatchableContext BC, List<sObject> scope) { //Execute on current scope } global void finish(Database.BatchableContext BC) { //Finish and clean up context }
  54. 54. Unit Testing Test.StartTest(); System.schedule('testSchedule','0 0 13 * * ?',new,WarehouseUtil()); ID batchprocessid = Database.executeBatch(new WarehouseUtil()); Test.StopTest();
  55. 55. OAuth Industry standard method of user authentication
  56. 56. OAuth2 Flow Sends App Credentials User logs in, Token sent to callback Remote Application Confirms token Send access token Maintain session with refresh token Salesforce Platform
  57. 57. Apex Endpoints Exposing Apex methods via SOAP and REST
  58. 58. Apex SOAP global class MyWebService { webService static Id makeContact(String lastName, Account a) { Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id); insert c; return; } }
  59. 59. Apex REST @RestResource(urlMapping='/CaseManagement/v1/*') global with sharing class CaseMgmtService { @HttpPost global static String attachPic(){ RestRequest req = RestContext.request; RestResponse res = Restcontext.response; Id caseId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); Blob picture = req.requestBody; Attachment a = new Attachment (ParentId = caseId, Body = picture, ContentType = 'image/
  60. 60. Apex Email Classes to handle both incoming and outgoing email
  61. 61. Outgoing Email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String body = count+' closed records older than 90 days have been deleted'; //Set addresses based on label mail.setToAddresses(Label.emaillist.split(',')); mail.setSubject ('[Warehouse] Dated Invoices'); mail.setPlainTextBody(body); //Send the email Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
  62. 62. Incoming Email global class PageHitsController implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail( Messaging.inboundEmail email, Messaging.InboundEnvelope env) { if(email.textAttachments.size() > 0) { Messaging.InboundEmail.TextAttachment csvDoc = email.textAttachments[0]; PageHitsController.uploadCSVData(csvDoc.body); } Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); result.success = true; return result; }
  63. 63. Incoming Email Define Service Limit Accepts
  64. 64. Team Development Tools for teams and build masters
  65. 65. Metadata API API to access customizations to the platform
  66. 66. Migration Tool Ant based tool for deploying applications
  67. 67. Continuous Integration Development Testing Source Control DE CI Tool Sandbox Fail Notifications
  68. 68. Tooling API Access, create and edit application code
  69. 69. Tutorial 472 – Create an App Time: 30 Minutes Note: use as the Gist.
  70. 70. Double-click to enter title The Wrap Up Double-click to enter text