You are on page 1of 47

Apex, Visualforce and Integration

Apex

Agenda
Model View Controller (MVC) Apex Introduction Use cases with examples

Model View Controller


Separating domain logic enables independent
Development Testing Maintenance

MVC Framework for Business Users


Model
Objects Fields Record Types Relationships Formulas Validation Rules Workflow Rules & Actions Page layouts (view & edit forms) Tabs Lookup controls Overview Pages List views Web tabs Standard action buttons Standard page flows

Build simple form-based apps with clicks not code

View

Controller

MVC Framework for Developers


Model
Objects Fields Record Types Relationships Formulas Validation Rules Workflow Rules & Actions Apex Programming Language Apex Classes & Interfaces Page layouts (view & edit forms) Tabs Lookup controls Overview Pages List views Web tabs Visualforce Pages Visualforce Page UI Component Library Custom actions Standard action overrides Parameterized web links Apex Controllers Apex Web Service Callouts

Build powerful apps with complex business logic & richly interactive user interfaces

View

Controller

What is Apex Code?


C# and Java-like syntax for creating logic and manipulating data Compiled and strongly typed Scope similar to stored procedures Transactional Runs natively on salesforce servers Multi-tenant programming language

Apex Code what it looks like


Variable Declaration

Control Structure

Array

Data Operation

Integer NUM = 10; SOQL Account[] accs; Query // 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;

Why is Apex Code used?


Going beyond point and click
Long running transaction Process incoming emails Data integrity

Custom logic behind visualforce pages


Process centric integration

Apex use cases


Batch Apex
Long running background processes

Email Services
Receive emails and process contents

Implementing Triggers
Code runs when data changes to ensure business logic is applied

Visualforce
Controllers and Controller Extensions

Create new Web Services


Special purpose, custom output format, data transactions

Consume external Web Services


Data mashups, data enhancement, integration

Batch Apex
Use Cases
Data cleansing Weekly / monthly processing

Runs asynchronously (jobs queued)

Can be started in a trigger or by apex scheduler


Can process millions of records Apex jobs are monitored

Example: Cleanse account data


Batchable interface global class ReplaceStateNames2 implements Database.Batchable<SObject>{ global Map<String,String> st2state; global ReplaceStateNames2() { st2state = new Map<String,String>(); st2state.put('ALABAMA','AL'); .. } Identify rows to process global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator([SELECT MailingAddressState__c FROM Provider__c WHERE StateLen__c > 2]); } global void finish(Database.BatchableContext BC){} global void execute(Database.BatchableContext BC, List<sObject> scope){ for(SObject s : scope) { String newState = st2state.get( (String)s.get('MailingAddressState__c') ); if(newState==null) { newState = '--'; } s.put('MailingAddressState__c', newState); } update scope; } }

Post processing Processing per batch

Email Services
Associate Salesforce-generated email addresses to a automated process
e.g. create an email service that automatically creates contact records based on contact information in messages.

Email Service can process contents, headers, and attachments of inbound email
Example generated email address
createcontact@52jdm7gr0mnvjhbxkxtlz5k9c.in.salesforce.com

Example: Create New Contact


Bootstrap to inbound email global 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) { // No Contact with that email address, so create one 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; } }

Reference From Address

Reference From Name

Was processing successful?

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 (.oldMap & .newMap)


Triggers need to be designed to process multiple records at a time (API based invocation can submit multiple records)

Example: Prevent Opportunity Deletion


Scenario: Prevent a user from deleting an opportunity if an active quote exists against the opportunity
Execute code before delete

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

Reference old values

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


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

Validation Error

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

Visualforce

Agenda
Visualforce Introduction Visualforce in MVC Use cases with examples

Introducing Visualforce
Any design for any web device

What is Visualforce?
A way to create custom graphical interfaces
with Images, JavaScript, Style Sheets, Flash, Silverlight

ASP / JSP like tag-based mark-up Uses model / controller Runs natively on salesforce servers Reusable component model

Visualforce what it looks like


Connecting to Controller

<apex:page standardController="Account"> <apex:sectionHeader title="Simple Account Create" /> <apex:form>

Reusable component

<apex:pageBlock title="Account Information"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save" /> </apex:pageBlockButtons> <apex:pageBlockSection> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.phone}"/> </apex:pageBlockSection>

Accessing fields

</apex:pageBlock>
Data entry form

</apex:form> </apex:page>

Visualforce generated page


<apex:page standardController="Account"> <apex:sectionHeader title="Simple Account Create" />

<apex:form>
<apex:pageBlock title="Account Information"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save" /> </apex:pageBlockButtons>

<apex:pageBlockSection> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.phone}"/> </apex:pageBlockSection>


</apex:pageBlock> </apex:form> </apex:page>

Why is Visualforce used?


Pixel level control of GUI Generating PDF documents Augment point and click page layouts Build external micro-sites
Capture HTML form data directly in salesforce

Performance
Compiled code executed on servers (not JavaScript on browsers)

View: Visualforce Pages

Canvas or design surface similar to standard Web development model Composed of HTML, Page tags and merge fields Ability to reference any CSS, Flex, AJAX or other Web technology
<apex:repeat value="{!Posts}" var="post"> <a class="title" href="/apex/blogedit?id={!post.Id}" target="_top">{!post.Name}</a> {!post.Post__c}<p>

Supports standard query strings for parameters, referenced via /apex/page_name url syntax Composed on the server, not the client

View: Visualforce Components

Create Standard UI elements, such as detail areas and related lists, with a single tag Built in data binding

Special UI elements, such as tab panels and repeat (iterators)


Built in AJAX functionality supporting incremental page refresh

Over 50 components in the first release


Accessed through <apex:tag> syntax

Controller: Visualforce Controllers

Controllers contain the logic and data references a page uses Separates presentation from logic Created in Apex code providing full access to Apex functionality (API, Web services, etc) Pages interact with controllers through components Maintain state across page interactions Standard controllers implement normal app behavior (view, edit, save, etc)

Visualforce Examples
Visualforce Tab
Employee Directory

Embedded in page layout


Salesforce International Mapping using Google Maps

Button / Link
Salesforce International Mapping using Google Maps

Page / Button Override


Account / Salesforce International Mapping using Google Maps

PDF generation
Simple Quote

Sites
Wireless Craze

Integration

Agenda
Integration Introduction
Case studies

Styles of Integration with demonstrations


Web services API

Further integration

Integration is Faster, Easier and Lower Risk with Force.com


Web Services API
100+ Million API calls per day > 50% of traffic: API integration transactions

Interoperability with Leading Cloud Platforms


Back-end and Desktop Integration Consume and Publish web services Over 40 Certified Integration Middleware Partners

All Integrations Are Upgraded With Zero Customer Effort

Integration Partners
Low Complexity
Composite Apps/SOA
Enterprise Mash-ups Rich user interface

Medium Complexity

High Complexity

Application Integration
Real-time integration
Multi-step integration Human workflow

Data Integration
Data migration Data replication Bulk Data Transfers

Data Cleansing
Data deduplication Data assessment

Over 40 Certified Solutions

Improved Visibility and Reporting Across Multiple Applications

Corporate Data Warehouse

Contact Management System

Challenge
Wanted to integrate customer information contained within Salesforce and custom contact management application. Provide a business intelligence reporting platform

Solution
Selected Relational Junction Salesforce data replication to a relational database Used existing tool sets for a custom integration between the Relational Junction schema and internal systems

Results
Delivered a consistent view of customer data in internal systems an in Salesforce.com Able to use existing database level integration tools

Able to use current reporting tool set

Visibility Across 13 Separate Data Silos Delivers Enterprise Efficiencies

13 Unique Organization data feeds Oracle, SQL, Other

IIP Business Intelligence and Reporting Server

Challenge
Funding based on ability to show and prove the impact for the company Dealing with multiple data sources and targets in SQL, Oracle, and others; there were 13 separate U.K. orgs form partnership Manual replication and synchronization of data Lack of confidence in same view of data Replication errors unknown Manual intervention in lead process was time consuming, costly, and inaccurate Final hurdle in cleansing program

Solution
Chose Pervasive Data Integrator: Speed of Implementation (end of Financial Year Gov. funded body) Ease of Use Automated Integration reduced manual work Scalability & Performance across multiple applications provides room for future growth

Results
No manual intervention increases accuracy and productivity One view of data Productive management of integration Ability to support business expansion Improved Reporting Fast ROI & proof of Value to Management

Better Pipeline Visibility for Manufacturing Firm With SAP Integration

SAP

Challenge
Sales teams spent too much time entering account data instead of with customers Needed to increase cross- and up-selling Wanted to improve collaboration between global sales and marketing teams across 50 product lines Multiple applications produced disparate views of the customer

Solution
Implemented a 360-degree view of the customer across the company Deployed Salesforce to 800 users in 20-plus countries Integration to SAP with Web Methods Middleware, the Force.com Web Services API, and a flat file extract. SAP is used as the Account and Product Master

Results
Streamlined sales processes mean sales reps and resellers have more time to focus on selling Multilanguage & multicurrency support simplify the activities of a global organization Strong adoption drives worldwide collaboration Reps have the time to go after bigger deals and have higher visibility into the sales pipeline

Three Styles of Integration

Security

User Interface

Screens exposed to the end users / Mashups Your business logic


(in C, Java, Apex + workflows, rules, etc.)

Application Logic

Data Layer

Your Data Model

User Interface Integration


Peoplesoft Hurricane Tracker Mashup

User interface example Google Maps


Mashup Google Maps into salesforce Integrate via URL

Logic Integration
Master Account Check

Real-time Call Out

Consume external Web Services


Generate from WSDL creates Apex stub classes from WSDL. Similar to
WSDL2Java (Java) Svcutil.exe (Microsoft)

Use Apex stub classes/methods in other Apex classes

Logic example send SMS message


Send text message details from salesforce to third party SMS gateway which sends message to phone

Data Integration
Invoice Example

Salesforce Account Data

SAP Material Master Pushed into SFDC Custom Object via API / Data Feed

Force.com web services API


Standards compliant
Simple Object Access Protocol (SOAP) 1.1
Web Service Description Language (WSDL) 1.1 WS-I Basic Profile 1.1

Secure
Supports Secure Sockets Layer (SSL) protocol SSLv3 Username/Password Credential Authentication Support for SAML and other token mechanisms

Exposes
Standard Salesforce Objects. Custom Salesforce Objects Custom fields on all objects

Boot strapping onto web services API

Username/Password
https
Internet

URL/Session ID Token

Request Message
Session Header

Session ID Token
Message Body

Operation = Create
sObject

https

Internet

Account

Response Message
Response

ReturnData Fault

Force.com web services API operations


Data
Create Update Delete Upsert (do either update or insert)

Describe Metadata
describeGlobal (get all objects) describeSObjects (field and properties for object)

Utility
resetPassword getUserInfo

Salesforce Data Loader


CSV and Database based batch processes

CSV and JDBC field mapping to salesforce schema Connectivity to all major Databases (Oracle, MS SQL Server, MySQL) through JDBC Interactive or Command Line use, can be scheduled

Custom integration - Create chatter feed item


Using an custom external process (Java) copy data from an external system (Yahoo Weather RSS) and insert into salesforce

Further integration

Middleware / Developer toolkits

Force.com Data Loader

Force.com IDE Migration Tool Custom Tools


Web Service Endpoint Web Service Endpoint

Data services

Data Upload

Custom Logic

Call External Web Service

Outbound Messaging

Customization & Config

Web Services API

Bulk API

Apex Web Services


Apex Callouts

Metadata API

Workflow

You might also like