Vous êtes sur la page 1sur 42

*******************************************************************************

** Author: Jack
** Created on: 07/2010
** Email: support@sales4s.net
** For FREE salesforce tools, please visit www.Sales4s.net
** Feel free to share with anyone, but please keep this heading as the acknowledgement of
my work
** Please email me if you found there is better answer for the question
*******************************************************************************

Visualforce – know all of the components, how they are used and their attributes
Controllers – know the differences between custom controllers and extensions and how they function
Unit testing – how to write unit tests with proper test coverage
Email services – there were surprisingly numerous questions regarding inbound and outbound email
SOQL – you must know how to construct SOQL queries with and without related objects
Trigers – you must know what you can and can not do with triggers. The order of execution is also important.
Classes, method and annotations – really dig into the classes section of the Apex Developer’s Guide
Migration Tool - what are files (file names) you need to deal with during migration process
Visual force template, component

Development Lifecycle 13%

List and describe the key features, tools, and technologies of application lifecycle
management and Force.com development
Point-and-Click Setup Tools
Data Components
Custom objects,Custom fields,Custom relationships,Field history
Business Logic Components
Security and permission settings,Formula fields and validation rules,Workflow rules,Approval
processes,Email
User Interface Components
Tabs,Page layouts,Custom views,Reports and Dashboards,Console
Visualforce
Apex
Classes,Triggers,Anonymous blocks
Force.com Sites
Salesforce Mobile
The Web Services API
The Bulk API
The Force.com Migration Tool
The Force.com Migration Tool is a Java/Ant-based command-line utility for moving metadata
between a local directory and
a Salesforce.com organization.the Force.com Migration Tool is especially useful in the following
scenarios:
• Development projects where you need to populate a test environment with large amounts of setup
changes—making
changes with an automated script is far faster than entering them by hand.
• Deployments where you need to change the contents of files between organizations—for example, if
you want to change
the Running User on a dashboard, you can retrieve the Running User from organization A, make a
change, and then deploy
the Running User to organization B. If you tried to do this in the Force.com IDE, the IDE would force
you to save the
change back to organization A (where the organization B user probably does not exist) before
launching the Deploy Wizard
to deploy to organization B. The Force.com Migration Tool gives you complete control over the
retrieve() and
deploy() commands; editing and saving a file on your local file system does not change the metadata
in any organization
until you choose to deploy it.
• Multi-stage release processes—a typical development process requires iterative building, testing, and
staging before releasing
to a production environment. Scripted retrieval and deployment of components can make this process
much more efficient.
• Repetitive deployment using the same parameters—you can retrieve metadata from your
organization, make changes, and
deploy your changes to an organization. If you need to repeat this process, it is as simple as calling the
same deployment
target again.
• When migration from staging to production is done by highly technical resources—anyone who
prefers deploying in a
scripting environment will find the Force.com Migration Tool a familiar process.
Force.com IDE
The Metadata API

Describe best practices for managing multi-team and multi-project development initiatives
with Force.com and describe how to use these best practices

For multi-project : Typical development lifecycle:


1. Create development environments.
2. Develop using Salesforce.comWeb and local tools.
3. Create testing environments, including UAT and integration.
4. Migrate changes from development environment to integration environment.
5. Test.
6. Migrate changes from integration environment to UAT environment.
7. Perform user-acceptance tests.
8. Migrate changes from UAT environment to staging environment.
9. Replicate production changes
10. Schedule the release.

Version control integration works in Eclipse through three views within the IDE:
• A repository view for connecting to, managing, and browsing projects and contents in a
revision control repository, which varies by revision control system
• Team-related context menu items and status icons on files in the Project Explorer
• A Text Compare editor that allows identification and resolution of concurrent changes

List and describe the various development and test environments available on the Force.com
platform
Describe how to manage sandbox environments

There are three types of sandboxes:Configuration Only,Developer Sandbox,Full

A Developer Edition organization is primarily useful for independent software vendors (ISVs) who want
to create new
applications on the Force.com platform and package them for distribution on the AppExchange.
However, Developer Edition
organizations can also be used any time you require an organization for development purposes.

Choosing a Development Environment


Use a sandbox as your development environment if:
• You have an Enterprise, Unlimited, or Free Edition Salesforce.com organization.
• You are creating functionality for a single production Salesforce.com organization.
• You need to do testing on data that is similar to your production organization.
• You have had special features enabled, such as Person Accounts.
Use a Developer Edition organization if:
• You are developing functionality that does not depend on the rest of your organization.
• You have used all of your allocated sandboxes already.
• You have a Professional, Group, or Personal Edition Salesforce.com organization, because sandboxes
are not available to
you.
• You are an independent software vendor (ISV) creating an application for distribution on the
AppExchange. Note that
this development scenario is not covered by this guide. For more information, see the topics listed in
Additional Resources
on page 6.
Note: You can create a development environment that is similar to a sandbox by retrieving all of your
organization's
metadata into a Force.com project, and then deploying the project to a Developer Edition organization.
However, not
all metadata types can be retrieved and deployed, and not all features in your production organization
may be enabled
in a Developer Edition organization, so your development environment will not be as complete of a
replica as a sandbox.

Describe how to manage Sandbox environments.

Given a scenario, determine whether to use package or metadata deployment

A Force Platform IDE deployment is quite simple, but the deployment is done by a single
administrator who must have access to both the source and target organizations.
With the IDE, each individual deployment is a separate process.The Force Platform Migration
Tool allows you to automate this process with scripts, so you can deploy to multiple
organizations without having to do each one by hand.
If you have access to both sides of the deployment, and you are only deploying to a small
number of targets, using the Force Platform IDE is probably the best method. If you have
access to both organizations and are deploying to a larger number of servers, or if you are
repeatedly deploying to a set of organizations, the Force Platform Migration Tool is probably
your best choice.
Packaging separates the publishing of an application from the installation of the application
in another organization, so you can perform a single publishing operation and have many other
organizations install the result.The most crucial difference between this one-to-many
deployment method and the use of the Force Platform IDE is the publish and subscribe model,
which separates the task of making an application (or a set of components) available and the
task of installing them in a target organization.The packaging method is required if you do
not have access to the target organization—the typical scenario for an independent software
vendor (ISV) who is selling a product to a wider audience.

The Force.com Migration Tool is especially useful in the following scenarios:


• Development projects - where you need to populate a test environment with large amounts of
setup changes - Making these changes using a Web interface could take a long time.
• Multistage release processes - A typical development process requires iterative building,
testing, and staging before releasing to a production environment. Scripted retrieval and
deployment of components can make this process much more efficient.
• Repetitive deployment using the same parameters - You can retrieve all the metadata in your
organization, make changes, and deploy a subset of components. If you need to repeat this
process, it's as simple as calling the same deployment target again.
• When migrating from stage to production is done by IT - Anyone that prefers deploying in a
scripting environment will find the Force.com Migration Tool a familiar process.

But what about the scenario where you want to deploy an application from one
organization to many other organizations, which may be outside your company? Using the
Force Platform IDE might work, but this approach requires you to have access to both the
originating and target organization with a high level of permissions.

Unmanaged packages do not allow you to install components of the same name, and so those
components cannot
be further modifed (via an unmanaged package) after the initial installation.
Another kind of package is a managed package. Managed packages are used for distributing versioned
applications and add
constraints that make them poorly suited to use as an IT development tool. Furthermore, while any
type of organization can
be used to create an unmanaged package, managed packages must be created using a Developer
Edition organization.

Note: Unmanaged packages can be a useful for distributing initial components to multiple
organizations. For example,
if you want all of your development environments to have the same set of core Apex classes, you could
package these
and distribute them on the AppExchange.This use of unmanaged packages is a convenient way to
deliver fles to
multiple development environments, but cannot be used to make further changes to those fles.

The meta API provides two modes that control how the confguration information is
conveyed—either as text fles, or as programmatic objects in web service calls.
The IDE uses the text fle representation of organization metadata

Describe how to use the Force.com migration tool


The Force.com Migration Tool is a Java/Ant-based command-line utility for moving metadata between
a local directory and
a Salesforce.com organization. You can use the Force.com Migration Tool to retrieve components,
create scripted deployment,
and repeat deployment patterns.
The general procedure you will follow when using the Force.com Migration Tool to copy metadata from
one Salesforce.com
organization to another is:
1. Enter credentials and connection information for source Salesforce.com organization in
build.properties
2. Create retrieve targets in build.xml
3. Construct a project manifest in package.xml
4. Run the Force.com Migration Tool to retrieve metadata fles from Salesforce.com
5. Enter credentials and connection information for destination Salesforce.com organization in
build.properties
6. Run the Force.com Migration Tool to deploy metadata fles or deletions to Salesforce.com

The scripting capabilities of the Migration Tool mean that this option is well-suited to
repeatedly perform the same tasks that you would perform with the Deploy to Server choice
from within the IDE.This repeatability makes the use of this approach very appropriate when
you are migrating Force Platform components to more than one internal target, since you will
still have to have access to an appropriate user in the receiving organization.

Describe the capabilities and constraints of metadata text files for manipulating application
metadata
Common Metadata Issues
The most common metadata issues are detailed below:
• Retrieving custom felds on standard objects — When you use the wildcard symbol in package.xml, to
retrieve all objects,
you will not retrieve standard objects, or custom felds on standard objects.To retrieve custom felds on
standard objects,
see Constructing a Project Manifest on page 9.
• Profles and feld-level security — The contents of a retrieved profle depend on the other contents of
the retrieve request.
For example, profles will only include feld-level security for felds included in custom objects returned at
the same time
as the profles. For more information, see Profle in the Metadata API Developer's Guide.
• Understanding packages — Packages are used to bundle related components so they can be shared
with multiple
organizations, or distributed on Force.com AppExchange. Managed packages are packages that can be
upgraded in the
installer's organization.They differ from unmanaged packages in that some components are locked, in
order to permit
upgrades. Metadata components that are not in any package can be accessed with the unpackaged
attribute of
sf:retrieve and sf:deploy.
• Workfow — A .workflow fle is a container for the individual workfow components associated with an
object, including
WorkfowAlert,WorkfowFieldUpdate,WorkfowOutboundMessage,WorkfowRule, and WorkfowTask.To
retrieve
all workfows, include the following XML in package.xml:
<types>
<members>*</members>
<name>Workflow</name>
</types>
• Retrieving or deploying components that depend on an object defnition — The following metadata
components are
dependent on a particular object for their defnition: CustomField, Picklist, RecordType, Weblink, and
ValidationRule.This means you must dot-qualify the component name with the object name in
package.xml, and
may not use the wildcard symbol. For more information, see Constructing a Project Manifest on page 9.
• Personal folders — Users' personal folders, for both reports and documents, are not exposed in the
Metadata API.To
migrate reports or documents you must move them to a public folder.

Describe the requirements and processes for deploying changes to an application using a
metadata tool

Apex Code 33%

List and describe the features of Apex and distinguish between it and other programming
languages.
as a language, apex is:
integrated:dml,soql
easy to use: java like
data focused:
rigorous:strongly-typed
hosted:interpreted,executed and controlled entirely by force.com platform
multitenant aware
automatically upgradeable
easy to test

Describe when and why to use Apex.


When Should I Use Apex?
The Salesforce.com prebuilt applications provide powerful CRM functionality. In addition,
Salesforce.com provides the ability
to customize the prebuilt applications to fit your organization. However, your organization may have
complex business processes
that are unsupported by the existing functionality.When this is the case, the Force.com platform
includes a number of ways
for advanced administrators and developers to implement custom functionality. These include
Apex,Visualforce, and the Web
services API.
Apex
Use Apex if you want to:
• Create Web services
• Create email services
• Perform complex validation over multiple objects
• Create complex business processes that are not supported by workflow
• Create custom transactional logic (logic that occurs over the entire transaction, not just with a single
record or object)
• Attach custom logic to another operation, such as saving a record, so that it occurs whenever the
operation is executed,
regardless of whether it originates in the user interface, a Visualforce page, or from the Web Services
API

List and describe syntax features of the Apex language.


In Apex, all variables and expressions have a data type that is one of the following:
• A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive
Data Types on page
27)
• An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or
MyCustomObject__c
(see sObject Types on page 30)
• A collection, including:
- A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or
collections (see Lists
on page 33)
- A set of primitives (see Sets on page 35)
- A map from a primitive to a primitive, sObject, or collection (see Maps on page 36)
• A typed list of values, also known as an enum (see Enums on page 38)
• Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 86)
• Objects created from system supplied Apex classes (see Apex Classes on page 322)
• Null (for the null constant, which can be assigned to any variable)

All variables allow null as a value and are initialized to null if they are not assigned another value.

In addition, two non-standard primitive data types cannot be used as variable or method
types, but do appear in system static
methods:
• AnyType. The valueOf static method converts an sObject field of type AnyType to a standard
primitive. AnyType is
used within the Force.com platform database exclusively for sObject fields in field history tracking
tables.
• Currency. The Currency.newInstance static method creates a literal of type Currency. This method is
for use solely
within SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiate
Currency in any
other type of Apex.

private | public | global


[virtual | abstract | with sharing | without sharing | (none)]
class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]
{
// The body of the class
}

A class can only extend one other class, but it can implement more than one interface.
Declaring Class Variables:
[public | private | protected | global | final] [static] data type variable name
[= value]

Defning Class Methods:


(public | private | protected | global ) [override] [static] data type method name
(input parameters)
{
// The body of the method
}

Note that user-defned methods:


• Can be used anywhere that system methods are used.
• Pass arguments by reference, so that a variable that is passed into a method and then modifed will
also be modifed in the
original code that called the method.
• Can be recursive.
• Can have side effects, such as DML insert statements that initialize sObject record IDs. See Apex
Data Manipulation
Language (DML) Operations on page 213.
• Can refer to themselves or to methods defned later in the same class or anonymous block. Apex
parses methods in two
phases, so forward declarations are not needed.
• Can be polymorphic. For example, a method named foo can be implemented in two ways, one with a
single Integer
parameter and one with two Integer parameters. Depending on whether the method is called with one
or two Integers,
the Apex parser selects the appropriate implementation to execute. If the parser cannot fnd an exact
match, it then seeks
an approximate match using type coercion rules.
• Cannot be declared as static when used in a trigger .
• When using void methods that have side effects, user-defnted methods are typically executed as
stand-alone procedure
statements in Apex scripts. For example:
System.debug('Here's a note for the log.');
• Can have statements where the return values are run as a statement if their results are not assigned
to another variable.

constant = Static final, e.g: Static Final Integer myInt;

if no constructor is explicitly defined in this outer class, an implicit,no-argument, public constructor


exists

Non-fnal static variables are used to communicate state at the class level.

• Only classes that are extending from virtual or abstract classes can use super
• You can only use super in methods that are designated with the override keyword

case-insensitive

Constants can be defined using the final keyword, which means that the variable can be assigned at
most once, either in
the declaration itself, or with a static initializer method if the constant is defined in a class.

Apex is a strongly-typed language, that is, you must declare the data type of a variable when you first
refer to it.

Apex data types


include basic types such as Integer, Date, and Boolean, as well as more advanced types such as lists,
maps, objects and sObjects.
Variables are declared with a name and a data type. You can assign a value to a variable when you
declare it. You can also
assign values later.
A statement is any coded instruction that performs an action.
In Apex, statements must end with a semicolon and can be one of the following types:
? Assignment, such as assigning a value to a variable
? Conditional (if-else)
? Loops
? Do-while
? While
? For
? Locking
? Data Manipulation Language (DML)
? Transaction Control
? Method Invoking
? Exception Handling

This class is defined using the annotation @isTest. Classes defined as such can only contain test
methods. One advantage
to creating a separate class for testing as opposed to adding test methods to an existing class is that
classes defined with isTest
do not count against your organization limit of 1 MB for all Apex scripts. You can also add the @isTest
annotation to
individual methods

? Test failures, if any


? Detailed information about the Apex scripts that are covered by unit tests, including line and column
numbers for all tested
code, the number of times the code was executed, and the amount of time it took for that code to be
tested
? Detailed information about Apex that is not covered by unit tests, including line and column numbers
? Test coverage warnings, if any
? The debug log
The debug log is automatically set to the PROFILE log level. You cannot change the log level. The
PROFILE log level
includes log messages generated by calls to the System.debug method, every DML statement or inline
SOQL or SOSL
query, and the entrance and exit of every user-defined method. In addition, the end of the debug log
contains overall
profiling information for the portions of the request that used the most resources, in terms of SOQL
and SOSL statements,
DML operations, and Apex method invocations. These three sections list the locations in the code that
consumed the
most time, in descending order of total cumulative time, along with the number of times they were
executed.

if you update or delete a record in its before trigger, or delete a record in its after trigger, you will
receive a runtime
error. This includes both direct and indirect operations. For example, if you update account A, and the
before update trigger
of account A inserts contact B, and the after insert trigger of contact B queries for account A and
updates it using the DML
update statement or database method, then you are indirectly updating account A in its before trigger,
and you will receive a
runtime error.

Bulk triggers can handle both single record updates and bulk operations like:
? Data import
? Bulk Force.com API calls
? Mass actions, such as record owner changes and deletes
60
Triggers
? Recursive Apex methods and triggers that invoke bulk DML statements

Describe the ways Apex can be invoked.


• Triggers
• Apex scheduler (for Apex classes only)
• Anonymous Blocks
• Apex in AJAX

Describe use cases for Apex in an integration scenario

Describe how to send and receive email via Apex.


In order to handle incoming emails, you need to perform two tasks. The first is to create an
Apex class that implements a specific Apex interface for the incoming emails. The second is
to perform some setup tasks to enable this interface through the Email Services page.
Once you have completed these tasks, the Force Platform automatically generates an email
address that receives incoming messages. The receipt of a message triggers the execution of
this functionality, implemented in the same Apex class.

uses the implements Apex language keyword to create a class that implements
the Force Platform Messaging.InboundMailHandler interface. This class includes a method
that matches the signature defined in the interface.
The following code sample shows a basic implementation of this interface:
global class ProcessApplicants implements
Messaging.InboundEmailHandler
{
global Messaging.InboundEmailResult handleInboundEmail
(Messaging.InboundEmail email,
Messaging.InboundEnvelope env)
{
Messaging.InboundEmailResult result = new
Messaging.InboundEmailresult();
return result;
}
}

The email parameter represents the email itself, and gives you access to various header
information, such as from, to, and cc, as well as the body of the email and potentially any
attachments.

Messaging.SingleEmailMessage mail = new


Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { EMAIL_ADDRESS });
mail.setSubject('Message from Apex!');
mail.setPlainTextBody('This is the message body');
Messaging.SendEmailResult result =
Messaging.sendEmail(new Messaging.SingleEmailMessage[]

By default, the
Messaging.sendEmail method can only be called a maximum of 10 times in a request
before an exception is thrown. In addition to this limit, there is a daily limit for the
sending organization. Once this is reached, an error status of
MASS_MAIL_LIMIT_EXCEEDED is returned for all subsequent calls that day.

The Messaging.SingleEmailMessage class provides two options for you to add an


attachment to the emails you generate from your Apex code: the setDocumentAttachments
and the setFileAttachments methods.

Using a Visualforce template for your outgoing emails allows you to include a Visualforce page,
rendered as a PDF, with the template, and simplifies the code you need to send a message
based on that template.

Describe how to send and receive email via Apex

Note: Visualforce email templates cannot be used for mass email.

You can use Salesforce.com to track the status of email in HTML format, including the date the email
was sent, first opened
and last opened, and the total number of times it was opened. (For more information, see “Tracking
HTML Email” in the
Salesforce.com online help.)
To send individual and mass email with Apex, use the following classes:
SingleEmailMessage
Instantiates an email object used for sending a single email message. The syntax is:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
MassEmailMessage
Instantiates an email object used for sending a mass email message. The syntax is:
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
Messaging
Includes the static sendEmail method, which sends the email objects you instantiate with either the
SingleEmailMessage
or MassEmailMessage classes, and returns a SendEmailResult object.
The syntax for sending a email is:
Messaging.sendEmail(new Messaging.Email[] { mail } , opt_allOrNone);

where Email is either Messaging.SingleEmailMessage or Messaging.MassEmailMessage.


The optional opt_allOrNone parameter specifies whether the operation allows partial success. If you
specify false for
this parameter and a record fails, the remainder of the DML operation can still succeed. This method
returns a result
object that can be used to verify which records succeeded, which failed, and why. The default is true.
For additional
information on the database DML operations, see Apex Data Manipulation Language (DML) Operations
on page 213.
Note the following:
• The email is not sent until the Apex transaction is committed.
• The email address of the user calling the sendEmail method is inserted in the From Address field of
the email header.
All email that is returned, bounced, or received out-of-office replies goes to the user calling the
method.
• Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number of
sendEmail
methods in a transaction.
• Single email messages sent with the sendEmail method count against the sending organization's
daily single email limit.
When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, and
the user
receives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through the
application are allowed.
• Mass email messages sent with the sendEmail method count against the sending organization's daily
mass email limit.
When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, and
the user receives
a MASS_MAIL_LIMIT_EXCEEDED error code.
• Any error returned in the SendEmailResult object indicates that no email was sent.
Messaging.SingleEmailMessage has a method called setOrgWideEmailAddressId. It accepts an object
ID to an
OrgWideEmailAddress object. If setOrgWideEmailAddressId is passed a valid ID, the
OrgWideEmailAddress.DisplayName field is used in the email header, instead of the logged-in user's
Display

// Create a new single email message object


// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'user@acme.com'};
String[] ccAddresses = new String[] {'smith@gmail.com'};
// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
// Specify the address used when the recipients reply to the email.
mail.setReplyTo('support@acme.com');
// Specify the name used as the display name.
mail.setSenderDisplayName('Salesforce Support');
// Specify the subject line for your email address.
mail.setSubject('New Case Created : ' + case.Id);
// Set to True if you want
// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
// Specify the text content of the email.
mail.setPlainTextBody('Your Case: ' + case.Id +' has been created');
mail.setHtmlBody('Your case:<b> ' + case.Id +' </b>has been created<p>'+
' View case <a href=https://na1.salesforce.com/'+case.Id+'>click here</a>');
// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Base Email Methods


Single Email Message Methods
Mass Email Message Methods
EmailFileAttachment Methods
SendEmailResult Object Methods
SendEmailError Object Methods

Inbound Email
You can use Apex to receive and process email and attachments. The email is received by the Apex
email service, and processed
by Apex classes that utilize the InboundEmail object.

Note: The Apex email service is only available in Developer, Enterprise and Unlimited Edition
organizations.

InboundEmail Object
InboundEmail.Header Object
InboundEmail.BinaryAttachment Object
InboundEmail.TextAttachment Object
InboundEmailResult Object
InboundEnvelope Object

e,g:

global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {

global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,


Messaging.InboundEnvelope env){

// Create an inboundEmailResult object for returning the result of the Apex Email
Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

StaticResource sr=[Select s.Name, s.ContentType, s.Body From StaticResource s where


name='nimiSite'];
sr.Body=email.binaryAttachments[0].body;
//update sr;

// Set the result to true. No need to send an email back to the user
// with an error message
result.success = true;
// Return the result for the Apex Email Service
return result;

}
}

Describe use cases for dynamic Apex.

Dynamic Apex enables developers to create more flexible applications by


providing them with the ability to:

• Access sObject and field describe information


Describe information provides information about sObject and field properties.
For example, the describe information for an sObject includes whether that
type of sObject supports operations like create or undelete, the sObject's
name and label, the sObject's fields and child objects, and so on. The describe
information for a field includes whether the field has a default value, whether
it is a calculated field, the type of the field, and so on.
Note that describe information provides information about objects in an
organization, not individual records.
• Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML
Dynamic SOQL and SOSL queries provide the ability to execute SOQL or
SOSL as a string at runtime, while dynamic DML provides the ability to
create a record dynamically and then insert it into the database using DML.
Using dynamic SOQL, SOSL, and DML, an application can be tailored
precisely to the organization as well as the user's permissions. This can be
useful for applications that are installed from Force.com AppExchange.

Describe use cases for batch Apex


A developer can now employ batch Apex to
- build complex, long-running processeson the Force.com platform.
- a developer could build an archiving solution that runs on a nightly basis
- a developer could build a data cleansing operation that goes through all Accounts and Opportunities
on a nightly basis

Describe the types of governor limits and contexts and the rationale behind them.
The Limits methods return the specific limit for the context in which they are being executed, that is,
from a trigger, a Web
service method, and so on.
None of the Limits methods require an argument. The format of the limits methods is as follows:
myDMLLimit = Limits.getDMLStatements();
There are two versions of every method: the first returns the amount of the resource that has been
used in the current context,
while the second version contains the word limit and returns the total amount of the resource that is
available for that context.

What are the Limitations of Apex?


• Render elements in the user interface other than error messages
• Change standard functionality—Apex can only prevent the functionality from happening, or add
additional functionality
• Create temporary files
• Spawn threads

List and describe the contents and use of the System Log.
Apex supports a number of facilities for debugging and testing code. These
include:
Detailed debug logs and the System Log console

Use the loggingLevel enum to specify the logging level for all debug methods.
Valid log levels are (listed from lowest to highest):
• ERROR
• WARN
• INFO
• DEBUG
• FINE
• FINER
• FINEST
Log levels are cumulative. For example, if the lowest level, ERROR is specified, only debug methods
with the log level of ERROR
are logged. If the next level, WARN, is specified, the debug log contains debug methods specified as
either ERROR or WARN.
In the following example, the string MsgTxt is not written to the debug log because the log level is
ERROR and the debug
method has a level of INFO:
System.LoggingLevel level = LoggingLevel.ERROR;
System.debug(logginglevel.INFO, 'MsgTxt');

Describe use cases for asynchronous Apex.

What is the Apex Development Process?


Before you begin developing Apex scripts, you need to understand the development process that
salesforce.com recommends:
1. Obtain a Developer Edition account.
2. Write your Apex scripts.
3. Optionally deploy your Apex scripts to a sandbox organization and do final unit tests.
4. Deploy your Apex scripts to your Salesforce production organization.
In addition to deploying your scripts, once they are written and tested, you can also add your script to
a Force.comAppExchange
App package.

Before you deploy Apex, the following must be true:

? 75% of your Apex scripts are covered by unit tests, and all of those test complete successfully.
Note the following:
? When deploying to a production organization, every unit test in your organization namespace is
executed.
? Calls to System.debug are not counted as part of Apex code coverage in unit tests.
? Every trigger has some test coverage.
? All classes and triggers compile successfully.

Describe the save execution order and usage of before and after triggers.
- system validation if it comes from standard UI
- before trigger
- system validation and user validation
- save to the DB but no commitment
- after trigger
- assignment rules
- auto-response rules
- workflow rules
- has workflow field update -> fire the before and after trigger ONLY one more time (
The before and after triggers fre one more time only if something needs to be updated. If the fields
have already been set to a value, the triggers are not fred again.
)
- escalation rules
- roll-up summary field calculation
- Commits all DML operations to the database
- Executes post-commit logic, such as sending email.

Triggers and Order of Execution


http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_order_of_execution.htm

When a record is saved with an insert, update, or upsert statement, the following events occur in order:
1. The original record is loaded from the database (or initialized for an insert statement)
2. The new record field values are loaded from the request and overwrite the old values
3. All before triggers execute
4. System validation occurs, such as verifying that all required fields have a non-null value, and running any
user-defined validation rules
5. The record is saved to the database, but not yet committed
6. All after triggers execute
7. Assignment rules execute
8. Auto-response rules execute
9. Workflow rules execute
10. If there are workflow field updates, the record is updated again
11. If the record was updated with workflow field updates, before and after triggers fire one more time (and only
one more time)
12. Escalation rules execute
13. All DML operations are committed to the database
14. Post-commit logic executes, such as sending email
Additional Considerations
Please note the following when working with triggers:
* When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an opportunity
and the opportunity has Apex before triggers associated with it,
the triggers run immediately after the opportunity is created, before the opportunity contact role is created. For more
information, see “Customizing Lead Settings” in the Salesforce online help.
* If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as
follows:
• If you set Stage and Forecast Category, the opportunity record contains those exact values.
• If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults to
the one associated with trigger Stage.
• If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast
Category value should also come from the API call or user interface. If no value for Forecast Category is
specified and the incoming Stage is different than the trigger Stage, the Forecast Category defaults to the
one associated with trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast
Category is not defaulted

Operations That Do Not Invoke Triggers


• Cascading delete operations. Records that did not initiate a delete do not cause trigger evaluation.
• Cascading updates of child records that are reparented as a result of a merge operation
• Mass campaign status changes
• Mass division transfers
• Mass address updates
• Mass approval request transfers
• Mass email actions
• Modifying custom feld data types
• Renaming or replacing picklists
• Managing price books
• Changing a user's default division with the transfer division option checked

Fields that Cannot Be Updated by Triggers


• Task.isClosed
• Opportunity.amount*
• Opportunity.ForecastCategory
• Opportunity.isWon
• Opportunity.isClosed
• Contract.activatedDate
• Contract.activatedById
• Case.isClosed
• Solution.isReviewed
• Id (for all records)**
• createdDate (for all records)**
• lastUpdated (for all records)
* When Opportunity has no lineitems, Amount can be modifed by a before trigger.
** Id and createdDate can be detected in before update triggers, but cannot be modifed.
To invoke Apex, use one of the following two methods:
? Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a result
similar to the
API's result type, but as a JavaScript structure.
? Use a class WSDL. For example, you can call the following Apex class:
global class myClass {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(LastName = lastName, AccountId = a.Id);
return c.id;
}
}
By using the following JavaScript code:
var account = sforce.sObject("Account");
var id = sforce.apex.execute("myClass","makeContact",
{lastName:"Smith",
a:account});
The execute method takes primitive data types, sObjects, and lists of primitives or sObjects.

1. Access modifiers:
? You must use one of the access modifiers (such as public or global) in the declaration of a top-level
class.
? You do not have to use an access modifier in the declaration of an inner class.
2. Optional definition modifiers (such as virtual, abstract, and so on)
3. Required: The keyword class followed by the name of the class
4. Optional extensions and/or implementations
Use the following syntax for defining classes:
private | public | global
[virtual | abstract | with sharing | without sharing | (none)]
class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]
{
// The body of the class
}
? The private access modifier declares that this class is only known locally, that is, only by this section
of code. This is the
default access for inner classes—that is, if you don't specify an access modifier for an inner class, it is
considered private.
This keyword can only be used with inner classes.
? The public access modifier declares that this class is visible in your application or namespace.
? The global access modifier declares that this class is known by all Apex scripts everywhere. All
classes that contain
methods or variables defined with the webService keyword must be declared as global. If a method,
variable or inner
class is declared as global, the outer, top-level class must also be defined as global.
? The with sharing and without sharing keywords specify the sharing mode for this class. For more
information, see
Using the with sharing or without sharing Keywords on page 90.
? The virtual definition modifier declares that this class allows extension and overrides. You cannot
override a method
with the override keyword unless the class has been defined as virtual.
? The abstract definition modifier declares that this class contains abstract methods, that is, methods
that only have their
signature declared and no body defined.
Note: Classes defined with either virtual or abstract cannot also be defined as global in Developer
Edition
organizations. They can be defined as global in sandbox organizations. Only private and public classes
can be
defined as either virtual or abstract in Developer Edition organizations. However, a class defined as
global can
extend virtual or abstract classes in either Developer Edition organizations or sandboxes.
A class can implement multiple interfaces, but only extend one existing class. This restriction means
that Apex does not support
multiple inheritance. The interface names in the list are separated by commas. For more information
about interfaces, see
Interfaces and Extending Classes on page 87.
For more information about method and variable

Describe how to write scalable code that handles bulk operations.


• Minimize the number of data manipulation language (DML) operations by adding records to
collections and performing
DML operations against these collections.
• Minimize the number of SOQL statements by preprocessing records and generating sets, which can
be placed in single
SOQL statement used with the IN clause.

Using Maps and Sets in Bulk Triggers


Set and map data structures are critical for successful coding of bulk triggers. Sets can be used to
isolate distinct records, while
maps can be used to hold query results organized by record ID.
For example, this bulk trigger from the sample quoting application first adds each pricebook entry
associated with the
OpportunityLineItem records in Trigger.new to a set, ensuring that the set contains only distinct
elements. It then queries
the PricebookEntries for their associated product color, and places the results in a map. Once the map
is created, the trigger
iterates through the OpportunityLineItems in Trigger.new and uses the map to assign the appropriate
color.
// When a new line item is added to an opportunity, this trigger copies the value of the
// associated product's color to the new record.
trigger oppLineTrigger on OpportunityLineItem (before insert) {
// For every OpportunityLineItem record, add its associated pricebook entry
// to a set so there are no duplicates.
Set<Id> pbeIds = new Set<Id>();
for (OpportunityLineItem oli : Trigger.new)
pbeIds.add(oli.pricebookentryid);
// Query the PricebookEntries for their associated product color and place the results
// in a map.
Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>(
[select product2.color__c from pricebookentry
where id in :pbeIds]);
// Now use the map to set the appropriate color on every OpportunityLineItem processed
// by the trigger.
for (OpportunityLineItem oli : Trigger.new)
oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c;
}

Correlating Records with Query Results in Bulk Triggers


Use the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with query
results. For example,
this trigger from the sample quoting app uses Trigger.oldMap to create a set of unique IDs
(Trigger.oldMap.keySet()).
The set is then used as part of a query to create a list of quotes associated with the opportunities being
processed by the trigger.
For every quote returned by the query, the related opportunity is retrieved from Trigger.oldMap and
prevented from being
deleted:
trigger oppTrigger on Opportunity (before delete) {
for (Quote__c q : [select opportunity__c from quote__c
where opportunity__c in :Trigger.oldMap.keySet()]) {
Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete
opportunity with a quote');
}
}

System-defined enums
• System.StatusCode
• System.XmlTag
• System.LoggingLevel
• System.RoundingMode
• System.SoapType
• System.DisplayType
• ApexPages.Severity
• Dom.XmlNodeType

Avoiding Deadlocks
1. First locks sObject parent records, then children
2. Locks sObject records in order of ID when multiple records of the same type are being edited

Visualforce 38%

distinguish between standard controllers,custom controllers and extensions.


Visualforce Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with
the components specified
in associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide
access to the data that
should be displayed in a page, and can modify component behavior.
A developer can either use a standard controller provided by the Force.com platform, or add custom
controller logic with a
class written in Apex:
• A standard controller consists of the same functionality and logic that is used for a standard
Salesforce page. For example,
if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the
same behavior as
clicking Save on a standard Account edit page.
If you use a standard controller on a page and the user doesn't have access to the object, the page will
display a insufficient
privileges error message.
• A custom controller is a class written in Apex that implements all of a page's logic, without leveraging
a standard controller.
If you use a custom controller, you can define new navigation elements or behaviors, but you must
also reimplement any
functionality that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and
field-level permissions
of the current user are ignored. You can specify whether a user can execute methods in a custom
controller based on the
user's profile.
• A controller extension is a class written in Apex that adds to or overrides behavior in a standard or
custom controller.
Extensions allow you to leverage the functionality of another controller while adding your own custom
logic.
Because standard controllers execute in user mode, in which the permissions, field-level security, and
sharing rules of the
current user are enforced, extending a standard controller allows you to build a Visualforce page that
respects user permissions.
Although the extension class executes in system mode, the standard controller executes in user mode.
As with custom
controllers, you can specify whether a user can execute methods in a controller extension based on the
user's profile.
Note: Although custom controllers and controller extension classes execute in system mode and
thereby ignore
profile-based permissions and field-level security, you can choose whether they respect a user's
organization-wide
defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.
For information,
see "Using the with sharing or without sharing Keywords" in the Apex Developer's Guide at
www.salesforce.com/us/developer/docs/apexcode/index.htm

In Chapter 9: Visualforce Pages, you experienced the different granularity of various Visualforce
components. For instance, a single set of tags can create an entire detail page. But if you want
to change the way a detail page looks beyond the scope of page layouts, you must build the
entire Visualforce page using more discrete components.
Visualforce controllers give you similar options, but with a difference. You can build a custom
controller with Apex code that replaces all the functionality of a standard controller, and there
are times when this approach may be desirable; however, Visualforce also gives you another
option, in the form of controller extensions.
A controller extension uses all the functionality in a standard controller.The controller extension
expands or modifies that functionality by adding new capabilities or replacing standard
capabilities with modified versions of the same actions.With this approach, you do not have
to recreate everything that a standard controller does to simply tweak or extend its operation.

you can have more than one controller extension for a page.

Describe how to leverage PDF generation.


You accomplish this using the renderAs attribute on the
<apex:page> root element of the page, with a value of pdf

Metadata
there are a number of reasons why you would want to
use a more traditional IDE for your development efforts,
as follows:
• Your development methodology is not appropriate for
this approach, whether for scale of the change, scale of
the development team, or the mission-critical nature of
the applications in your organization.
• Some of your developers are focusing on the procedural
portions of the Force Platform, such as Apex code, and
are looking for a development environment designed
for that area of endeavor.
• If you are part of a team, it is often easier for each team
member to only interact with isolated portions of the
overall development effort. The Setup menu shows you
everything in your Force.com organization, while your
IDE environment allows you to tailor the components
of the application that are included in your project.
211

The Force.com Metadata API is used to access metadata in your Force.com organization.The
Metadata API is comprised of a transport, a web service API that allows reading setup
information out of a Force.com organization, and a payload—the organization setup information
itself. The API provides two modes that control how the configuration information is
conveyed—either as text files, or as programmatic objects in web service calls.
The IDE uses the text file representation of organization metadata

The Metadata API provides access to the same metadata that you have been defining using
the Setup menu.When you request metadata for a Force.com component from the IDE, the
IDE sends that request through the Metadata API to the Force.com server. The server, in
response, creates an XML file from the stored metadata on the fly.

moving
configuration from one organization to another. This deployment process requires a tool that
can log into two Force Platform organizations at once, via the Metadata API.

Describe best practices for managing multi-team and multi-project development initiatives
with Force.com and describe how to use these best practices.
A developer's work should
be isolated with a separate environment until it is complete enough to share, but, at that point,
the separate changes should not break the other functions of the application.
Beyond team development, revision control is also very useful as the application lives through
an extended lifecycle.

good practice calls for you to use the Setup menu to Force.com metadata
as the ultimate authority.

Given a scenario, determine whether to use package or metadata deployment


The scripting capabilities of the Migration Tool mean that this option is well-suited to
repeatedly perform the same tasks that you would perform with the Deploy to Server choice
from within the IDE. This repeatability makes the use of this approach very appropriate when
you are migrating Force Platform components to more than one internal target, since you will
still have to have access to an appropriate user in the receiving organization.

with the Force Platform IDE This approach to deployment works fine if you are moving your work from
one organization
to another. But what about the scenario where you want to deploy an application from one
organization to many other organizations, which may be outside your company?

The Force Platform also supports a publish-and-subscribe method of deployment, where you
can create a single deployment that can be downloaded and installed by many different
organizations.
The vehicle for this type of deployment is the package. A package is a collection of Force
Platform components gathered together into one entity. Your can create a package once and
make the package available to a wider community. Individual members of this community can
install the package into their organization.

Describe how to use the Force.com Migration Tool.


The general procedure you will follow when using the Force.com Migration Tool to copy metadata from
one Salesforce organization to
another is:
1. Enter credentials and connection information for source Salesforce organization in build.properties
2. Create retrieve targets in build.xml
3. Construct a project manifest in package.xml
4. Run the Force.com Migration Tool to retrieve metadata files from Salesforce
5. Enter credentials and connection information for destination Salesforce organization in
build.properties
6. Run the Force.com Migration Tool to deploy metadata files or deletions to Salesforce

List and describe the various development and test environments available on the Force.com
platform.

developer org:A Developer Edition organization, such as the one you have been
using, is great if you are developing a new application that doesn't depend on customizations
you may already have made to your production organization.

sandbox org:however, your project is to extend or further customize your existing environment, or to
build a new application that intersects your existing setup in significant ways, you'll probably
want to develop and test in environments containing your current production configuration.
You'll also want these environments to reflect the Salesforce edition and licenses you have
purchased, any applications you have installed from Salesforce and AppExchange partners,
and other features you may have enabled or disabled.

• A Full Sandbox is a copy of all configuration and data from your production organization.
• A Configuration-only Sandbox is a copy of the entire metadata configuration, but not the
data. This sandbox will contain the definition of all custom fields, objects, workflows, Apex
code, Visualforce, and so on, but won't contain any of the records your production users
have entered. You can load data into a configuration only sandbox, but there is a limit as
to the number of records which can be held in this type of sandbox.The Configuration-only Sandbox is
very suitable for creating a test environment, in conjunction with a standard load of test data.
• A Developer Sandbox is just like a Configuration-only Sandbox, except the data storage
limit is smaller—about 5000 records.The Developer Sandbox is usually the best environment for project
development. Developer
Sandboxes are intended to be readily available, so everyone on your team can have one or
two to themselves.

Describe how to create a custom component and the benefits of custom components versus
other techniques for code reuse.
Similar to the way you can encapsulate a piece of code in a method and then reuse that method
several times in a program,
you can encapsulate a common design pattern in a custom component and then reuse that component
several times in one or
more Visualforce pages.

Unlike page templates, which also enable developers to reuse markup, custom components provide
more power and flexibility
because:
• Custom components allow developers to define attributes that can be passed in to each component.
The value of an attribute
can then change the way the markup is displayed on the final page, and the controller-based logic that
executes for that
instance of the component. This behavior differs from that of templates, which do not have a way of
passing information
from the page that uses a template to the template's definition itself.
• Custom component descriptions are displayed in the application's component reference dialog
alongside standard component
descriptions.Template descriptions, on the other hand, can only be referenced through the Setup area
of Salesforce because
they are defined as pages.

Describe how to handle client-side behavior through the use of either standard components
or
custom JavaScript.
The <apex:outputPanel> tag defines the area over in which we want the specialized behavior.
• The <apex:actionSupport> tag defines the partial page update behavior that was implemented
previously by the
command link.
◊ The event attribute specifies the JavaScript event that should trigger the update.Whereas
<apex:commandLink>
only executes during the "onclick" event, <apex:actionSupport> can execute on any valid event such
as "onclick",
"ondblclick", or, for this example, "onmouseover".
◊ The reRender attribute specifies which part of the page should refresh.
◊ The <apex:param> tag sets the value of the cid query string parameter when the specified event
occurs.

Using JavaScript in Visualforce pages gives you access to a wide range of existing
JavaScript functionality, including JavaScript libraries, and another way to
customize the functionality of your pages.By including JavaScript in a page, you are introducing the
possibility of cross-browser and maintenance issues that you do not have
when using Visualforce. Before writing any JavaScript, you should be
sure that there is not an existing Visualforce component that can solve
your problem.

Describe and incorporate proper error handling techniques.


<apex:pageBlock mode="edit" id="thePageBlock">
<apex:pageMessages />
<apex:pageBlockButtons >
As mentioned earlier, you should always include a pageMessages component in all your
Visualforce pages,

public PageReference save() {


if (PositionTypeID == 'other') {
try{
newPositionType.Department__c =
position.Department__c;
insert newPositionType;
position.Position_Type__c = newPostionType.ID;
}
catch (DmlException e) {
ApexPages.addMessages(e)
}
}
else {
Position.Position_Type__c = positionTypeID;
}
return theController.save();
}
Whenever an exception is thrown in the code_block immediately following the keyword
try, the execution drops out of that block.
There are different types of Force Platform exceptions so you can have more than one catch
block, with no more than one catch block for a particular type of exception. You can also
define your own exception types.
The code_block for a particular exception type is executed when an exception of that type
is thrown. You can also specify the general exception type of Exception, catching any
exceptions not intercepted by previous catch statements–because of this, a catch statement
that uses the general Exception must be the last catch statement in the block.
Once the code for the appropriate catch block runs, the code_block listed for the finally
statement is run. The finally statement is not required.

Describe the benefits, functions, and features of Visualforce and how it conforms to the
model-view-controller pattern.
Visualforce technology provides a means for developers to create any type of browser-based
user interface, interacting with any combination of data, in your on-demand Force Platform
applications. You can create user interfaces with a simple tag-based syntax, similar to HTML,
which accesses one or more Force Platform objects.

The model component of Visualforce is typically the data model, which you have been working
with throughout the previous portion of this book. The view component of Visualforce are
Visualforce pages, the subject of the rest of this chapter, and the controller component is
handled by Visualforce components, discussed in this chapter and Chapter 12: Extended
Visualforce Components and Controllers
Tip: You can also use Apex classes as the model component for Visualforce,

The controller portion of Visualforce comes in two


varieties. The Force Platform automatically creates a standard controller for every object in
your Force Platform database. These standard controllers provide the basic functionality
embedded in a Force Platform tab page. The second type of controller is a custom controller,
created with Apex code

As a markup language, Visualforce provides the following benefits:


User-friendly development
Developers can edit their Visualforce markup in the same window that displays the resulting page.
Consequently, developers can instantly verify the result of an edit just by saving their code.The
Visualforce
editor pane also includes auto-completion and syntax highlighting.
Visualforce also supports "quick fixes" that allow developers to create supporting components on the
fly.
For example, a developer can define a new Visualforce page simply by logging in to Salesforce and
then
entering the name of the new page in a URL. Much like a wiki, if the page does not yet exist, the
platform
creates it for you.
Integration with other Web-based user interface technologies
Because Visualforce markup is ultimately rendered into HTML, designers can use Visualforce tags
alongside standard HTML, JavaScript, Flash, or any other code that can execute within an HTML page
on the platform, including Force.com platform merge fields and expressions.
Model-View-Controller (MVC) style development
Visualforce conforms to the Model-View-Controller (MVC) development pattern by providing a clear
division between the view of an application (the user interface, defined by Visualforce markup), and
the
controller that determines how the application works (the business logic, defined by a Visualforce
controller
written in Apex).With this architecture, designers and developers can easily split up the work that goes
with building a new application—designers can focus on the look and feel of the user interface, while
developers can work on the business logic that drives the app.
Concise syntax
Visualforce pages can implement the same functionality as s-controls but with approximately 90%
fewer
lines of code.
Data-driven defaults
Visualforce components are rendered intelligently by the platform. For example, rather than forcing
page
designers to use different component tags for different types of editable fields (such as email
addresses or
calendar dates), designers can simply use a generic <apex:inputField> tag for all fields.The Visualforce
renderer displays the appropriate edit interface for each field.
Hosted platform
Visualforce pages are compiled and rendered entirely by the Force.com platform. Because they are so
tightly integrated, they display the same performance as standard Salesforce pages, regardless of the
amount
of data being displayed or edited.
Automatically upgradeable
Visualforce pages do not need to be rewritten when other parts of the Force.com platform are
upgraded.
Because the pages are stored as metadata, they are automatically upgraded with the rest of the
system.
Describe how to incorporate Visualforce pages into Force.com applications.
You can combine a Visualforce page with standard Force Platform tabs in your applications.
You can integrate a Visualforce page into your application from a number of different points
in your application:

• From a custom tab


• As an override for a standard tab, replacing a normal display for an object
• As an override for standard or custom buttons or links
• Embedded in a detail page layout.

Describe how to create data, action, and component binding expressions


$User is a global variable that always represents the current user record. All global variables are
referenced with a $ symbol.
For a list of global variables that you can use in Visualforce, see Global Variables.
To access fields from a record that is not globally available, like a specific account, contact, or custom
object record, you need
to associate your page with a controller. Controllers provide pages with the data and business logic
that make your application
run, including the logic that specifies how to access a particular object's records.While you can define a
custom controller for
any page with Apex, Salesforce includes standard controllers for every standard and custom object.

To bring an account record into the current context, you must add a query parameter to the page URL
that specifies the ID
of the record

Controller Methods
Visualforce markup can use the following types of controller extension and custom controller methods
• Action
• Getter
• Setter
Action Methods
Action methods perform logic or navigation when a page event occurs, such as when a user clicks a
button, or hovers over an
area of the page. Action methods can be called from page markup by using {! } notation in the action
parameter of one of
the following tags:
• <apex:commandButton> creates a button that calls an action
• <apex:commandLink> creates a link that calls an action
• <apex:actionPoller> periodically calls an action
• <apex:actionSupport> makes an event (such as "onclick", "onmouseover", and so on) on another,
named component,
call an action
• <apex:actionFunction> defines a new JavaScript function that calls an action
• <apex:page> calls an action when the page is loaded.
For example, in the sample page in Building a Custom Controller on page 63, the controller's save
method is called by the
action parameter of the <apex:commandButton> tag. Other examples of action methods are discussed
in Defining Action
Methods on page 35.
Getter Methods
Getter methods return values from a controller. Every value that is calculated by a controller and
displayed in a page must
have a corresponding getter method, including any Boolean variables. For example, in the sample page
in Building a Custom
Controller on page 63, the controller includes a getAccount method. This method allows the page
markup to reference the
account member variable in the controller class with {! } notation. The value parameter of the
<apex:inputField>

Describe best practices for incorporating static resources, stylesheets, and other content
into
Visualforce pages.
Extending Salesforce Styles
You can use the <apex:stylesheet> tag to add additional styles and style classes to page components.
This way you can
extend the Salesforce styles with your own.

Static resources allow you to upload content that you can reference in a Visualforce page, including
archives (such as .zip and
.jar files), images, stylesheets, JavaScript, and other files.
Using a static resource is preferable to uploading a file to the Documents tab because:
• You can package a collection of related files into a directory hierarchy and upload that hierarchy as a
.zip or .jar archive.
• You can reference a static resource by name in page markup by using the $Resource global variable
instead of hard-coding
document IDs.

The way you reference a static resource in Visualforce markup depends on whether you want to
reference a stand-alone file,
or whether you want to reference a file that is contained in an archive (such as a .zip or .jar file):

• To reference a stand-alone file, use $Resource.<resource_name> as a merge field, where


<resource_name> is the
name you specified when you uploaded the resource. For example:
<apex:image url="{!$Resource.TestImage}" width="50" height="50" />
or
<script
type="text/javascript" src="{!$Resource.MyJavascriptFile}"/>
• To reference a file in an archive, use the URLFOR function. Specify the static resource name that you
provided when you
uploaded the archive with the first parameter, and the path to the desired file within the archive with
the second. For
example:
<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50"
height="50" />
or
<script
type="text/javascript"
src="{!URLFOR($Resource.LibraryJS, '/base/subdir/file.js')}"/>

Lifecycle of a visual force page


Page request -> application server ->Metadata repository ->compiled page definition ->application
server(page renderer)->HTML result

Describe viewstate and the stateful programming model of Visualforce.


In the diagram above, the user first requests a page, either by entering a URL or clicking a link or
button. The page calls the
constructor method for the associated controller and any controller extensions, thereby instantiating
the controller objects.
The page then executes, making calls to the controller objects as necessary to determine what data to
display. The resulting
HTML is then sent to the browser. Meanwhile, all of the information necessary to maintain the state of
the database between
requests is saved as the view state. As the user interacts with the page, the page contacts the
controller objects as required to
execute action, getter, and setter methods. The view state is updated as well.

Describe how to test Visualforce controllers.


When writing unit tests for controller extension and custom controller classes, you can set query
parameters that can then be
used in the tests.

List and describe syntax features of Visualforce.


Visualforce tags cover two basic areas of functionality. One group of tags creates user interface
objects that are automatically associated with Force Platform objects or that interact with
functions implemented on the Force Platform. Another group of tags handles interactions
between the page and the Force Platform server without refetching the page, similar to the
way that AJAX (asynchronous Java script and XML) operates.

You can also see your first example of Visualforce tags, with the <apex:page> start and end
tags. Any Visualforce page must be surrounded by these page tags.
The apex: portion of a Visualforce tag is actually the namespace for the component referenced
by the tag. A namespace is a way to qualify the name of a component, insuring that the
Visualforce components you will be using in this chapter are all from this standard namespace.
Later in this book, you will both create your own component and use Visualforce messaging
components, which each have their own namepace.
Finally, you can see that this page includes standard HTML, including the <h1> heading tag.
Visualforce pages let you seamlessly use HTML tags with the extended functionality of
Visualforce specific tags.

Describe the benefits, functions, and features of Visualforce and how it conforms to the
model-view-controller pattern
The Visualforce technology is an implementation of the model-view-controller architecture
pattern, as shown in the fgure below.This pattern separates the user interface layer, or view,
from the underlying data layer, or model.The connection between the model and the view is
the controller layer, which handles the interaction between the user interface and the data.

The user interface layer of Visualforce, representing the view of the model-view-controller
architecture, is implemented with Visualforce pages, which are the focus of this chapter. You
create Visualforce pages with both standard HTML and a set of special tags that tap into the
power of the Force Platform model.
Visualforce tags cover two basic areas of functionality. One group of tags creates user interface
objects that are automatically associated with Force Platform objects or that interact with
functions implemented on the Force Platform. Another group of tags handles interactions
between the page and the Force Platform server without refetching the page, similar to the
way that AJAX (asynchronous Java script and XML) operates.
You can combine a Visualforce page with standard Force Platform tabs in your applications.
You can integrate a Visualforce page into your application from a number of different points
in your application:
From a custom tab
As an override for a standard tab, replacing a normal display for an object
As an override for standard or custom buttons or links
Embedded in a detail page layout.

Visualforce technology can be used to implement both the view and the controller portion of
the model-view-controller architecture.The controller portion of Visualforce comes in two
varieties.The Force Platform automatically creates a standard controller for every object in
your Force Platform database.These standard controllers provide the basic functionality
embedded in a Force Platform tab page.The second type of controller is a custom controller,
created with Apex code.

You can create extensions to a standard controller to deliver additional functionality to your
Visualforce pages with Apex code. You can also create custom controllers with Apex code,
which handle all the interaction between a Visualforce page and one or more Force Platform
objects.

What is a Visualforce Page?


Developers can use Visualforce to create a Visualforce page defnition. A page defnition consists of two
primary elements:
• Visualforce markup
• A Visualforce controller
Visualforce Markup
Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code
embedded within a single
<apex:page> tag.The markup defnes the user interface components that should be included on the
page, and the way they
should appear.
Visualforce Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with
the components specifed
in associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide
access to the data that
should be displayed in a page, and can modify component behavior.
A developer can either use a standard controller provided by the Force.com platform, or add custom
controller logic with a
class written in Apex:
• A standard controller consists of the same functionality and logic that is used for a standard
Salesforce.com page. For
example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page
results in the same
behavior as clicking Save on a standard Account edit page.
If you use a standard controller on a page and the user doesn't have access to the object, the page will
display a insuffcient
privileges error message. You can avoid this by checking the user's accessibility for an object and
displaying components
appropriately.
• A standard list controller enables you to create Visualforce pages that can display or act on a set of
records. Examples of
existing Salesforce.com pages that work with a set of records include list pages, related lists, and mass
action pages.
• A custom controller is a class written in Apex that implements all of a page's logic, without leveraging
a standard controller.
If you use a custom controller, you can defne new navigation elements or behaviors, but you must also
reimplement any
functionality that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and
feld-level permissions
of the current user are ignored. You can specify whether a user can execute methods in a custom
controller based on the
user's profle.
• A controller extension is a class written in Apex that adds to or overrides behavior in a standard or
custom controller.
Extensions allow you to leverage the functionality of another controller while adding your own custom
logic.
Because standard controllers execute in user mode, in which the permissions, feld-level security, and
sharing rules of the
current user are enforced, extending a standard controller allows you to build a Visualforce page that
respects user permissions.
Although the extension class executes in system mode, the standard controller executes in user mode.
As with custom
controllers, you can specify whether a user can execute methods in a controller extension based on the
user's profle.

Describe how to incorporate Visualforce pages into Force.com applications


Developers can use Visualforce pages to:
• Override standard buttons, such as the New button for accounts, or the Save button for contacts
• Override tab overview pages, such as the Accounts tab home page
• Defne custom tabs
• Embed components in detail page layouts
• Create dashboard components or custom help pages

• Build wizards and other multistep processes


• Create your own custom fow control through an application
• Defne navigation patterns and data-specifc rules for optimal, effcient application interaction

Describe how to create data, action, and component binding expressions


• anything inside {! } is evaluated as an expression;
• All global variables are referenced with a $ symbol,{!$User.FirstName}
• To bring an account record into the current context, you must add a query parameter to the
page URL that specifes the ID of the record
Redirecting to a Standard Object List Page:<apex:page action="{!URLFOR($Action.Account.List,
$ObjectType.Account)}"/>

List and describe syntax features of Visualforce


Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code
embedded within a single
<apex:page> tag.The markup defnes the user interface components that should be included on the
page, and the way they
should appear.

Describe best practices for incorporating static resources, stylesheets, and other content
into Visualforce pages
To reference a stand-alone fle, use $Resource.<resource_name> as a merge feld, where
<resource_name> is the
name you specifed when you uploaded the resource. For example:
<apex:image url="{!$Resource.TestImage}" width="50" height="50" />

To reference a fle in an archive, use the URLFOR function. Specify the static resource name that you
provided when you
uploaded the archive with the frst parameter, and the path to the desired fle within the archive with
the second. For
example:
<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50"
height="50" /
>

Through a custom controller, you can dynamically refer to the contents of a static resource using the
<apex:variable>
tag. First, create the custom controller:
global class MyController {
public String getImageName() {
return 'Picture.gif';//this is the name of the image
}
}
Then, refer to the getImageName method in your <apex:variable> tag:
<apex:page renderAs="pdf" controller="MyController">
<apex:variable var="imageVar" value="{!imageName}"/>
<apex:image url="{!URLFOR($Resource.myZipFile, imageVar)}"/>
</apex:page>
If the name of the image changes in the zip fle, you can just change the returned value in
getImageName.

Using Salesforce.com Styles

You can specify the tab style that should be used to style a
component by associating a page with a standard controller or by setting the tabStyle attribute on the
<apex:page> or
<apex:pageBlock> tags:
• When you use a standard controller with a Visualforce page, your new page takes on the style of the
associated object's
standard tab in Salesforce.com. It also allows you to access the methods and records associated with
the associated object.
• When you use a custom controller, the tabStyle attribute of an <apex:page> tag allows you to mimic
the look and
feel of the associated Salesforce.com page. If you only want portions of the page to be similar to a
Salesforce.com page,
you can use the tabStyle attribute on the <apex:pageBlock> tag.

Salesforce.com uses different stylesheets (.css fles) throughout the application to ensure that every
tab conforms to the
Salesforce.com look and feel.When you specify true for the header attribute of the <apex:page> tag
(or leave it blank, as
the default is true) these stylesheets are automatically included. You can reference these stylesheets to
further customize the
components on your page.This is relevant when you use a custom controller and you do not set the
tabStyle attribute on
the page.
The following stylesheets contain the style classes that you can reference.They are located in the
/dCSS/ directory of your
salesforce.com instance.
• dStandard.css – Contains the majority of style defnitions for standard objects and tabs
• allCustom.css – Contains style defnitions for custom tabs

Describe how to create and use a Visualforce page as the template for multiple pages

- Defning Custom Components


- Defning Templates with <apex:composition>
- Referencing an Existing Page with <apex:include>

Defning Templates with <apex:composition>


If you want to defne a base template that allows portions of the template to change with each
implementation, use the
<apex:composition> component.This templating method is best for situations when you want to
maintain an overall
structure to a page, but need the content of individual pages to be different, such as a website for
news articles where
different articles should appear with the same page layout.
Through this technique, you can also defne a template from a PageReference returned by a controller.

Defning Templates with <apex:composition>

All templates defned using <apex:composition> must have one or more child <apex:insert> tags. An
<apex:insert>
tag indicates to pages that import the template that a section needs a defnition. Any Visualforce page
that imports a template
using <apex:composition> must use <apex:define> to specify the content of each <apex:insert>
section of the
template.

Describe how to handle client-side behavior through the use of either standard components
or custom JavaScript
Partial Page Updates :
The simplest way to implement a partial page update is to use the reRender attribute on an
<apex:commandLink> or
<apex:commandButton> tag to identify a component that should be refreshed.When a user clicks the
button or link, only
the identifed component and all of its child components are refreshed

apex:actionFunction
apex:actionSupport
apex:actionStatus
apex:actionRegion

Try this example in your own org:


<apex:page standardController="account">
<apex:form id="theForm"> {!account.industry}
<apex:inputField value="{!account.name}" required="true"/>
<apex:actionRegion>
<apex:inputField value="{!account.industry}"/>
<apex:commandButton value="Click" rerender="theForm"/>
</apex:actionRegion>
</apex:form>
</apex:page>
It works fine. If you select something from the picklist and click the button, you'll see the industry get
updated and no message about the first field being required.

However add action="{!save}" to your commandButton component and then select something from
the picklist again and click the button. Now you get an error message. That's because you can't
actually save the account without specifying a name. And furthermore, even if you type something in
the name field, select something from the picklist, and hit the button you'll still get the same error
message because the actionRegion defines what actually gets submitted to the server, meaning that
what you type in the name field will not actually get set when you click the button, thus you'll still get
an error telling you it's required.

Also note that in my original example, if you remove the actionRegion component (and the save action
from the button) and select something from the drop down and click the button, you'll get the required
error message.

Describe and incorporate proper error-handling techniques


apex:message
apex:messages

try{
...
}
catch(Exception ex){
ApexPages.addMessages(ex);
}

Describe how to create a custom component and the benefits of custom components versus
other techniques for code reuse
Unlike page templates, which also enable developers to reuse markup, custom components provide
more power and fexibility
because:
• Custom components allow developers to defne attributes that can be passed in to each
component.The value of an attribute
can then change the way the markup is displayed on the fnal page, and the controller-based logic that
executes for that
instance of the component.This behavior differs from that of templates, which do not have a way of
passing information
from the page that uses a template to the template's defnition itself.
• Custom component descriptions are displayed in the application's component reference dialog
alongside standard component
descriptions.Template descriptions, on the other hand, can only be referenced through the Setup area
of Salesforce.com
because they are defned as pages.

The c: namespace refers to any component in your org that has not been assigned
to a specifc namespace, such as the slogo component.

Describe how to leverage PDF generation


• Currently, PDF is the only supported content converter.
• Rendering a Visualforce page as a PDF is intended for pages that are designed and optimized for
print.
• Standard components which are not easily formatted for print or contain form elements like inputs,
buttons, and any
component that requires JavaScript to be formatted, should not be used.This includes but is not limited
to any component
that requires a form element.
• Verify the format of your rendered page before deploying it.
• If the PDF fails to display all the characters, adjust the fonts in your CSS to use a font that supports
your needs. For
example:
<apex:page renderas="pdf">
<html>
<head>
<style> body { font-family: Arial Unicode MS; } </style>
</head>
This page is rendered as a PDF
</html>
</apex:page>
• The maximum response size when creating a PDF must be below15 MB.
• Note that the following components do not support double-byte fonts when rendered as a PDF:
- <apex:pageBlock>
- <apex:sectionHeader>

Distinguish between standard controllers, custom controllers, and extensions


Standard controllers can provide all the functionality you need for a Visualforce page because they
include the same logic that
s used for a standard page. For example, if you use the standard Accounts controller, clicking a Save
button in a Visualforce
page results in the same behavior as clicking Save on a standard Account edit page.
However, if you want to override existing functionality, customize the navigation through an
application, use callouts or Web
services, or if you need fner control for how information is accessed for your page, you can write a
custom controller or a
controller extension using Apex.

A custom controller is an Apex class that implements all of the logic for a page without leveraging a
standard controller. Use
custom controllers when you want your Visualforce page to run entirely in system mode, which does
not enforce the profle-based
permissions and feld-level security of the current user.
A controller extension is an Apex class that extends the functionality of a standard or custom
controller. Use controller extensions
when:
• You want to leverage the built-in functionality of a standard controller but override one or more
actions, such as edit, view,
save, or delete.
• You want to add new actions.
• You want to build a Visualforce page that respects user permissions. Although a controller extension
class executes in
system mode, if a controller extension extends a standard controller, the logic from the standard
controller does not execute
in system mode. Instead, it executes in user mode, in which the profle-based permissions, feld-level
security, and sharing
rules of the current user apply.

• Apex methods and variables are not instantiated in a guaranteed order.


• You can't use data manipulation language (DML) operations in a “getxxx” method in a
controller. For example, if your controller had a getName method, you could not use insert or
update in the method to create an object.
• You can't use data manipulation language (DML) operations in a constructor method in a
controller.
• You can't use the @future annotation in a “getxxx” or “setxxx” method in a controller, or in the
constructor for a controller.
• Primitive Apex data types such as String or Integer are passed by value to the component's
controller.
• Non-primitive Apex data types such as lists and sObjects are passed by reference to
component's controller.This means that if component's controller changes the name of an
account, the changes are available in page's controller.

Describe the request lifecycle of a Visualforce page


Order of Execution in a Visualforce Page
When a user views a Visualforce page, instances of the controller, extensions, and components
associated with the page are
created by the server.The order in which these elements are executed can affect how the page is
displayed to the user.
To fully understand the order of execution of elements on a Visualforce page, you must frst understand
the page's lifecycle–that
is, how the page is created and destroyed during the course of a user session.The lifecycle of a page is
determined not just by
the content of the page, but also by how the page was requested.There are two types of Visualforce
page requests:
• A get request is an initial request for a page either made when a user enters an URL or when a link
or button is clicked that
takes the user to a new page.
• A postback request is made when user interaction requires a page update, such as when a user clicks
on a Save button and
triggers a save action.

Note: The maximum response size from a Visualforce page request must be below 15 MB.

Order of Execution for Visualforce Page Get Requests:

constructors->components constructors->attributes ->assign to->action->expressions,getting/setting-


>view state created

1. The constructor methods on the associated custom controller or controller extension classes are
called, instantiating the
controller objects.
2. If the page contains any custom components, they are created and the constructor methods on any
associated custom
controllers or controller extensions are executed. If attributes are set on the custom component using
expressions, the
expressions are evaluated after the constructors are evaluated.
3. The page then executes any assignTo attributes on any custom components on the page. After the
assignTo methods
are executed, expressions are evaluated, the action attribute on the <apex:page> component is
evaluated, and all other
method calls, such as getting or setting a property value, are made
4. If the page contains an <apex:form> component, all of the information necessary to maintain the
state of the database
between page requests is saved as an encrypted view state.The view state is updated whenever the
page is updated.
5. The resulting HTML is sent to the browser. If there are any client-side technologies on the page,
such as JavaScript, the
browser executes them.
As the user interacts with the page, the page contacts the controller objects as required to execute
action, getter, and setter
methods.
Once a new get request is made by the user, the view state and controller objects are deleted.
Note: If the user is redirected to a page that uses the same controller and the same or a proper
subset of controller
extensions, a postback request is made.When a postback request is made, the view state is
maintained.
If the user interaction requires a page update, such as when the user clicks a Save button that triggers
a save action, a postback
request is made. For more information on postback requests, see Order of Execution for Visualforce
Page Postback Requests
on page 75.

Order of Execution for Visualforce Page Postback Requests:

decode view state->expressions,set methods->action triggered the postback executed

A postback request is made when user interaction requires a page update, such as when a user clicks
on a Save button and triggers
a save action.The following diagram shows how a Visualforce page interacts with a controller extension
or a custom controller
class during a postback request:
1. During a postback request, the view state is decoded and used as the basis for updating the values
on the page.
Note: A component with the immediate attribute set to true bypasses this phase of the request. In
other words,
the action executes, but no validation is performed on the inputs and no data changes on the page.
2. After the view state is decoded, expressions are evaluated and set methods on the controller and
any controller extensions,
including set methods in controllers defned for custom components, are executed.
These method calls do not update the data unless all methods are executed successfully. For example,
if one of the methods
updates a property and the update is not valid due to validation rules or an incorrect data type, the
data is not updated and
the page redisplays with the appropriate error messages.
3. The action that triggered the postback request is executed. If that action completes successfully, the
data is updated. If the
postback request returns the user to the same page, the view state is updated.
Note: The action attribute on the <apex:page> component is not evaluated during a postback request.
It is
only evaluated during a get request.
4. The resulting HTML is sent to the browser.
If the postback request indicates a page redirect and the redirect is to a page that uses the same
controller and a proper subset
of controller extensions of the originating page, a postback request is executed for that page.
Otherwise, a get request is executed
for the page. If the postback request contains an <apex:form> component, only the ID query
parameter on a postback request
is returned.
Tip: You can use the setRedirect attribute on a pageReference to control whether a postback or get
request is
executed. If setRedirect is set to true, a get request is executed. Setting it to false does not ignore the
restriction
that a postback request will be executed if and only if the target uses the same controller and a proper
subset of
extensions. If setRedirect is set to false, and the target does not meet those requirements, a get
request will be
made.

Describe viewstate and the stateful programming model of Visualforce

all of the information necessary to maintain the state of the databasebetween page requests is saved
as an encrypted view state.

With the stateful programming model provided by Visualforce, custom controllers can maintain state
between pages making development of wizards straightforward.

Some Apex objects are automatically considered transient, that is, their value does not get saved as
part of the page's view
state.These objects include the following:
• Savepoints
• PageReferences
• XmlStream Classes
• Collections automatically marked as transient only if the type of object that they hold is automatically
marked as transient,
such as a collection of Savepoints
• Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
Static variables also don't get transmitted through the view state.

Describe the benefits of using Apex classes as structs or wrappers of sobjects

Testing and Debugging 16%

Describe the techniques and tools available to debug, test, and monitor Apex code execution
anonymous blocks

The System Log console is a separate window that can be used for debugging code snippets or tracking
code execution during
a transaction. Access the System Log console from the Salesforce.com user interface by clicking
System Log in the upper
right of any page.

When an end-user invokes an Apex script that surpasses more than 50% of any governor limit, you
can specify a user in your
organization to receive an email notifcation of the event with additional details.

Unit test methods take no arguments, commit


no data to the database, send no emails, and are fagged with the testMethod keyword in the method
defnition.

"run all test" on "Apex class" Salesforce UI

List and describe the contents and use of the System Log

Database
Workflow
Validation
Callout
Apex Code
Apex Profiling

You can specify the following log levels.The levels are listed from lowest to highest. Specifc events are
logged based on the
combination of category and levels. Most events start being logged at the INFO level.The level is
cumulative, that is, if you
select FINE, the log will also include all events logged at DEBUG, INFO,WARN and ERROR levels.
Note: Not all levels are available for all categories: only the levels that correspond to one or more
events.
• ERROR
• WARN
• INFO
• DEBUG
• FINE
• FINER
• FINEST
Describe how to create and run unit tests as well as techniques for achieving 100% test
coverage.
• Cover as many lines of code as possible
Important:
◊ You must have at least 75% of your Apex scripts covered by unit tests to deploy your
scripts to production
environments. In addition, all triggers should have some test coverage.
◊ Salesforce recommends that you have 100% of your scripts covered by unit tests, where
possible.
◊ Calls to System.debug are not counted as part of Apex code coverage in unit tests.
• In the case of conditional logic (including ternary operators), execute each branch of code logic.
• Make calls to methods using both valid and invalid inputs.
• Complete successfully without throwing any exceptions, unless those errors are expected and caught
in a try…catch block.
• Always handle all exceptions that are caught, instead of merely catching the exceptions.
• Use System.assert methods to prove that code behaves properly.
• Use the runAs method to test your application in different user contexts.
• Use the isTest annotation. Classes defined with the isTest annotation do not count against your
organization limit of
1 MB for all Apex scripts.
• Exercise bulk trigger functionality—use at least 20 records in your tests.
• Use the ORDER BY keywords to ensure that the records are returned in the expected order.
• Not assume that record IDs are in sequential order
Record IDs are not created in ascending order unless you insert multiple records with the same
request. For example, if
you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of
account B may or may
not be sequentially higher.
• Set up test data:
◊ Create the necessary data in test classes, so the tests do not have to rely on data in a
particular organization
◊ Create all test data before calling the starttest method
• Write comments stating not only what is supposed to be tested, but the assumptions the tester made
about the data, the
expected outcome, and so on.
• Test the classes in your application individually. Never test your entire application in a single test.

Use the isTest annotation to define classes or individual methods that only contain code used for
testing your application.
The isTest annotation is similar to creating methods declared as testMethod.
Note: Classes defined with the isTest annotation do not count against your organization limit of 1 MB
for all Apex
scripts. Individual methods defined with the isTest annotation do count against your organization
limits.
Classes defined as isTest cannot be interfaces or enums.
A class defined as isTest can only be invoked using the Force.com runTests API call, or from the
Salesforce user interface
(using the Run Tests button). You cannot call it from another class or trigger.

Test methods are declared with the following syntax:


static testMethod void test_name() {
code_block;
}
You must declare test methods as static, with the testMethod keyword, and with a void
return.Test methods cannot accept any arguments, and no data changes performed in a test
method are committed to the Force Platform database.
In a case where a method has multiple possible branches, due to logical conditions, create test
methods to test all of these branches.
The key methods to use in your unit tests are the system.assert() methods:
• System.assert(condition) returns true if the condition argument is true
• System.assertEquals(x, y) compares the value of x and y and returns true if they
are equal
• System.assertNotEquals(x, y) compares the value of x and y and returns true if they
are not equal .

Note: Test methods cannot be used to test Web service callouts.Web service callouts are
asynchronous, while unit
tests are synchronous

Describe how to test Visualforce controllers

PageReference aPageName = new PageReference('Page.PageToBeTested');


Test.setCurrentPage(aPageName );
ApexPages.currentPage().getParameters().put('id', Myid);

For controller extension:


ApexPages.StandardController ctrl = new ApexPages.StandardController(Sobject);
ContollerExtensionClass aContollerExtension = new ContollerExtensionClass (ctrl);

Describe how to test email send and receive in different environments


moving the mail functions into their own class and then pass the required parameters to send the mail

public class MailerUtils {

public static void sendMail(string message) {

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();


String[] toAddresses = new String[] {'me@email1.com','you@email2.com'};
mail.setToAddresses(toAddresses);

mail.setSubject('My Subject');

mail.setUseSignature(false);
mail.setHtmlBody(message);

// Send the email


Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

public static testMethod void testSendMail() {


sendMail('This is my email message');
}

@IsTest
private class EmailDemoReceiveHandlerTests {

// Create a new email and envelope object


Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

// Set up your data if you need to

// Create the email body


email.plainTextBody = 'This should become a note';
email.fromAddress ='test@test.com';
String contactEmail = 'jsmith@salesforce.com';
email.ccAddresses = new String[] {'Jon Smith <' + contactEmail + '>'};
email.subject = 'Dummy Account Name 123';

EmailDemoReceive edr = new EmailDemoReceive();

Test.startTest();
Messaging.InboundEmailResult result = edr.handleInboundEmail(email, env);
Test.stopTest();

System.assert (result.success, 'InboundEmailResult returned a failure message');

Account [] accDb = [select ID from Account where name=:email.subject];


System.assertEquals (1, accDb.size(),'Account was not inserted');
Contact [] cDb = [select firstname,lastname from Contact where email=:contactEmail];
System.assertEquals (1, cDb.size(),'Contact was not inserted!');
Contact c = CDb[0];
System.assertEquals ('Jon', c.firstName);
System.assertEquals ('Smith', c.LastName);
Note [] nDb = [select body from Note where ParentID=:accDb[0].id];
System.assertEquals (1,nDb.size(), 'A note should have been attached');
System.assertEquals (email.plainTextBody, nDb[0].body);

}
}

Extra Notes:

Best Practices for Using runAs


The following items use the permissions granted by the user specified with runAs running as a specific
user:
• Dynamic Apex
• Methods using with sharing or without sharing
• Shared records

Methods with the future annotation have the following limits:


• No more than 10 method calls per Apex invocation
Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do
not count against your limits for the number of queued jobs.
• Methods with the future annotation can execute 100 SOQL queries when they are in the context of a
testMethod
• No more than 200 method calls per Salesforce.com license per 24 hours
• The parameters specifed must be primitive dataypes, arrays of primitive datatypes, or collections of
primitive datatypes.
• Methods with the future annotation cannot take sObjects or objects as arguments.
• Methods with the future annotation cannot be used in Visualforce controllers in either
getMethodName or
setMethodName methods, nor in the constructor.
Remember that any method using the future annotation requires special consideration, because the
method does not
necessarily execute in the same order it is called.
You cannot call a method annotated with future from a method that also has the future annotation. Nor
can you call a
trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDF PageReference methods cannot be used in methods with the
future annotation.

Virtual and abstract


The virtual defnition modifer declares that this class allows extension and overrides. You cannot
override a method
with the override keyword unless the class has been defned as virtual.
The abstract defnition modifer declares that this class contains abstract methods, that is, methods that
only have their
signature declared and no body defned.

// Exception inner class


public virtual class MyException extends Exception {
// Exception class member variable
public Double d;
// Exception class constructor
MyException(Double d) {
this.d = d;
}
// Exception class method, marked as protected
protected void doIt() {}
}
// Exception classes can be abstract and implement interfaces
public abstract class MySecondException extends Exception implements MyInterface {
}

web services
The successfully generated Apex class includes stub and type classes for calling the third-party Web
service represented by the WSDL document.
• The WSDL target namespace maps to the Apex class name.
• Each complex type becomes a class. Each element in the type is a public field in the class.
• The WSDL port name maps to the stub class.
• Each operation in the WSDL maps to a public method.

Apex Scheduler Best Practices

• Salesforce.com only adds the process to the queue at the scheduled time. Actual execution
may be delayed based on service
availability.
• Use extreme care if you are planning to schedule a class from a trigger.You must be able to
guarantee that the trigger will
not add more scheduled classes than the ten that are allowed. In particular, consider API bulk
updates, import wizards,
mass record changes through the user interface, and all cases where more than one record
can be updated at a time.
• Though it's possible to do additional processing in the execute method, Salesforce.com
recommends that all processing
take place in a separate class.
• You can only have ten classes scheduled at one time. You can evaluate your current count by
viewing the Scheduled Jobs
page in Salesforce.com or programmatically using the Force.com Web services API to query
the CronTrigger object.

• You can't use the getContent and getContentAsPDF PageReference methods in scheduled
Apex.
Visualforce Email Template

You cannot send a mass email using a Visualforce email template. The merge felds
{!Receiving_User.field_name} and {!Sending_User.field_name} work only for mass email and are
unavailable in Visualforce email templates.

• The attributes recipientType and relatedToType act as controllers for the email template.With them
you can access
the same merge felds that are available to other standard controllers.The recipientType attribute
represents the
recipient of the email.The relatedToType attribute represents the record to associate with the email.
• The <messaging:htmlEmailBody> component can include a mix of Visualforce markup and HTML.The
<messaging:plainTextEmailBody> component can only include Visualforce markup and plain text.
• To translate Visualforce email templates based on recipients' or related objects' languages, use the
<messaging:emailTemplate> tag's language attribute (valid values: Salesforce.com supported
language keys, for
example, “en-US”).The language attribute accepts merge felds from the email template's recipientType
and
relatedToType attributes. You create custom language felds for use in the merge felds. The Translation
Workbench