Upload
satkabeer654
View
213
Download
0
Embed Size (px)
Citation preview
7/27/2019 introductiontoapexcode-120510175542-phpapp01
1/31
Coding the Cloud: An Introduction
to Apex Code
Andrew Albert, salesforce.com
Force.com Plat form Fundamentals
7/27/2019 introductiontoapexcode-120510175542-phpapp01
2/31
Safe Harbor Statement
Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-
looking statements including but not limited to statements concerning the potential market for our existing service offerings
and future offerings. All of our forward looking statements involve risks, uncertainties and assumptions. If any such risks or
uncertainties materialize or if any of the assumptions proves incorrect, our results could differ materially from the results
expressed or implied by the forward-looking statements we make.
The risks and uncertainties referred to above include - but are not limited to - risks associated with possible fluctuations in
our operating results and cash flows, rate of growth and anticipated revenue run rate, errors, interruptions or delays in our
service or our Web hosting, our new business model, our history of operating losses, the possibility that we will not remain
profitable, breach of our security measures, the emerging market in which we operate, our relatively limited operatinghistory, our ability to hire, retain and motivate our employees and manage our growth, competition, our ability to continue to
release and gain customer acceptance of new and improved versions of our service, customer and partner acceptance of
the AppExchange, successful customer deployment and utilization of our services, unanticipated changes in our effective
tax rate, fluctuations in the number of shares outstanding, the price of such shares, foreign currency exchange rates and
interest rates.
Further information on these and other factors that could affect our financial results is included in the reports on Forms 10-
K, 10-Q and 8-K and in other filings we make with the Securities and Exchange Commission from time to time. These
documents are available on the SEC Filings section of the Investor Information section of our website atwww.salesforce.com/investor. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-
looking statements, except as required by law.
http://www.salesforce.com/investorhttp://www.salesforce.com/investor7/27/2019 introductiontoapexcode-120510175542-phpapp01
3/31
Andrew AlbertTechnical Evangelist
7/27/2019 introductiontoapexcode-120510175542-phpapp01
4/31
Apex Code: Logic-as-a-Service
What is it?
What can it do?
How do I use it?
Well, lets see it!
7/27/2019 introductiontoapexcode-120510175542-phpapp01
5/31
Introducing Apex
Force.com allows many customizations through User
Interface Force.com API allows developers to write client-side
programs or integrations for more flexibility in their
applications
Client side programs have performance costs
Lack transactional control across API requests
Cost and complexity of client hosting server code
APEX was introduced to address those issues and to
revolutionize the way developers create on-demand
applications.
7/27/2019 introductiontoapexcode-120510175542-phpapp01
6/31
Apex Code Is
Strongly-typed, object-based programming language
Enables developers to execute logic and transaction
control statements on Force.com
Runs natively on the server
Code executes on the server when initiated by UserInterface via Buttons & Events, and data through the
API
Java or C#-like syntax
Transactional
7/27/2019 introductiontoapexcode-120510175542-phpapp01
7/31
How can you use Apex Code?
Database Trigger
- Apex Code that is executed in response to adatabase interaction
Example: Apex trigger is initiated whenever a new
Contact record is inserted.
Class
- Similar to a Java or .NET class
- A trigger can call an Apex Class
7/27/2019 introductiontoapexcode-120510175542-phpapp01
8/31
Differences between Triggers and Classes
Triggers execute impl ic i t lyin response to a database
action Apex class methods can be expl ici t lycalled in many
areas of the Force.com
For example:
(a) Email to Apex Services
(b)Apex Web Services
(c) Visualforce controllers
7/27/2019 introductiontoapexcode-120510175542-phpapp01
9/31
How is Apex Different?
Executes directly on the Force.com
Eliminates network traffic between client applicationand Force.com
Apex Code tightly integrated to the rest of the platform
functionality
Changes to the metadata referenced in Apex Code will
cause an automatic recompilation the next time those
components are executed
7/27/2019 introductiontoapexcode-120510175542-phpapp01
10/31
Language Basics
Data Types Primitive
- String
- Boolean
- Date and DateTime
- Integer, Long, Double
- ID (Force.com database record identifier)
- Blob (for storing binary data)
- Sobject (object representing a Force.com standard or custom
object)
Example:
DateTime dt = System.now() + 1;
Boolean isClosed = true;
String sCapsFirstName = Andrew.toUpperCase();
Account acct = new Account(); //Sobject example
7/27/2019 introductiontoapexcode-120510175542-phpapp01
11/31
Language Basics (cont)
Data Types Collections
- Lists
- Sets
- Maps
- Arrays
Example:List myList = new List();
myList.add(12); //Add the number 12 to the list
myList.get(0); //Access to first integer stored in the List
7/27/2019 introductiontoapexcode-120510175542-phpapp01
12/31
Language Basics (cont)
Statements and Expressions
- If/Else- For Loops
- Do/While Loops
- While Loops
Example:Integer count = 0;
while(count < 11){
System.debug(Count = + count);
count++;
}
7/27/2019 introductiontoapexcode-120510175542-phpapp01
13/31
Language Basics (cont)
Exception Handling
- Try/Catch/Finally statements- Ability to create and throw your own Exceptions
Example:
public class OtherException extends BaseException {}
Try{
//Add code here
throw new OtherException(Something went wrong here);
} Catch (OtherException oex) {
//Caught a custom exception type here
} Catch (Exception ex){
//Caught all other exceptions here
}
7/27/2019 introductiontoapexcode-120510175542-phpapp01
14/31
Force.com Query Languages
SOQL Salesforce object Query Language
String myName = Acme;
Account[] accts = [select ID from Account where name =:myName] //Pass in a variable
SOSL Salesforce object Search Language
List searchList = [FIND '415' IN PHONE FIELDS RETURNING Account, Contact ];Account [] accounts = ((List)searchList[0]);
Contact [] contacts = ((List)searchList[1]);
7/27/2019 introductiontoapexcode-120510175542-phpapp01
15/31
Data Manipulation with Apex
DML (Data Manipulation Language)
- Insert- Update
- Upsert - Operation to create a new or update existing record
based on an external id.
- Delete
- Undelete
7/27/2019 introductiontoapexcode-120510175542-phpapp01
16/31
Heres what it looks like
1
2
3
45
6
7
8
9
1
1
1
1 myPlainText = email.plainTextBody.substring(0, email.plainTextBody.indexOf(''));
1
1 myPlainText = email.plainTextBody;
1 System.debug('No in email: ' + e);1
1
1
2
2
2
2
2 try {
2
...
1
2
3
45
6
7
8
9
10
11
12
13
14
15
1617
18
19
20
21
22
2324
25
26
27
28
29
global class tasks implements Messaging.InboundEmailHandler {
// Create inboundEmailResult object for returning the result of the Force.com Email Service
// Add the email plain text into the local variable
// new Task object to be created
/* Try to lookup any contacts based on the email from address
/ If there is more than 1 contact with the same email address/ an exception will be thrown and the catch statement will be called
*/
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String myPlainText = ';
try {
} catch (System.StringException e) {
}
List newTask = new List();
[Select Id, Name, Email From Contact Where Email = :email.fromAddress]Contact vCon =
Interface
Implementation
Comment
Syntax
Object
InstantiationVariable Declaration
Exception
Handling
List Creation
Query Language
Function
Declaration
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
Messaging.InboundEnvelope env){
7/27/2019 introductiontoapexcode-120510175542-phpapp01
17/31
Bulk data operations with Apex
Commonly, the ordering of process for an apex solution is as follows:
1) Records are retrieved from the Force.com database with a querystatement
2) The array of records ismodified in the processing of your Apex
Code
3) The array of records is then sent back to the object through a
data manipulation statement
These actions are performed in bulk on the Force.com
7/27/2019 introductiontoapexcode-120510175542-phpapp01
18/31
Bulk data operations with Apex (cont)
Apex Code must be designed to handle bulk operations
Why is this important?
- The Force.com enforces limits to how many records can be
processed at a time (governor limits)
Examples:
Limit on the number of records that can be queried. Limit on the number of records that be modified.
Limits are calculated by the number of records invoking the Apex
Code code
7/27/2019 introductiontoapexcode-120510175542-phpapp01
19/31
Handling Bulk operations - example
7/27/2019 introductiontoapexcode-120510175542-phpapp01
20/31
Testing
Apex Code to test your Apex Code
Code to help developers perform and automate unit testing Enables the platform to execute these test methods during
deployment
Force.com requires that at least 75% of your Apex is
covered by testing before code can be deployed to a
Production environment (100% is ideal!)
Unit test methods are denoted with testMethodkeyword.
testMethods do not modify any data in your org
7/27/2019 introductiontoapexcode-120510175542-phpapp01
21/31
What can you do with Apex Code?
Triggers
Apex Web Services
Email Services
SOA (callouts)
Visualforce Controllers
7/27/2019 introductiontoapexcode-120510175542-phpapp01
22/31
What can you do with Apex Code?
Triggers
Code runs when data changes to ensure business logic isapplied
Executes on the serverwhen data changes in either the UI or API.
Email Services
Send & Receive emails, including attachments, with custom
logic to process contents.
Includes all standard email attributes, use email templates, and
supports plain text or HTML. Force.com generates a unique email address to process the
contents.
7/27/2019 introductiontoapexcode-120510175542-phpapp01
23/31
What else can you do with Apex Code?
Apex Web Services
Develop new Force.com Web Services Define and expose a custom Web Service for an external service
to invoke.
As simple as adding the webService keyword to a Apex method
WSDL automatically available
Consume other Web Services
Provides integration with external Web Services
Apex provides integration with Web services that utilize SOAP
and WSDL, or HTTP services
7/27/2019 introductiontoapexcode-120510175542-phpapp01
24/31
What else can you do with Apex Code?
Visualforce Controllers
Apex logic accessed by Visualforce pages through customcontrollers and controller extensions.
Apex Class that drives the logic when a user interacts with the
Visualforce pages.
7/27/2019 introductiontoapexcode-120510175542-phpapp01
25/31
Winter 09 Apex Feature Dynamic Apex
public class displayFields{
//Retrieves available SObjects with Global Describe
private Map schemaMap =
Schema.getGlobalDescribe();
//Retrieve accessible fields for specified object
public List showFields(String selectedObject) {
fields.clear();
Map fieldMap =
schemaMap.get(selectedObject).getDescribe().fields.getMap();
//for each field determine whether the running user has
access to the field
for(Schema.SObjectField f : fieldMap.Values()){
Schema.DescribeFieldResult df = f.getDescribe();
if(df.isAccessible()){
fields.add(f);
}
}
return fields;
}
Streamline code design
eliminate repetitive code by
constructing dynamic procedures
for query, search, and data
manipulation
Describe methods
New Apex methods to describe
schema including object definition
and field definitions.
User permission awareness
The power of system level access
with the capability to enforce user
permissions and constraints
7/27/2019 introductiontoapexcode-120510175542-phpapp01
26/31
Winter 09 Apex Feature Async Apex
Asynchronous execution
Supports web service callouts
from triggers
Monitoring UI provides
detailed view of status and
execution time
global class myclass {
public class MyException extends Exception{}public static void throwException() {
System.debug('calling throw exception');
throw new MyException('for bar');
}
@future(callout=true) static void voidvoid() {
System.debug('void void');
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('http://www.cheenath.com');HttpResponse res = http.send(req);
System.debug(res.getBody());
//throw new MyException('for bar');
}
@future static void createAccount(String n) {
Account a = new Account(name=n);
insert a;
}
7/27/2019 introductiontoapexcode-120510175542-phpapp01
27/31
Additional Dreamforce 2008 Apex Sessions
Apex Test Coverage Best Practices
Tuesday, 2:00-3:00PM, Esplanade 305
Hands-On : Apex Code
Tuesday, 2:00-3:00PM, South 102
Development As A Service Building and Deploying Apps
in the Cloud
Wednesday, 10:15-11:15AM, Esplanade 303
7/27/2019 introductiontoapexcode-120510175542-phpapp01
28/31
Force.com Library
Books
Developers Guide to the Force.com
Force.com Cookbook
Creating On-Demand Apps
Apex Language Reference
7/27/2019 introductiontoapexcode-120510175542-phpapp01
29/31
Additional Resources
Developer.Force.com
Force.com Developer Community
Apex Developer Guide & Language Reference
Recorded technical presentations and whitepapers
Apex Message Boards
Sign up for free Developer Edition
Training Courses & Certification
DEV401: Force.com essentials
DEV501: Visualforce, Apex, DaaS (Development As A Service)
7/27/2019 introductiontoapexcode-120510175542-phpapp01
30/31
Session FeedbackLet us know how were doing and enter to win an iPod nano!
Please score the session from 5 to 1 (5=excellent,1=needs
improvement) in the following categories: Overall rating of the session
Quality of content
Strength of presentation delivery
Relevance of the session to your organization
Additionally, please fill in the name of each speaker &
score them on overall delivery.
We strive to improve, thank you for filling out our survey.
7/27/2019 introductiontoapexcode-120510175542-phpapp01
31/31
QUESTION & ANSWER
SESSION