501 Study Notes
501 Study Notes
** Author: Jack
** Created on: 07/2010
** Email: [email protected]
** 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
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
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
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.
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.
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
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
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
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.
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]
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.
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
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
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.
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.
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.
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);
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:
// Create an inboundEmailResult object for returning the result of the Apex Email
Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
// 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 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.
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');
? 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.
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
•
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
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%
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.
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.
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.
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 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,
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):
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.
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.
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
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
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.
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.
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.
Note: The maximum response size from a Visualforce page request must be below 15 MB.
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.
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.
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 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.
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.
Note: Test methods cannot be used to test Web service callouts.Web service callouts are
asynchronous, while unit
tests are synchronous
mail.setSubject('My Subject');
mail.setUseSignature(false);
mail.setHtmlBody(message);
@IsTest
private class EmailDemoReceiveHandlerTests {
Test.startTest();
Messaging.InboundEmailResult result = edr.handleInboundEmail(email, env);
Test.stopTest();
}
}
Extra Notes:
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.
• 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