501 study notes

42
******************************************************************************* ** 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 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

Upload: anil-kumar

Post on 26-Mar-2015

546 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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 ofmy 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 attributesControllers – know the differences between custom controllers and extensions and how they functionUnit testing – how to write unit tests with proper test coverageEmail services – there were surprisingly numerous questions regarding inbound and outbound emailSOQL – you must know how to construct SOQL queries with and without related objectsTrigers – 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 GuideMigration Tool - what are files (file names) you need to deal with during migration processVisual force template, component

Development Lifecycle 13%

List and describe the key features, tools, and technologies of application lifecyclemanagement and Force.com developmentPoint-and-Click Setup Tools

Data ComponentsCustom objects,Custom fields,Custom relationships,Field history

Business Logic ComponentsSecurity and permission settings,Formula fields and validation rules,Workflow rules,Approval

processes,EmailUser Interface Components

Tabs,Page layouts,Custom views,Reports and Dashboards,ConsoleVisualforceApex

Classes,Triggers,Anonymous blocksForce.com SitesSalesforce MobileThe Web Services APIThe Bulk APIThe Force.com Migration Tool

The Force.com Migration Tool is a Java/Ant-based command-line utility for moving metadatabetween a local directory anda Salesforce.com organization.the Force.com Migration Tool is especially useful in the followingscenarios:• Development projects where you need to populate a test environment with large amounts of setupchanges—makingchanges 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, ifyou want to changethe Running User on a dashboard, you can retrieve the Running User from organization A, make achange, and then deploythe Running User to organization B. If you tried to do this in the Force.com IDE, the IDE would forceyou to save thechange back to organization A (where the organization B user probably does not exist) beforelaunching the Deploy Wizardto deploy to organization B. The Force.com Migration Tool gives you complete control over theretrieve() anddeploy() commands; editing and saving a file on your local file system does not change the metadatain any organizationuntil you choose to deploy it.• Multi-stage release processes—a typical development process requires iterative building, testing, andstaging before releasingto a production environment. Scripted retrieval and deployment of components can make this process

Page 2: 501 Study Notes

much more efficient.• Repetitive deployment using the same parameters—you can retrieve metadata from yourorganization, make changes, anddeploy your changes to an organization. If you need to repeat this process, it is as simple as calling thesame deploymenttarget again.• When migration from staging to production is done by highly technical resources—anyone whoprefers deploying in ascripting environment will find the Force.com Migration Tool a familiar process.

Force.com IDEThe Metadata API

Describe best practices for managing multi-team and multi-project development initiativeswith 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 changes10. 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 arevision 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.complatformDescribe 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 wantto create newapplications on the Force.com platform and package them for distribution on the AppExchange.However, Developer Editionorganizations can also be used any time you require an organization for development purposes.

Choosing a Development EnvironmentUse 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 sandboxesare not available toyou.• You are an independent software vendor (ISV) creating an application for distribution on theAppExchange. Note thatthis development scenario is not covered by this guide. For more information, see the topics listed inAdditional Resourceson page 6.Note: You can create a development environment that is similar to a sandbox by retrieving all of your

Page 3: 501 Study Notes

organization'smetadata into a Force.com project, and then deploying the project to a Developer Edition organization.However, notall metadata types can be retrieved and deployed, and not all features in your production organizationmay be enabledin a Developer Edition organization, so your development environment will not be as complete of areplica 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 singleadministrator who must have access to both the source and target organizations.With the IDE, each individual deployment is a separate process.The Force Platform MigrationTool allows you to automate this process with scripts, so you can deploy to multipleorganizations 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 smallnumber of targets, using the Force Platform IDE is probably the best method. If you haveaccess to both organizations and are deploying to a larger number of servers, or if you arerepeatedly deploying to a set of organizations, the Force Platform Migration Tool is probablyyour best choice.Packaging separates the publishing of an application from the installation of the applicationin another organization, so you can perform a single publishing operation and have many otherorganizations install the result.The most crucial difference between this one-to-manydeployment 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 thetask of installing them in a target organization.The packaging method is required if you donot have access to the target organization—the typical scenario for an independent softwarevendor (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.

Page 4: 501 Study Notes

• Multistage release processes - A typical development process requires iterative building,testing, and staging before releasing to a production environment. Scripted retrieval anddeployment of components can make this process much more efficient.

• Repetitive deployment using the same parameters - You can retrieve all the metadata in yourorganization, make changes, and deploy a subset of components. If you need to repeat thisprocess, 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 ascripting environment will find the Force.com Migration Tool a familiar process.

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

Unmanaged packages do not allow you to install components of the same name, and so thosecomponents cannotbe further modifed (via an unmanaged package) after the initial installation.Another kind of package is a managed package. Managed packages are used for distributing versionedapplications and addconstraints that make them poorly suited to use as an IT development tool. Furthermore, while anytype of organization canbe used to create an unmanaged package, managed packages must be created using a DeveloperEdition organization.

Note: Unmanaged packages can be a useful for distributing initial components to multipleorganizations. For example,if you want all of your development environments to have the same set of core Apex classes, you couldpackage theseand distribute them on the AppExchange.This use of unmanaged packages is a convenient way todeliver fles tomultiple 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 isconveyed—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 toolThe Force.com Migration Tool is a Java/Ant-based command-line utility for moving metadata betweena local directory anda 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 fromone Salesforce.comorganization to another is:1. Enter credentials and connection information for source Salesforce.com organization inbuild.properties2. Create retrieve targets in build.xml3. Construct a project manifest in package.xml4. Run the Force.com Migration Tool to retrieve metadata fles from Salesforce.com5. Enter credentials and connection information for destination Salesforce.com organization inbuild.properties6. 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 torepeatedly perform the same tasks that you would perform with the Deploy to Server choicefrom within the IDE.This repeatability makes the use of this approach very appropriate whenyou are migrating Force Platform components to more than one internal target, since you willstill have to have access to an appropriate user in the receiving organization.

Describe the capabilities and constraints of metadata text files for manipulating application

Page 5: 501 Study Notes

metadataCommon Metadata IssuesThe most common metadata issues are detailed below:• Retrieving custom felds on standard objects — When you use the wildcard symbol in package.xml, toretrieve all objects,you will not retrieve standard objects, or custom felds on standard objects.To retrieve custom felds onstandard 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 ofthe retrieve request.For example, profles will only include feld-level security for felds included in custom objects returned atthe same timeas 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 sharedwith multipleorganizations, or distributed on Force.com AppExchange. Managed packages are packages that can beupgraded in theinstaller's organization.They differ from unmanaged packages in that some components are locked, inorder to permitupgrades. Metadata components that are not in any package can be accessed with the unpackagedattribute ofsf:retrieve and sf:deploy.• Workfow — A .workflow fle is a container for the individual workfow components associated with anobject, includingWorkfowAlert,WorkfowFieldUpdate,WorkfowOutboundMessage,WorkfowRule, and WorkfowTask.Toretrieveall 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 metadatacomponents aredependent on a particular object for their defnition: CustomField, Picklist, RecordType, Weblink, andValidationRule.This means you must dot-qualify the component name with the object name inpackage.xml, andmay 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 theMetadata API.Tomigrate reports or documents you must move them to a public folder.

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

Apex Code 33%

List and describe the features of Apex and distinguish between it and other programminglanguages.as a language, apex is:integrated:dml,soqleasy to use: java likedata focused:rigorous:strongly-typedhosted:interpreted,executed and controlled entirely by force.com platformmultitenant awareautomatically upgradeableeasy 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,

Page 6: 501 Study Notes

Salesforce.com provides the abilityto customize the prebuilt applications to fit your organization. However, your organization may havecomplex business processesthat are unsupported by the existing functionality.When this is the case, the Force.com platformincludes a number of waysfor advanced administrators and developers to implement custom functionality. These includeApex,Visualforce, and the Webservices API.ApexUse 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 singlerecord or object)• Attach custom logic to another operation, such as saving a record, so that it occurs whenever theoperation is executed,regardless of whether it originates in the user interface, a Visualforce page, or from the Web ServicesAPI

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 PrimitiveData Types on page27)• An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, orMyCustomObject__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, orcollections (see Listson 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 methodtypes, but do appear in system staticmethods:• AnyType. The valueOf static method converts an sObject field of type AnyType to a standardprimitive. AnyType isused within the Force.com platform database exclusively for sObject fields in field history trackingtables.• Currency. The Currency.newInstance static method creates a literal of type Currency. This method isfor use solelywithin SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiateCurrency in anyother 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.

Page 7: 501 Study Notes

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 willalso be modifed in theoriginal code that called the method.• Can be recursive.• Can have side effects, such as DML insert statements that initialize sObject record IDs. See ApexData ManipulationLanguage (DML) Operations on page 213.• Can refer to themselves or to methods defned later in the same class or anonymous block. Apexparses methods in twophases, so forward declarations are not needed.• Can be polymorphic. For example, a method named foo can be implemented in two ways, one with asingle Integerparameter and one with two Integer parameters. Depending on whether the method is called with oneor two Integers,the Apex parser selects the appropriate implementation to execute. If the parser cannot fnd an exactmatch, it then seeksan 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 asstand-alone procedurestatements 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 assignedto 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 constructorexists

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 atmost once, either inthe 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 firstrefer to it.

Apex data typesinclude 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 youdeclare it. You can alsoassign values later.

Page 8: 501 Study Notes

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 testmethods. One advantageto creating a separate class for testing as opposed to adding test methods to an existing class is thatclasses defined with isTestdo not count against your organization limit of 1 MB for all Apex scripts. You can also add the @isTestannotation toindividual methods

? Test failures, if any? Detailed information about the Apex scripts that are covered by unit tests, including line and columnnumbers for all testedcode, the number of times the code was executed, and the amount of time it took for that code to betested? Detailed information about Apex that is not covered by unit tests, including line and column numbers? Test coverage warnings, if any? The debug logThe debug log is automatically set to the PROFILE log level. You cannot change the log level. ThePROFILE log levelincludes log messages generated by calls to the System.debug method, every DML statement or inlineSOQL or SOSLquery, and the entrance and exit of every user-defined method. In addition, the end of the debug logcontains overallprofiling information for the portions of the request that used the most resources, in terms of SOQLand SOSL statements,DML operations, and Apex method invocations. These three sections list the locations in the code thatconsumed themost time, in descending order of total cumulative time, along with the number of times they wereexecuted.

if you update or delete a record in its before trigger, or delete a record in its after trigger, you willreceive a runtimeerror. This includes both direct and indirect operations. For example, if you update account A, and thebefore update triggerof account A inserts contact B, and the after insert trigger of contact B queries for account A andupdates it using the DMLupdate statement or database method, then you are indirectly updating account A in its before trigger,and you will receive aruntime 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 deletes60Triggers? Recursive Apex methods and triggers that invoke bulk DML statements

Describe the ways Apex can be invoked.• Triggers• Apex scheduler (for Apex classes only)

Page 9: 501 Study Notes

• 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 anApex class that implements a specific Apex interface for the incoming emails. The second isto 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 emailaddress that receives incoming messages. The receipt of a message triggers the execution ofthis functionality, implemented in the same Apex class.

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

The email parameter represents the email itself, and gives you access to various headerinformation, such as from, to, and cc, as well as the body of the email and potentially anyattachments.

Messaging.SingleEmailMessage mail = newMessaging.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, theMessaging.sendEmail method can only be called a maximum of 10 times in a requestbefore an exception is thrown. In addition to this limit, there is a daily limit for thesending organization. Once this is reached, an error status ofMASS_MAIL_LIMIT_EXCEEDED is returned for all subsequent calls that day.

The Messaging.SingleEmailMessage class provides two options for you to add anattachment to the emails you generate from your Apex code: the setDocumentAttachmentsand 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 messagebased 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 emailwas sent, first openedand last opened, and the total number of times it was opened. (For more information, see “Tracking

Page 10: 501 Study Notes

HTML Email” in theSalesforce.com online help.)To send individual and mass email with Apex, use the following classes:SingleEmailMessageInstantiates an email object used for sending a single email message. The syntax is:Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();MassEmailMessageInstantiates an email object used for sending a mass email message. The syntax is:Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();MessagingIncludes the static sendEmail method, which sends the email objects you instantiate with either theSingleEmailMessageor 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 youspecify false forthis parameter and a record fails, the remainder of the DML operation can still succeed. This methodreturns a resultobject that can be used to verify which records succeeded, which failed, and why. The default is true.For additionalinformation on the database DML operations, see Apex Data Manipulation Language (DML) Operationson 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 ofthe email header.All email that is returned, bounced, or received out-of-office replies goes to the user calling themethod.• Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number ofsendEmailmethods in a transaction.• Single email messages sent with the sendEmail method count against the sending organization'sdaily single email limit.When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, andthe userreceives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through theapplication are allowed.• Mass email messages sent with the sendEmail method count against the sending organization's dailymass email limit.When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, andthe user receivesa 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 objectID to anOrgWideEmailAddress object. If setOrgWideEmailAddressId is passed a valid ID, theOrgWideEmailAddress.DisplayName field is used in the email header, instead of the logged-in user'sDisplay

// 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[] {'[email protected]'};String[] ccAddresses = new String[] {'[email protected]'};// 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('[email protected]');

Page 11: 501 Study Notes

// 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 MethodsSingle Email Message MethodsMass Email Message MethodsEmailFileAttachment MethodsSendEmailResult Object MethodsSendEmailError Object Methods

Inbound EmailYou can use Apex to receive and process email and attachments. The email is received by the Apexemail service, and processedby Apex classes that utilize the InboundEmail object.

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

InboundEmail ObjectInboundEmail.Header ObjectInboundEmail.BinaryAttachment ObjectInboundEmail.TextAttachment ObjectInboundEmailResult ObjectInboundEnvelope 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 EmailServiceMessaging.InboundEmailResult result = new Messaging.InboundEmailResult();

StaticResource sr=[Select s.Name, s.ContentType, s.Body From StaticResource s wherename='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 messageresult.success = true;// Return the result for the Apex Email Servicereturn result;

}

Page 12: 501 Study Notes

}

Describe use cases for dynamic Apex.

Dynamic Apex enables developers to create more flexible applications byproviding them with the ability to:

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

Describe use cases for batch ApexA 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 Opportunitieson 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 Webservice 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 beenused in the current context,while the second version contains the word limit and returns the total amount of the resource that isavailable 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 addadditional 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. Theseinclude: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• FINESTLog levels are cumulative. For example, if the lowest level, ERROR is specified, only debug methods

Page 13: 501 Study Notes

with the log level of ERRORare logged. If the next level, WARN, is specified, the debug log contains debug methods specified aseither ERROR or WARN.In the following example, the string MsgTxt is not written to the debug log because the log level isERROR and the debugmethod 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 thatsalesforce.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 toa Force.comAppExchangeApp 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 isexecuted.? 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 fieldshave 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 Executionhttp://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 values3. All before triggers execute4. System validation occurs, such as verifying that all required fields have a non-null value, and running any

user-defined validation rules5. The record is saved to the database, but not yet committed6. All after triggers execute

Page 14: 501 Study Notes

7. Assignment rules execute8. Auto-response rules execute9. Workflow rules execute

10. If there are workflow field updates, the record is updated again11. 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 execute13. All DML operations are committed to the database14. Post-commit logic executes, such as sending email

Additional ConsiderationsPlease note the following when working with triggers:* When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an opportunityand 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 moreinformation, 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 asfollows:

• 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 isspecified and the incoming Stage is different than the trigger Stage, the Forecast Category defaults to theone associated with trigger Stage. If the trigger Stage and incoming Stage are the same, the ForecastCategory 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.

Page 15: 501 Study Notes

To invoke Apex, use one of the following two methods:? Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a resultsimilar to theAPI'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-levelclass.? 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 class4. Optional extensions and/or implementationsUse the following syntax for defining classes:private | public | global[virtual | abstract | with sharing | without sharing | (none)]

Page 16: 501 Study Notes

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 sectionof code. This is thedefault access for inner classes—that is, if you don't specify an access modifier for an inner class, it isconsidered 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. Allclasses that containmethods or variables defined with the webService keyword must be declared as global. If a method,variable or innerclass 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 moreinformation, seeUsing the with sharing or without sharing Keywords on page 90.? The virtual definition modifier declares that this class allows extension and overrides. You cannotoverride a methodwith the override keyword unless the class has been defined as virtual.? The abstract definition modifier declares that this class contains abstract methods, that is, methodsthat only have theirsignature declared and no body defined.Note: Classes defined with either virtual or abstract cannot also be defined as global in DeveloperEditionorganizations. They can be defined as global in sandbox organizations. Only private and public classescan bedefined as either virtual or abstract in Developer Edition organizations. However, a class defined asglobal canextend 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 meansthat Apex does not supportmultiple inheritance. The interface names in the list are separated by commas. For more informationabout interfaces, seeInterfaces 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 tocollections and performingDML operations against these collections.• Minimize the number of SOQL statements by preprocessing records and generating sets, which canbe placed in singleSOQL statement used with the IN clause.

Using Maps and Sets in Bulk TriggersSet and map data structures are critical for successful coding of bulk triggers. Sets can be used toisolate distinct records, whilemaps 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 entryassociated with theOpportunityLineItem records in Trigger.new to a set, ensuring that the set contains only distinctelements. It then queriesthe PricebookEntries for their associated product color, and places the results in a map. Once the mapis created, the triggeriterates through the OpportunityLineItems in Trigger.new and uses the map to assign the appropriatecolor.// 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.

Page 17: 501 Study Notes

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 pricebookentrywhere 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 TriggersUse the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with queryresults. 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 beingprocessed by the trigger.For every quote returned by the query, the related opportunity is retrieved from Trigger.oldMap andprevented from beingdeleted:trigger oppTrigger on Opportunity (before delete) {for (Quote__c q : [select opportunity__c from quote__cwhere opportunity__c in :Trigger.oldMap.keySet()]) {Trigger.oldMap.get(q.opportunity__c).addError('Cannot deleteopportunity with a quote');}}

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

Avoiding Deadlocks1. First locks sObject parent records, then children2. 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 ControllersA Visualforce controller is a set of instructions that specify what happens when a user interacts withthe components specifiedin associated Visualforce markup, such as when a user clicks a button or link. Controllers also provideaccess to the data thatshould 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 customcontroller logic with aclass written in Apex:• A standard controller consists of the same functionality and logic that is used for a standardSalesforce page. For example,if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the

Page 18: 501 Study Notes

same behavior asclicking 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 willdisplay a insufficientprivileges error message.• A custom controller is a class written in Apex that implements all of a page's logic, without leveraginga standard controller.If you use a custom controller, you can define new navigation elements or behaviors, but you mustalso reimplement anyfunctionality that was already provided in a standard controller.Like other Apex classes, custom controllers execute entirely in system mode, in which the object andfield-level permissionsof the current user are ignored. You can specify whether a user can execute methods in a customcontroller based on theuser's profile.• A controller extension is a class written in Apex that adds to or overrides behavior in a standard orcustom controller.Extensions allow you to leverage the functionality of another controller while adding your own customlogic.Because standard controllers execute in user mode, in which the permissions, field-level security, andsharing rules of thecurrent user are enforced, extending a standard controller allows you to build a Visualforce page thatrespects user permissions.Although the extension class executes in system mode, the standard controller executes in user mode.As with customcontrollers, you can specify whether a user can execute methods in a controller extension based on theuser's profile.Note: Although custom controllers and controller extension classes execute in system mode andthereby ignoreprofile-based permissions and field-level security, you can choose whether they respect a user'sorganization-widedefaults, 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 atwww.salesforce.com/us/developer/docs/apexcode/index.htm

In Chapter 9: Visualforce Pages, you experienced the different granularity of various Visualforcecomponents. For instance, a single set of tags can create an entire detail page. But if you wantto change the way a detail page looks beyond the scope of page layouts, you must build theentire Visualforce page using more discrete components.Visualforce controllers give you similar options, but with a difference. You can build a customcontroller with Apex code that replaces all the functionality of a standard controller, and thereare times when this approach may be desirable; however, Visualforce also gives you anotheroption, in the form of controller extensions.A controller extension uses all the functionality in a standard controller.The controller extensionexpands or modifies that functionality by adding new capabilities or replacing standardcapabilities with modified versions of the same actions.With this approach, you do not haveto 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

Metadatathere are a number of reasons why you would want touse a more traditional IDE for your development efforts,as follows:• Your development methodology is not appropriate forthis approach, whether for scale of the change, scale of

Page 19: 501 Study Notes

the development team, or the mission-critical nature ofthe applications in your organization.• Some of your developers are focusing on the proceduralportions of the Force Platform, such as Apex code, andare looking for a development environment designedfor that area of endeavor.• If you are part of a team, it is often easier for each teammember to only interact with isolated portions of theoverall development effort. The Setup menu shows youeverything in your Force.com organization, while yourIDE environment allows you to tailor the componentsof the application that are included in your project.211

The Force.com Metadata API is used to access metadata in your Force.com organization.TheMetadata API is comprised of a transport, a web service API that allows reading setupinformation out of a Force.com organization, and a payload—the organization setup informationitself. The API provides two modes that control how the configuration information isconveyed—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 usingthe Setup menu.When you request metadata for a Force.com component from the IDE, theIDE sends that request through the Metadata API to the Force.com server. The server, inresponse, creates an XML file from the stored metadata on the fly.

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

Describe best practices for managing multi-team and multi-project development initiativeswith Force.com and describe how to use these best practices.A developer's work shouldbe 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 throughan extended lifecycle.

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

Given a scenario, determine whether to use package or metadata deploymentThe scripting capabilities of the Migration Tool mean that this option is well-suited torepeatedly perform the same tasks that you would perform with the Deploy to Server choicefrom within the IDE. This repeatability makes the use of this approach very appropriate whenyou are migrating Force Platform components to more than one internal target, since you willstill 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 fromone organizationto another. But what about the scenario where you want to deploy an application from oneorganization to many other organizations, which may be outside your company?

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

Describe how to use the Force.com Migration Tool.

Page 20: 501 Study Notes

The general procedure you will follow when using the Force.com Migration Tool to copy metadata fromone Salesforce organization toanother is:1. Enter credentials and connection information for source Salesforce organization in build.properties2. Create retrieve targets in build.xml3. Construct a project manifest in package.xml4. Run the Force.com Migration Tool to retrieve metadata files from Salesforce5. Enter credentials and connection information for destination Salesforce organization inbuild.properties6. 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.complatform.

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

sandbox org:however, your project is to extend or further customize your existing environment, or tobuild a new application that intersects your existing setup in significant ways, you'll probablywant 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 havepurchased, 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 thedata. This sandbox will contain the definition of all custom fields, objects, workflows, Apexcode, Visualforce, and so on, but won't contain any of the records your production usershave entered. You can load data into a configuration only sandbox, but there is a limit asto the number of records which can be held in this type of sandbox.The Configuration-only Sandbox isvery 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 storagelimit is smaller—about 5000 records.The Developer Sandbox is usually the best environment for projectdevelopment. DeveloperSandboxes are intended to be readily available, so everyone on your team can have one ortwo to themselves.

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

Unlike page templates, which also enable developers to reuse markup, custom components providemore power and flexibilitybecause:• Custom components allow developers to define attributes that can be passed in to each component.The value of an attributecan then change the way the markup is displayed on the final page, and the controller-based logic thatexecutes for thatinstance of the component. This behavior differs from that of templates, which do not have a way ofpassing informationfrom the page that uses a template to the template's definition itself.• Custom component descriptions are displayed in the application's component reference dialogalongside standard componentdescriptions.Template descriptions, on the other hand, can only be referenced through the Setup areaof Salesforce becausethey are defined as pages.

Describe how to handle client-side behavior through the use of either standard components

Page 21: 501 Study Notes

orcustom 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 implementedpreviously by thecommand 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 suchas "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 eventoccurs.

Using JavaScript in Visualforce pages gives you access to a wide range of existingJavaScript functionality, including JavaScript libraries, and another way tocustomize the functionality of your pages.By including JavaScript in a page, you are introducing thepossibility of cross-browser and maintenance issues that you do not havewhen using Visualforce. Before writing any JavaScript, you should besure that there is not an existing Visualforce component that can solveyour 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 yourVisualforce 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 keywordtry, the execution drops out of that block.There are different types of Force Platform exceptions so you can have more than one catchblock, with no more than one catch block for a particular type of exception. You can alsodefine your own exception types.The code_block for a particular exception type is executed when an exception of that typeis thrown. You can also specify the general exception type of Exception, catching anyexceptions not intercepted by previous catch statements–because of this, a catch statementthat 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 finallystatement is run. The finally statement is not required.

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

Page 22: 501 Study Notes

which accesses one or more Force Platform objects.

The model component of Visualforce is typically the data model, which you have been workingwith throughout the previous portion of this book. The view component of Visualforce areVisualforce pages, the subject of the rest of this chapter, and the controller component ishandled by Visualforce components, discussed in this chapter and Chapter 12: ExtendedVisualforce Components and ControllersTip: You can also use Apex classes as the model component for Visualforce,

The controller portion of Visualforce comes in twovarieties. The Force Platform automatically creates a standard controller for every object inyour Force Platform database. These standard controllers provide the basic functionalityembedded 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 developmentDevelopers 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.TheVisualforceeditor pane also includes auto-completion and syntax highlighting.Visualforce also supports "quick fixes" that allow developers to create supporting components on thefly.For example, a developer can define a new Visualforce page simply by logging in to Salesforce andthenentering the name of the new page in a URL. Much like a wiki, if the page does not yet exist, theplatformcreates it for you.Integration with other Web-based user interface technologiesBecause Visualforce markup is ultimately rendered into HTML, designers can use Visualforce tagsalongside standard HTML, JavaScript, Flash, or any other code that can execute within an HTML pageon the platform, including Force.com platform merge fields and expressions.Model-View-Controller (MVC) style developmentVisualforce conforms to the Model-View-Controller (MVC) development pattern by providing a cleardivision between the view of an application (the user interface, defined by Visualforce markup), andthecontroller that determines how the application works (the business logic, defined by a Visualforcecontrollerwritten in Apex).With this architecture, designers and developers can easily split up the work that goeswith building a new application—designers can focus on the look and feel of the user interface, whiledevelopers can work on the business logic that drives the app.Concise syntaxVisualforce pages can implement the same functionality as s-controls but with approximately 90%fewerlines of code.Data-driven defaultsVisualforce components are rendered intelligently by the platform. For example, rather than forcingpagedesigners to use different component tags for different types of editable fields (such as emailaddresses orcalendar dates), designers can simply use a generic <apex:inputField> tag for all fields.The Visualforcerenderer displays the appropriate edit interface for each field.Hosted platformVisualforce pages are compiled and rendered entirely by the Force.com platform. Because they are sotightly integrated, they display the same performance as standard Salesforce pages, regardless of theamountof data being displayed or edited.Automatically upgradeableVisualforce pages do not need to be rewritten when other parts of the Force.com platform areupgraded.Because the pages are stored as metadata, they are automatically upgraded with the rest of thesystem.

Page 23: 501 Study Notes

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 pointsin 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 arereferenced 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 customobject record, you needto associate your page with a controller. Controllers provide pages with the data and business logicthat make your applicationrun, including the logic that specifies how to access a particular object's records.While you can define acustom controller forany 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 URLthat specifies the IDof the record

Controller MethodsVisualforce markup can use the following types of controller extension and custom controller methods• Action• Getter• SetterAction MethodsAction methods perform logic or navigation when a page event occurs, such as when a user clicks abutton, or hovers over anarea of the page. Action methods can be called from page markup by using {! } notation in the actionparameter of one ofthe 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 savemethod is called by theaction parameter of the <apex:commandButton> tag. Other examples of action methods are discussedin Defining ActionMethods on page 35.Getter MethodsGetter methods return values from a controller. Every value that is calculated by a controller anddisplayed in a page musthave a corresponding getter method, including any Boolean variables. For example, in the sample pagein Building a CustomController on page 63, the controller includes a getAccount method. This method allows the pagemarkup to reference theaccount 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

Page 24: 501 Study Notes

intoVisualforce pages.Extending Salesforce StylesYou can use the <apex:stylesheet> tag to add additional styles and style classes to page components.This way you canextend the Salesforce styles with your own.

Static resources allow you to upload content that you can reference in a Visualforce page, includingarchives (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 variableinstead of hard-codingdocument IDs.

The way you reference a static resource in Visualforce markup depends on whether you want toreference 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 thename you specified when you uploaded the resource. For example:<apex:image url="{!$Resource.TestImage}" width="50" height="50" />or<scripttype="text/javascript" src="{!$Resource.MyJavascriptFile}"/>• To reference a file in an archive, use the URLFOR function. Specify the static resource name that youprovided when youuploaded the archive with the first parameter, and the path to the desired file within the archive withthe second. Forexample:<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50"height="50" />or<scripttype="text/javascript"src="{!URLFOR($Resource.LibraryJS, '/base/subdir/file.js')}"/>

Lifecycle of a visual force pagePage request -> application server ->Metadata repository ->compiled page definition ->applicationserver(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 orbutton. The page calls theconstructor method for the associated controller and any controller extensions, thereby instantiatingthe controller objects.The page then executes, making calls to the controller objects as necessary to determine what data todisplay. The resultingHTML is then sent to the browser. Meanwhile, all of the information necessary to maintain the state ofthe database betweenrequests is saved as the view state. As the user interacts with the page, the page contacts thecontroller objects as required toexecute 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 queryparameters that can then beused 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

Page 25: 501 Study Notes

objects that are automatically associated with Force Platform objects or that interact withfunctions implemented on the Force Platform. Another group of tags handles interactionsbetween the page and the Force Platform server without refetching the page, similar to theway that AJAX (asynchronous Java script and XML) operates.

You can also see your first example of Visualforce tags, with the <apex:page> start and endtags. Any Visualforce page must be surrounded by these page tags.The apex: portion of a Visualforce tag is actually the namespace for the component referencedby the tag. A namespace is a way to qualify the name of a component, insuring that theVisualforce 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 messagingcomponents, 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 ofVisualforce specific tags.

Describe the benefits, functions, and features of Visualforce and how it conforms to themodel-view-controller patternThe Visualforce technology is an implementation of the model-view-controller architecturepattern, 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 isthe 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-controllerarchitecture, is implemented with Visualforce pages, which are the focus of this chapter. Youcreate Visualforce pages with both standard HTML and a set of special tags that tap into thepower of the Force Platform model.Visualforce tags cover two basic areas of functionality. One group of tags creates user interfaceobjects that are automatically associated with Force Platform objects or that interact withfunctions implemented on the Force Platform. Another group of tags handles interactionsbetween the page and the Force Platform server without refetching the page, similar to theway 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 pointsin your application:From a custom tabAs an override for a standard tab, replacing a normal display for an objectAs an override for standard or custom buttons or linksEmbedded in a detail page layout.

Visualforce technology can be used to implement both the view and the controller portion ofthe model-view-controller architecture.The controller portion of Visualforce comes in twovarieties.The Force Platform automatically creates a standard controller for every object inyour Force Platform database.These standard controllers provide the basic functionalityembedded 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 yourVisualforce 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 Platformobjects.

What is a Visualforce Page?Developers can use Visualforce to create a Visualforce page defnition. A page defnition consists of twoprimary elements:• Visualforce markup• A Visualforce controllerVisualforce MarkupVisualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled codeembedded within a single<apex:page> tag.The markup defnes the user interface components that should be included on thepage, and the way theyshould appear.

Page 26: 501 Study Notes

Visualforce ControllersA Visualforce controller is a set of instructions that specify what happens when a user interacts withthe components specifedin associated Visualforce markup, such as when a user clicks a button or link. Controllers also provideaccess to the data thatshould 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 customcontroller logic with aclass written in Apex:• A standard controller consists of the same functionality and logic that is used for a standardSalesforce.com page. Forexample, if you use the standard Accounts controller, clicking a Save button in a Visualforce pageresults in the samebehavior 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 willdisplay a insuffcientprivileges error message. You can avoid this by checking the user's accessibility for an object anddisplaying componentsappropriately.• A standard list controller enables you to create Visualforce pages that can display or act on a set ofrecords. Examples ofexisting Salesforce.com pages that work with a set of records include list pages, related lists, and massaction pages.• A custom controller is a class written in Apex that implements all of a page's logic, without leveraginga standard controller.If you use a custom controller, you can defne new navigation elements or behaviors, but you must alsoreimplement anyfunctionality that was already provided in a standard controller.Like other Apex classes, custom controllers execute entirely in system mode, in which the object andfeld-level permissionsof the current user are ignored. You can specify whether a user can execute methods in a customcontroller based on theuser's profle.• A controller extension is a class written in Apex that adds to or overrides behavior in a standard orcustom controller.Extensions allow you to leverage the functionality of another controller while adding your own customlogic.Because standard controllers execute in user mode, in which the permissions, feld-level security, andsharing rules of thecurrent user are enforced, extending a standard controller allows you to build a Visualforce page thatrespects user permissions.Although the extension class executes in system mode, the standard controller executes in user mode.As with customcontrollers, you can specify whether a user can execute methods in a controller extension based on theuser's profle.

Describe how to incorporate Visualforce pages into Force.com applicationsDevelopers 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}

Page 27: 501 Study Notes

• To bring an account record into the current context, you must add a query parameter to thepage 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 VisualforceVisualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled codeembedded within a single<apex:page> tag.The markup defnes the user interface components that should be included on thepage, and the way theyshould appear.

Describe best practices for incorporating static resources, stylesheets, and other contentinto Visualforce pagesTo reference a stand-alone fle, use $Resource.<resource_name> as a merge feld, where<resource_name> is thename 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 youprovided when youuploaded the archive with the frst parameter, and the path to the desired fle within the archive withthe second. Forexample:<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 ingetImageName.

Using Salesforce.com Styles

You can specify the tab style that should be used to style acomponent 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 theassociated object'sstandard tab in Salesforce.com. It also allows you to access the methods and records associated withthe associated object.• When you use a custom controller, the tabStyle attribute of an <apex:page> tag allows you to mimicthe look andfeel of the associated Salesforce.com page. If you only want portions of the page to be similar to aSalesforce.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 everytab conforms to theSalesforce.com look and feel.When you specify true for the header attribute of the <apex:page> tag(or leave it blank, as

Page 28: 501 Study Notes

the default is true) these stylesheets are automatically included. You can reference these stylesheets tofurther customize thecomponents on your page.This is relevant when you use a custom controller and you do not set thetabStyle attribute onthe page.The following stylesheets contain the style classes that you can reference.They are located in the/dCSS/ directory of yoursalesforce.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 eachimplementation, use the<apex:composition> component.This templating method is best for situations when you want tomaintain an overallstructure to a page, but need the content of individual pages to be different, such as a website fornews articles wheredifferent 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 pagethat imports a templateusing <apex:composition> must use <apex:define> to specify the content of each <apex:insert>section of thetemplate.

Describe how to handle client-side behavior through the use of either standard componentsor custom JavaScriptPartial 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 thebutton or link, onlythe identifed component and all of its child components are refreshed

apex:actionFunctionapex:actionSupportapex:actionStatusapex: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>

Page 29: 501 Study Notes

It works fine. If you select something from the picklist and click the button, you'll see the industry getupdated and no message about the first field being required.

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

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

Describe and incorporate proper error-handling techniquesapex:messageapex:messages

try{...

}catch(Exception ex){

ApexPages.addMessages(ex);}

Describe how to create a custom component and the benefits of custom components versusother techniques for code reuseUnlike page templates, which also enable developers to reuse markup, custom components providemore power and fexibilitybecause:• Custom components allow developers to defne attributes that can be passed in to eachcomponent.The value of an attributecan then change the way the markup is displayed on the fnal page, and the controller-based logic thatexecutes for thatinstance of the component.This behavior differs from that of templates, which do not have a way ofpassing informationfrom the page that uses a template to the template's defnition itself.• Custom component descriptions are displayed in the application's component reference dialogalongside standard componentdescriptions.Template descriptions, on the other hand, can only be referenced through the Setup areaof Salesforce.combecause they are defned as pages.

The c: namespace refers to any component in your org that has not been assignedto 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 forprint.• Standard components which are not easily formatted for print or contain form elements like inputs,buttons, and anycomponent that requires JavaScript to be formatted, should not be used.This includes but is not limitedto any componentthat 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 supportsyour needs. Forexample:<apex:page renderas="pdf"><html><head>

Page 30: 501 Study Notes

<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 extensionsStandard controllers can provide all the functionality you need for a Visualforce page because theyinclude the same logic thats used for a standard page. For example, if you use the standard Accounts controller, clicking a Savebutton in a Visualforcepage 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 anapplication, use callouts or Webservices, or if you need fner control for how information is accessed for your page, you can write acustom controller or acontroller extension using Apex.

A custom controller is an Apex class that implements all of the logic for a page without leveraging astandard controller. Usecustom controllers when you want your Visualforce page to run entirely in system mode, which doesnot enforce the profle-basedpermissions and feld-level security of the current user.A controller extension is an Apex class that extends the functionality of a standard or customcontroller. Use controller extensionswhen:• You want to leverage the built-in functionality of a standard controller but override one or moreactions, 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 extensionclass executes insystem mode, if a controller extension extends a standard controller, the logic from the standardcontroller does not executein system mode. Instead, it executes in user mode, in which the profle-based permissions, feld-levelsecurity, and sharingrules 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 orupdate in the method to create an object.

• You can't use data manipulation language (DML) operations in a constructor method in acontroller.

• You can't use the @future annotation in a “getxxx” or “setxxx” method in a controller, or in theconstructor for a controller.

• Primitive Apex data types such as String or Integer are passed by value to the component'scontroller.

• Non-primitive Apex data types such as lists and sObjects are passed by reference tocomponent's controller.This means that if component's controller changes the name of anaccount, the changes are available in page's controller.

Describe the request lifecycle of a Visualforce pageOrder of Execution in a Visualforce PageWhen a user views a Visualforce page, instances of the controller, extensions, and componentsassociated with the page arecreated by the server.The order in which these elements are executed can affect how the page isdisplayed to the user.

Page 31: 501 Study Notes

To fully understand the order of execution of elements on a Visualforce page, you must frst understandthe page's lifecycle–thatis, how the page is created and destroyed during the course of a user session.The lifecycle of a page isdetermined not just bythe content of the page, but also by how the page was requested.There are two types of Visualforcepage requests:• A get request is an initial request for a page either made when a user enters an URL or when a linkor button is clicked thattakes the user to a new page.• A postback request is made when user interaction requires a page update, such as when a user clickson a Save button andtriggers 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 arecalled, instantiating thecontroller objects.2. If the page contains any custom components, they are created and the constructor methods on anyassociated customcontrollers or controller extensions are executed. If attributes are set on the custom component usingexpressions, theexpressions are evaluated after the constructors are evaluated.3. The page then executes any assignTo attributes on any custom components on the page. After theassignTo methodsare executed, expressions are evaluated, the action attribute on the <apex:page> component isevaluated, and all othermethod calls, such as getting or setting a property value, are made4. If the page contains an <apex:form> component, all of the information necessary to maintain thestate of the databasebetween page requests is saved as an encrypted view state.The view state is updated whenever thepage is updated.5. The resulting HTML is sent to the browser. If there are any client-side technologies on the page,such as JavaScript, thebrowser executes them.As the user interacts with the page, the page contacts the controller objects as required to executeaction, getter, and settermethods.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 propersubset of controllerextensions, a postback request is made.When a postback request is made, the view state ismaintained.If the user interaction requires a page update, such as when the user clicks a Save button that triggersa save action, a postbackrequest is made. For more information on postback requests, see Order of Execution for VisualforcePage Postback Requestson 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 clickson a Save button and triggersa save action.The following diagram shows how a Visualforce page interacts with a controller extensionor a custom controllerclass during a postback request:

Page 32: 501 Study Notes

1. During a postback request, the view state is decoded and used as the basis for updating the valueson the page.Note: A component with the immediate attribute set to true bypasses this phase of the request. Inother 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 andany 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 methodsupdates a property and the update is not valid due to validation rules or an incorrect data type, thedata is not updated andthe page redisplays with the appropriate error messages.3. The action that triggered the postback request is executed. If that action completes successfully, thedata is updated. If thepostback 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 isonly 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 samecontroller and a proper subsetof controller extensions of the originating page, a postback request is executed for that page.Otherwise, a get request is executedfor the page. If the postback request contains an <apex:form> component, only the ID queryparameter on a postback requestis returned.Tip: You can use the setRedirect attribute on a pageReference to control whether a postback or getrequest isexecuted. If setRedirect is set to true, a get request is executed. Setting it to false does not ignore therestrictionthat a postback request will be executed if and only if the target uses the same controller and a propersubset ofextensions. If setRedirect is set to false, and the target does not meet those requirements, a getrequest will bemade.

Describe viewstate and the stateful programming model of Visualforce

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

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

Some Apex objects are automatically considered transient, that is, their value does not get saved aspart of the page's viewstate.These objects include the following:• Savepoints• PageReferences• XmlStream Classes• Collections automatically marked as transient only if the type of object that they hold is automaticallymarked 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

Page 33: 501 Study Notes

anonymous blocks

The System Log console is a separate window that can be used for debugging code snippets or trackingcode execution duringa transaction. Access the System Log console from the Salesforce.com user interface by clickingSystem Log in the upperright of any page.

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

Unit test methods take no arguments, commitno data to the database, send no emails, and are fagged with the testMethod keyword in the methoddefnition.

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

List and describe the contents and use of the System Log

DatabaseWorkflowValidationCalloutApex CodeApex Profiling

You can specify the following log levels.The levels are listed from lowest to highest. Specifc events arelogged based on thecombination of category and levels. Most events start being logged at the INFO level.The level iscumulative, that is, if youselect 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 moreevents.• ERROR• WARN• INFO• DEBUG• FINE• FINER• FINESTDescribe how to create and run unit tests as well as techniques for achieving 100% testcoverage.• Cover as many lines of code as possibleImportant:

◊ You must have at least 75% of your Apex scripts covered by unit tests to deploy yourscripts to productionenvironments. In addition, all triggers should have some test coverage.◊ Salesforce recommends that you have 100% of your scripts covered by unit tests, wherepossible.◊ 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 caughtin 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 yourorganization limit of

Page 34: 501 Study Notes

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 orderRecord IDs are not created in ascending order unless you insert multiple records with the samerequest. For example, ifyou create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID ofaccount B may or maynot 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 aparticular 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 madeabout the data, theexpected 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 fortesting 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 MBfor all Apexscripts. Individual methods defined with the isTest annotation do count against your organizationlimits.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 theSalesforce 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 voidreturn.Test methods cannot accept any arguments, and no data changes performed in a testmethod are committed to the Force Platform database.In a case where a method has multiple possible branches, due to logical conditions, create testmethods 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 theyare equal• System.assertNotEquals(x, y) compares the value of x and y and returns true if theyare not equal .

Note: Test methods cannot be used to test Web service callouts.Web service callouts areasynchronous, while unittests 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

Page 35: 501 Study Notes

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[] {'[email protected]','[email protected]'};mail.setToAddresses(toAddresses);

mail.setSubject('My Subject');

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

// Send the emailMessaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

}

public static testMethod void testSendMail() {sendMail('This is my email message');

}

}

@IsTestprivate class EmailDemoReceiveHandlerTests {

// Create a new email and envelope objectMessaging.InboundEmail email = new Messaging.InboundEmail();Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

// Set up your data if you need to

// Create the email bodyemail.plainTextBody = 'This should become a note';email.fromAddress ='[email protected]';String contactEmail = '[email protected]';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);

Page 36: 501 Study Notes

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 runAsThe following items use the permissions granted by the user specified with runAs running as a specificuser:• 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 invocationNote: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, donot 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 atestMethod• 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 ofprimitive 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 eithergetMethodName orsetMethodName methods, nor in the constructor.Remember that any method using the future annotation requires special consideration, because themethod does notnecessarily 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. Norcan you call atrigger from an annotated method that calls another annotated method.The getContent and getContentAsPDF PageReference methods cannot be used in methods with thefuture annotation.

Virtual and abstractThe virtual defnition modifer declares that this class allows extension and overrides. You cannotoverride a methodwith 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 thatonly have theirsignature declared and no body defned.

// Exception inner classpublic virtual class MyException extends Exception {// Exception class member variablepublic Double d;// Exception class constructorMyException(Double d) {this.d = d;}// Exception class method, marked as protectedprotected void doIt() {}}// Exception classes can be abstract and implement interfacespublic abstract class MySecondException extends Exception implements MyInterface {}

web servicesThe successfully generated Apex class includes stub and type classes for calling the third-party Web

Page 37: 501 Study Notes

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 executionmay 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 willnot 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 processingtake place in a separate class.

• You can only have ten classes scheduled at one time. You can evaluate your current count byviewing the Scheduled Jobs

page in Salesforce.com or programmatically using the Force.com Web services API to querythe CronTrigger object.

• You can't use the getContent and getContentAsPDF PageReference methods in scheduledApex.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 areunavailable in Visualforce email templates.

• The attributes recipientType and relatedToType act as controllers for the email template.With themyou can accessthe same merge felds that are available to other standard controllers.The recipientType attributerepresents therecipient 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 supportedlanguage keys, forexample, “en-US”).The language attribute accepts merge felds from the email template's recipientTypeandrelatedToType attributes. You create custom language felds for use in the merge felds. The TranslationWorkbench

Page 38: 501 Study Notes
Page 39: 501 Study Notes
Page 40: 501 Study Notes
Page 41: 501 Study Notes
Page 42: 501 Study Notes