Friday 24 May 2013


                      Introduction to Batch Apex

Prior to the availability of Batch Apex, the only options for processing data exceeding the
governor limits of triggers and controllers were tricky workarounds to shift work off of
the platform. For example, you might have hundreds of thousands of records spanning
multiple Lookup relationships to be summarized, de-duplicated, cleansed, or otherwise
modified en masse algorithmically.You could use the Web Services API to interact with
the Force.com data from outside of Force.com itself, or JavaScript to process batches of
data inside the web browser.These approaches are usually slow and brittle, requiring
lots of code and exposing you to data quality problems over time due to gaps in error
handling and recovery. Batch Apex allows you to keep the large, data-intensive processing
tasks within the platform, taking advantage of its close proximity to the data and transactional
integrity to create secure, reliable processes without the limits of normal, interactive
Apex code.This section introduces you to concepts and guidelines for using Batch Apex
to prepare you for hands-on work in the following section

Batch Apex Concepts

Batch Apex is an execution framework that splits a large dataset into subsets and provides
them to ordinary Apex programs that you develop, which continue to operate within
their usual governor limits.This means with some minor rework to make your code
operate as Batch Apex, you can process data volumes that would otherwise be prohibited
within the platform. By helping Salesforce break up your processing task, you are permitted
to run it within its platform.

A few key concepts in Batch Apex are used are:

>>Scope: The scope is the set of records that a Batch Apex process operates on. It can
consist of 1 record or up to 50 million records. Scope is usually expressed as a
SOQL statement, which is contained in a Query Locator, a system object that is
blessedly exempt from the normal governor limits on SOQL. If your scope is too
complex to be specified in a single SOQL statement, then writing Apex code to
generate the scope programmatically is also possible. Unfortunately, using Apex
code dramatically reduces the number of records that can be processed, because it is
subject to the standard governor limit on records returned by a SOQL statement.

>> Batch job: A batch job is a Batch Apex program that has been submitted for execution.
 It is the runtime manifestation of your code, running asynchronously within

the Force.com platform. Because batch jobs run in the background and can take
many hours to complete their work, Salesforce provides a user interface for listing
batch jobs and their statuses, and to allow individual jobs to be canceled.This job
information is also available as a standard object in the database.Although the batch
job is not the atomic unit of work within Batch Apex, it is the only platform-provided
level at which you have control over a batch process.

>>Transaction: Each batch job consists of transactions, which are the governor limitfriendly
units of work you’re familiar with from triggers and Visualforce controllers.
By default, a transaction is up to 200 records, but you can adjust this downward in
code.When a batch job starts, the scope is split into a series of transactions. Each
transaction is then processed by your Apex code and committed to the database
independently.Although the same block of your code is being called upon to
process potentially thousands of transactions, the transactions themselves are normally
stateless. None of the variables within it are saved between invocations unless
you explicitly designate your Batch Apex code as stateful when it is developed.
Salesforce doesn’t provide information on whether your transactions are run in parallel
or serially, nor how they are ordered. Observationally, transactions seem to run
serially, in order based on scope.





                                Batch Processing

Two ways you can process database records within the Force.com platform:
triggers and Visualforce controllers. Each has its own set of platform-imposed limitations,
such as how many records can be created at one time.As you accumulate tens of
thousands of records or more in your database, you might need to process more of records
than permitted by the governor limits applying to triggers and controllers.

Although Salesforce has simplified and incrementally relaxed governor limits in recent
Force.com releases, triggers and Visualforce controllers are fundamentally not suited to
processing large amounts of data in a multitenant environment.They are driven by user
interaction, and must be limited to provide good performance to all users.The Force.com
platform carefully controls its resources to maintain high performance for all, so resource
intensive tasks such as processing millions of records must be planned and executed over
time, balanced with the demands of other customers.

Batch processing makes this possible, and Batch Apex is the Force.com feature that
enables batch processing on the platform.With Batch Apex, data-intensive tasks are taken
offline, detached from user interactions, the exact timing of their execution determined
by Salesforce itself. In return for relinquishing some control, you the developer receive
the ability to process orders of magnitude more records than you can in triggers and
controllers.

 You are going to  learn how to use Batch Apex to create, update, and delete millions
of records at a time. It is divided into five sections:

  •  Introduction to Batch Apex: Learn the concepts and terminology of Batch Apex, what it can do, and when you should and should not use it.


  •  Getting Started with Batch Apex:Walk through a simple example of Batch Apex. Develop the code, run it, and monitor its execution.


  • Testing Batch Apex: Like any other Apex code, proper test coverage is required.Learn how to kick off Batch Apex jobs within test code.


  •  Scheduling Batch Apex: Although Salesforce has the final say on when BatchApex is run, you can schedule jobs to run using a built-in scheduler. Learn how to use the scheduling user interface and achieve finer-grained control in Apex code.

Thursday 23 May 2013


               SOQL with Parent-to-Child Relationship




The second form of relationship query is the parent-to-child query. Listing 5-30 provides
an example.The parent object is Resource, and the child is Timecard.The query
selects from every Resource its Id, Name, and a list of hours from its Timecards in the current
month.

Listing 5-30 SOQL with Parent-to-Child Relationship



SELECT Id, Name,(SELECT Total_Hours__c FROM Timecards__r WHERE Week_Ending__c = THIS_MONTH) FROM Resource__c

Listing 5-29 SOQL with Child-to-Parent Relationship

SELECT Name, Contact__r.MailingCity, Contact__r.CreatedBy.Name
FROM Resource__c WHERE Contact__r.MailingState = 'IL'

Sorting Query Results

Results of a query can be sorted by up to 32 fields in ascending (ASC, the default) or
descending (DESC) order. Sorting is not case-sensitive, and nulls appear first unless otherwise
specified (NULLS LAST). Multi-select picklists, long text areas, and reference type
fields cannot be used as sort fields.The SOQL query in Listing 5-28 returns records first
in ascending order by Type, and then in descending order by LastModifiedDate.

Listing 5-28 SOQL Statement with Sort Fields

SELECT Name, Type, AnnualRevenue FROM Account ORDER BY Type, LastModifiedDate DESC


SOQL Statement with Record Limit



SELECT Name, Type
FROM Account
WHERE LastModifiedDate = TODAY
LIMIT 10

SOQL Statement with Filter Conditions


SELECT Name
FROM Account
WHERE AnnualRevenue > 100000000
AND Type = 'Customer - Direct'
AND LastModifiedDate = THIS_YEAR



Notice the way literal values are specified.Apostrophes must be used around String literals
but never with other data types. THIS_YEAR is a built-in relative time function.The
values of relative time functions vary based on when the query is executed. Other relative
time functions are YESTERDAY, TODAY, TOMORROW, LAST_WEEK, THIS_WEEK, NEXT_WEEK, and so forth.

Delete and Undelete

Delete and Undelete statements move up to 200 records of the same object type to and
from the Recycle Bin, respectively. Listing 5-36 shows an example of the Delete statement.
A new Resource record named Terry is added and then deleted.

Listing 5-36 Deleting Records

Resource__c terry = new Resource__c(Name = 'Terry Bull');
insert terry;
delete terry;


Listing 5-37 builds on Listing 5-36 to undelete the Terry record. Concatenate the listings
in the Execute Anonymous view to test.The database is queried to prove the existence
of the undeleted record.Try running the code a second time with the undelete
statement commented out to see that it is working as intended.


Listing 5-37 Undeleting Records
undelete terry;
Resource__c terry2 = [ SELECT Id, Name
FROM Resource__c WHERE Name LIKE 'Terry%' LIMIT 1 ];
System.debug(terry2.Name + ' exists');
delete terry;

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

String str_date="2011-03-10T11:54:30.207Z";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
date = (Date)formatter.parse(str_date);
System.out.println("output: " +date );

Wednesday 15 May 2013


Upsert

Upsert combines the behavior of the Insert and Update operations on up to 200 records
of the same object type. First, it attempts to locate a matching record using its unique
identifier or external identifier. If one is found, the statement acts as an Update. If not, it
behaves as an Insert.



The syntax of the Upsert statement is identical to Update and Insert, but adds a second,
optional argument for specifying an external identifier. If an external identifier is not
provided, the record’s unique identifier is used.The code in Listing 5-35 upserts a record
in the Resource object using the field Resource_ID__c as an external identifier. If a
Resource record with a Resource_ID__c value of 1001 exists, it is updated. If not, it is
created.

Listing 5-35 Upserting a Record
Resource__c r = new Resource__c(Resource_ID__c = 1001, Name = 'Terry Bull');
upsert r Resource_ID__c;


Update

Update saves up to 200 existing records of a single object type. Existing records are identified
by unique identifier (Id). Listing 5-34 illustrates the usage of the Update statement by
creating a Resource record for Doug and updating it. Refresh the Resources tab in the
native user interface to see the new record.

Listing 5-34 Updating Records
Resource__c doug = new Resource__c(Name = 'Doug Hole');
insert doug;
doug.Hourly_Cost_Rate__c = 100;
doug.Home_Office__c = 'London';
update doug;

Insert

The Insert statement adds up to 200 records of a single object type to the database.
When all records succeed, they contain their new unique identifiers. If any record fails, a
DmlException is raised and the database is returned to its state prior to the Insert statement.
For example, the code in Listing 5-33 inserts a Contact record and uses it as the
parent of a new Resource record.

Listing 5-33 Inserting a Record

try {
Contact c = new Contact(FirstName = 'Justin', LastName = 'Case');
insert c;
Resource__c r = new Resource__c(
Contact__c = c.Id, Hourly_Cost_Rate__c = 75, Region__c = 'West');
insert r;
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, e.getMessage());
}


Persisting Database Records

Changes to database records in Force.com are saved using Data Manipulation Language
(DML) operations. DML operations allow you to modify records one at a time, or more
efficiently in batches of multiple records.The five major DML operation types are listed
next. Each is discussed in more detail later in this subsection.

  •  Insert: Creates new records.
  •  Update: Updates the values in existing records, identified by Force.com unique identifier (Id) field or a custom field designated as an external identifier.
  •  Upsert: If records with the same unique identifier or external identifier exist, this updates   their values. Otherwise, it inserts them.
  • Delete: Moves records into the Recycle Bin.
  •  Undelete: Restores records from the Recycle Bin.

DML operations can be included in Apex code in one of two ways: DML statements and
database methods. Beyond the syntax, they differ in how errors are handled. If any one
record in a DML statement fails, all records fail and are rolled back. Database methods
allow for partial success.

Note

Usage of DML in Apex is subject to governor limits. For example, you are limited to a total of
150 DML operations. The cumulative maximum number of records modified by all DML operations
is 10,000.


Using SOQL in Apex

Like database objects,SOQL queries are an integrated part of the Apex language.They are
developed in-line with your code and verified at compile time against your database schema.
Listing 5-31 is an example of a SOQL query used in Apex. It retrieves a list of Project
records for this year and loops over them, summing their billable hours invoiced in the
variable totalHours. Note the usage of the variable named statuses directly in the
SOQL query, preceded by a colon.This is known as a bind variable. Bind variables can
appear on the right side of a WHERE clause, as the value of an IN or NOT IN clause, and in
the LIMIT clause.

Listing 5-31 SOQL Query in Apex

Decimal totalHours = 0;
List<String> statuses = new String[] { 'Green', 'Yellow' };
List<Proj__c> projects = [ SELECT Total_Billable_Hours_Invoiced__c FROM Proj__c WHERE Start_Date__c = THIS_YEAR and Status__c IN :statuses ];

for (Proj__c project : projects) {
totalHours += project.Total_Billable_Hours_Invoiced__c;
}

This code relies on a List to store the results of the SOQL query.This means the entire
SOQL query result must fit within the heap size available to the program.A better syntax
for looping over SOQL records is a variation of the List/Set Iteration For Loop called a
SOQL For Loop.The code in Listing 5-32 is a rewrite of Listing 5-31 using the SOQL
For Loop.This allows it to run when the Project object contains up to 50,000 records for
this year without consuming 50,000 records worth of heap space at one time.

Listing 5-32 SOQL Query in Apex Using SOQL For Loop
Decimal totalHours = 0;
for (Proj__c project : [ SELECT Total_Billable_Hours_Invoiced__c
FROM Proj__c
WHERE Start_Date__c = THIS_YEAR ]) {
totalHours += project.Total_Billable_Hours_Invoiced__c;
}

An additional form of the SOQL For Loop is designed for use with Data Manipulation
Language (DML). Consider how the code in Listing 5-32 could be adapted to modify
Project records returned from the SOQL query rather than simply summing them.With
the existing code, one Project record would be modified for each loop iteration, an inefficient
approach and a quick way to run afoul of the governor limits. But if you change the
type of variable in the For loop to a list of Project records, Force.com provides up to 200
records per loop iteration.This allows you to modify a whole list of records in a single
operation.

Note

Looping through a list of records to calculate the sum of a field is provided as an example of
using SOQL with Apex. It is not an optimal way to perform calculations on groups of records
in the database. 

Any valid SOQL statement can be executed in Apex code, including relationship
queries.The result of a child-to-parent query is returned in a List of objects whose types
match the child object.Where fields from a parent object are included in the query, they
are available as nested variables in Apex code. For example, running the query in Listing
5-29 within a block of Apex code returns a List<Resource__c>. If this List is assigned to
a variable named resources, the first Resource record’s mailing city is accessible by
resources[0].Contact__r.MailingCity.

Parent-to-child queries are returned in a List of objects, their type matching the parent
object. Each record of the parent object includes a nested List of child objects. Using
Listing 5-30 as an example, if results contains the List<Resource__c> returned by the
query, results[0].Timecards__r[0].Total_Hours__c accesses a field in the first
Resource’s first Timecard child record.

Note

Usage of SOQL in Apex is subject to governor limits. For example, you are limited to a total
of 100 SOQL queries, or 300 including parent-to-child queries. The cumulative maximum
number of records returned by all SOQL queries, including parent-to-child, is 50,000.


Querying Multiple Objects

The result of a SOQL query can be a simple list of records containing rows and columns
or hierarchies of records containing data from multiple, related objects. Relationships
between objects are navigated implicitly from the database structure.This eliminates the
work of writing accurate, efficient join conditions common to development on traditional
SQL databases.

The two ways to navigate object relationships in SOQL are child-to-parent and parent-
to-child. Listing 5-29 is an example of a child-to-parent query, returning the name,
city, and Force.com username creating its contact of all resources with a mailing address in
the state of Illinois. It selects and filters fields of the Contact object, the parent object of
Resource. It also selects the Name field from the User object, a parent two levels removed
from Resource via the Contact’s CreatedBy field.

Listing 5-29 SOQL with Child-to-Parent Relationship
SELECT Name, Contact__r.MailingCity, Contact__r.CreatedBy.Name
FROM Resource__c
WHERE Contact__r.MailingState = 'IL'

Note

The results of child-to-parent relationship queries are not completely rendered in the
Force.com IDE. You can double-click a row and column to view fields from a parent record,
but this is limited to direct parents only. Fields from parent-of-parent objects, such as the
Contact__r.CreatedBy relationship in Listing 5-29, are omitted from the results. This is a
limitation not of SOQL, but of the Force.com IDE.

At most, five levels of parent objects can be referenced in a single child-to-parent
query, and the query cannot reference more than 25 relationships in total.
The second form of relationship query is the parent-to-child query. Listing 5-30 provides
an example.The parent object is Resource, and the child is Timecard.The query
selects from every Resource its Id, Name, and a list of hours from its Timecards in the current
month.

Listing 5-30 SOQL with Parent-to-Child Relationship
SELECT Id, Name,
(SELECT Total_Hours__c
FROM Timecards__r
WHERE Week_Ending__c = THIS_MONTH)
FROM Resource__c

A parent-to-child query cannot reference more than twenty child objects. Doubleclicking
the parent record in the results table brings up the child records for viewing in
the Force.com IDE.

Sorting Query Results

Results of a query can be sorted by up to 32 fields in ascending (ASC, the default) or
descending (DESC) order. Sorting is not case-sensitive, and nulls appear first unless otherwise
specified (NULLS LAST). Multi-select picklists, long text areas, and reference type
fields cannot be used as sort fields.The SOQL query in Listing 5-28 returns records first
in ascending order by Type, and then in descending order by LastModifiedDate.

Listing 5-28 SOQL Statement with Sort Fields
SELECT Name, Type, AnnualRevenue
FROM Account
ORDER BY Type, LastModifiedDate DESC


Filtering Records

SOQL supports filter conditions to reduce the number of records returned.A filter condition
consists of a field name to filter, an operator, and a literal value.
Valid operators are > (greater than), < (less than), >= (greater than or equal to), <= (less
than or equal to), = (equal to), != (not equal to), IN and NOT IN (matches a list of literal
values, and supports semi-joins and anti-joins), and INCLUDES and EXCLUDES (match
against multi-select picklist values). On String fields the LIKE operator is also available,
which applies a pattern to filter records.The pattern uses the % wildcard to match zero or
more characters, _ to match one character, and the \ character to escape the % and _
wildcards, treating them as regular characters.
Multiple filters are combined in a single SOQL statement using the Boolean operators
AND and OR and grouped with parentheses. Listing 5-26 returns the names of accounts
with a type of direct customer, a modification date sometime during the current year, and
more than $100 million in annual revenue.


Listing 5-26 SOQL Statement with Filter Conditions
SELECT Name
FROM Account
WHERE AnnualRevenue > 100000000
AND Type = 'Customer - Direct'
AND LastModifiedDate = THIS_YEAR


Notice the way literal values are specified.Apostrophes must be used around String literals
but never with other data types. THIS_YEAR is a built-in relative time function.The
values of relative time functions vary based on when the query is executed. Other relative
time functions are YESTERDAY, TODAY, TOMORROW, LAST_WEEK, THIS_WEEK, NEXT_WEEK, and
so forth.
Absolute dates and times can also be specified without apostrophes. Dates must use the
YYYY-MM-DD format. Datetimes can be YYYY-MM-DDThh:mm:ssZ, YYYY-MMDDThh:
mm:ss+hh:mm, or YYYY-MM-DDThh:mm:ss-hh:mm, indicating the positive or negative
offset from Coordinated Universal Time (UTC).
In addition to filter conditions, SOQL supports the LIMIT keyword. It sets an absolute
upper bound on the number of records that can be returned from the query. It can be
used in conjunction with all the other SOQL features. For example, the SOQL statement
in Listing 5-27 returns up to ten Account records modified today.

Listing 5-27
SELECT Name, Type
FROM Account
WHERE LastModifiedDate = TODAY
LIMIT 10




SOQL Basics

Despite being one letter away from SQL and borrowing some of its syntax, SOQL is
completely different and much easier to understand on its own terms. Just as Apex is not a
general-purpose programming language like Java, SOQL is not a general-purpose database
query language like SQL. SOQL is specifically designed and optimized for the Force.com
database.
A SOQL statement is centered on a single database object, specifying one or more
fields to retrieve from it.The fields to select are separated by commas. Listing 5-25 is a
simple SOQL statement that returns a list of Account records with Id and Name fields
populated. SOQL is not case-sensitive. SOQL keywords are shown throughout the book
in uppercase and metadata objects in title case for readability only.

Listing 5-25 
SELECT Id, Name
FROM Account


Database Queries

You’ve seen how data structures in Apex are implicitly defined by the objects in your
database. Force.com provides two query languages to populate these objects with data:
Salesforce Object Query Language (SOQL) and Salesforce Object Search Language
(SOSL). SOSL,  provides unstructured,
full-text search across many objects from a single query.
The focus of this section is SOQL because it is the workhorse of typical business applications.
This section includes subsections on the basics of SOQL, filtering and sorting,
how to query related objects, and how to use SOQL from Apex code.
As you read this section, you can experiment with the sample SOQL queries using the
Force.com IDE’s Schema Explorer. Enter a query in the text box in the upper-left corner
and click the Run Me button.The results appear in the table below the query. 

Database Records as Objects

All database objects, standard and custom, are available as first-class members of the Apex
language, automatically and transparently.This eliminates the mind-numbing, error-prone
work of importing, mapping, and translating between relational and program data structures,
chores commonly required in general-purpose programming languages. In Apex,
references to database objects are verified at compile time.This reduces the possibility of
runtime surprises caused by field or object mismatches. Listing 5-22 shows an example of
creating a record in the Resource custom database object and setting its name field.

Listing 5-22 Creating a Record
Resource__c resource = new Resource__c();
resource.Name = 'Larry';

Database relationships are also exposed in Apex.The __r syntax refers to a relationship
field, a field that contains a reference to another object or list of objects. Listing 5-23
builds on the previous listing, creating a standard Contact record and associating it with
the Resource record.

Listing 5-23 Creating a Record with Relationship
Contact c = new Contact();
c.FirstName = 'Larry';
resource.Contact__r = c;

The Force.com IDE’s Schema Explorer can take the mystery out of relationship fields
like Contact__r. It displays the correct syntax for referring to fields and relationships,
based on the actual schema of the database object. Its Schema list on the right side displays
all objects, custom and standard. Drilling into an object, the Fields folder lists all fields in
the object and their types.A reference type indicates that a field is the child object in a
Lookup relationship. Expand these fields to reveal their parent object’s type and name. For
example, Contact__r is the foreign key to the Contact object
Data integrity is protected in Apex at compile and runtime using object metadata. For
example, Name is defined as a read-only field in Contact, so the code in Listing 5-24
cannot be compiled.

Listing 5-24 Attempted Assignment to Read-Only Field
Contact c = new Contact();
c.Name = 'Larry';
After a database object is referenced in Apex code, that object cannot be deleted or
edited in a way that invalidates the code.This protects your code from changes to the
database schema. Impacted code must be commented out before the database objects are
modified.

Tuesday 14 May 2013



Execute Anonymous View

The Execute Anonymous view provides an interactive, immediate way to execute arbitrary
blocks of Apex code. Unless noted otherwise, you can execute all the code snippets
in this chapter directly from the Force.com IDE using the Execute Anonymous view.
To try the Execute Anonymous view, first create a new Force.com Project. Go to the
File menu and select File ? New Force.com Project. Enter a project name; enter your
Force.com username, password, and security token; and click the Next button. If you
receive an error on this step, double-check your username, password, and security token.
Also make sure you’re providing the credentials for a Developer Edition organization,
given that other types of organizations might not have access to the Force.com API. Click
the Finish button to create the project.
After you’ve created a project for your Development Edition organization, the Execute
Anonymous view should be visible in the lower-right half of the screen. If not, go to the
Window menu and select Show View --> Execute Anonymous. In the Source to Execute
text box, enter the code given in Listing 5-1. If the text box is not visible, resize your Execute
Anonymous view until it’s tall enough to see it.After you’ve entered the code, click
the Execute Anonymous button to run it.
Listing 5-1 Hello World
String helloWorld(String name) {
return 'Hello, ' + name;
}
System.debug(helloWorld('Apex'));
This sample code defines a function called helloWorld that accepts a single String
parameter. It then invokes it with the name Apex and displays the results, Hello Apex, to
the debug log

Problems View


The Force.com IDE leverages the standard Eclipse view called Problems to display compilation
errors.When you save changes to an object in a Force.com Project, it is sent over
the network to the Force.com service for compilation. If compilation fails, Force.comspecific
errors are added to the Problems view. In most cases, you can double-click a problem
row to navigate to the offending line of code.

Schema Explorer


The Schema Explorer allows direct interaction with the Force.com database. Use it to
inspect objects and fields and to execute database queries and preview their results.To
open the Schema Explorer, double-click the object named salesforce.schema in any
Force.com Project


Force.com Projects


A Force.com Project allows you to read and write code, user interfaces, and other metadata
objects within a Force.com organization from your local computer.Although this
metadata is edited locally, it must be deployed to the Force.com service to run. Deployment
to Force.com occurs automatically every time you make a modification to an object
in a Force.com Project and save the changes.

Note


Force.com does not provide its own integrated source control system, but Force.com Projects
can be integrated into your company’s source control system through the built-in Team
features of Eclipse. Refer to the Eclipse documentation for more information.


Force.com Perspective


A perspective is a concept used by Eclipse to describe a collection of user interface components.
For example, Eclipse has built-in perspectives called Java and Java Debug. By
installing the Force.com IDE, you’ve added a perspective called Force.com. 
If you do not see the Force.com perspective, click the menu option Window-->Open
Perspective ? Other, select Force.com from the Open Perspective dialog, and click the
OK button
The Force.com perspective includes several user interface panels, called views. Execute Anonymous and Apex Test Runner.
It also adds a new type of project called the Force.com Project, which is shown in the leftside
Navigator tab.The first step to using the Force.com IDE is to create a Force.com
Project.

Apex Test Runner View

All business logic written in Force.com must be accompanied by unit tests to deploy it to
a production environment.Apex Test Runner view is a user interface to run unit tests and
view test results, including statistics on code performance and test coverage. If the Apex
Test Runner is not already visible on the bottom of your screen, go to the Window menu
and select Show View --> Apex Test Runner.

Introducing the Force.com IDE

The Force.com IDE is an extension to the standard Eclipse development tool for building,
managing, and deploying projects on the Force.com platform.

Installation

Force.com IDE is distributed in two forms: a standalone application, and a plugin to the
Eclipse IDE. If Force.com is your primary development language or you are not an existing
Eclipse IDE user, the standalone version is a good choice.The plugin version of the
Force.com IDE requires Eclipse, which you can find at www.eclipse.org. Only specific
versions of Eclipse are supported by the Force.com IDE. If you are already using Eclipse
but it’s an unsupported version, keep your existing Eclipse version and install the supported
version just for use with the Force.com IDE. Multiple versions of Eclipse can
coexist peacefully on a single computer.
Visit http://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse to learn
how to install the standalone and plugin versions of the Force.com IDE.


Friday 10 May 2013


Introduction to Apex

Apex is a stored procedure-like language that runs entirely on the Force.com platform. It
provides object-oriented features and tight integration with the Force.com database. It’s
mainly used in custom user interfaces and in triggers, code that is executed when data is
changed in the database.
Apex is not a general-purpose programming language like Java or C. Its scope is limited
to business and consumer applications that operate on relational data and can benefit
from the feature set of the surrounding Force.com platform.
Apex programs exist in a multitenant environment.The computing infrastructure used
to execute Apex is operated by Salesforce and shared among many developers or tenants
of the system. As a result, unlike general-purpose programming languages you are familiar
with, the execution of Apex programs is closely controlled to maintain a consistently high
quality of service for all tenants.
This control is accomplished through governor limits, rules that Force.com places on
programs to keep them operating within their allotted share of system resources. Governor
limits are placed on database operations, memory and bandwidth usage, and lines of
code executed. Some governor limits vary based on the type of licensing agreement you
have in place with Salesforce or the context that the code is running in, and others are
fixed for all users and use cases.

Note

The most prevalent governor limits are discussed throughout this book, but it is not a complete
treatment of the subject. The authoritative guide to governor limits is the Force.com
Apex Code Developer’s Guide, available at http://developer.force.com. Educate yourself on
governor limits early in the development process. This education will alter the way you architect
your Apex code and prevent costly surprises. Additionally, test all of your Apex code with
production-like data volumes. This helps to expose governor-related issues prior to a production
deployment.
Here are a few important facts about Apex:
  •  It includes integrated testing features. Code coverage is monitored and must reach 75% or greater to be   deployed into a production environment.
  •  It is automatically upgraded. Salesforce executes all of its customers’ unit tests to verify that they pass before deploying a major release of the Force.com platform.Your code is always running on the latest version of Force.com and can take advantage of any and all new functionality without the hassle and risks of a traditional software upgrade process.
  •  There is no offline runtime environment for Force.com.You can edit your code on your desktop computer, but it must be sent to Force.com for execution.
  •  Apex is the only language that runs on the Force.com platform.You can integrate Apex with programs running outside of Force.com using HTTP-based techniques such as Web services.
  •  The Force.com database is the only database integrated into the Apex language. Other databases can be integrated through Web services or other technology using HTTP.


The two primary choices for developing Apex code are the Web-based App Builder Tools
and the Force.com IDE, provided as a standalone application as well as a plugin to the
standard Eclipse IDE.The Force.com IDE is the more powerful and developer-friendly of
the two, so it is used throughout this book.


Thursday 9 May 2013


Using Hierarchy Custom Settings

Hierarchy type custom settings provide additional options when storing values.To see
them in action, create a new custom setting object called Hierarchy Setting with an
object name of HierarchySetting.Again, add a checkbox field named Debug.The default
value of Debug selected here is the organization-level setting, which applies if no values
are defined for a user or profile.

When you’ve finished creating the custom setting, add a new value to it.You are
prompted to set the value of the Debug field as with the List custom setting example. But
there is an additional system field called Location. Location determines at which level in
the hierarchy the setting applies.The two options are Profile and User.Try to create two
custom setting records, one with Debug selected for the System Administrator profile, and
the other a user in that profile with Debug deselected. Figure 4-15 shows the result of
this, with a custom view (named Custom View) that pulls in the value of the Debug field
to show it varying across the two custom settings records.

Caution
Storage limits exist on custom settings data. For example, in a Developer Edition organization,
you cannot store more than 2MB total in all of your custom setting objects. Current
usage and the limit for your organization is shown on the Custom Settings main page. To
view it, go to the App Setup area and select Develop -->Custom Settings.

Using List Custom Settings

The following steps describe how to build a simple custom settings object and manage the
values stored in it:
1. Go to the App Setup area and click Develop -->Custom Settings.This is where you
define custom settings and maintain their values.
2. Click the New button to define a new custom settings object. Label is the display
name for your object; Object Name is the name you’ll refer to it by in programs.
Enter Config Setting as the Label, and ConfigSetting as the Object Name. For
Setting Type, select List.Visibility controls how this setting behaves when packaged.
Leave it as Protected. Use the Description field to explain the purpose of your custom
setting to other developers in your organization.
Tip
Following a naming convention for your custom settings so that they can be easily differentiated
from custom objects is a good practice. For example, append the word “Setting” to the
end of any custom setting name. The value of naming conventions will become more apparent
when you write Apex code that interacts with the database.
3. Click the Save button.Your custom setting is now created and needs some fields
and data. Each custom setting can have up to 300 fields.
4. In the Custom Fields section, click the New button to create a new field. Custom
settings fields use a subset of the data types available to custom object fields.They
are Checkbox, Currency, Date, Date/Time, Email, Number, Percent,Text,Text
Area, and URL. Select Checkbox for your field and click the Next button. For the
field label, enter Debug.The Field Name, used to refer to the field in code, is automatically
populated. Click the Next button.
5.
You’re ready to store values in your custom settings object. Force.com provides a standard
user interface for this purpose. Click the Manage button and then the New button.There
is a field for the Name of the setting record, which serves as a human-readable identifier
for the record. Following the name are the custom fields you’ve defined on the custom
setting. In this case, you have a single checkbox field named Debug. Enter Default for
the name, select the Debug box, and click the Save button.

Wednesday 8 May 2013


Custom Settings

Custom settings are a special data storage feature designed for relatively simple, frequently
accessed data.The type of data stored in custom settings is ancillary, used to configure or
control your application rather than the operational data itself, which belongs in standard
and custom objects. For example, user preferences in a Java application might be stored in

an XML or properties file. In Force.com, they are stored in custom settings. Data in custom
settings is readily accessible throughout the Force.com platform in Apex,Visualforce,
formula fields, validation rules, and Web Services API.As an example, a custom setting
named Expert might indicate whether a given user receives the default or advanced version
of a user interface.
A custom setting is an object definition,much like a standard or custom database object. It consists of a name, a type, and one or more fields.The two types of custom settings are List and Hierarchy:
 List: The List is the simpler form, behaving like a database object except for the fact that records are accessed one at a time, by unique name. For example, you might define a custom setting with fields representing configurable options in your application, and each named record representing a collection of those options, such as Test and Production.
Hierarchy: The Hierarchy type expands upon the List type, adding the ability to relate data to organization, profile, and user. If a value is not provided for a given level, it defaults to the levels above it.With Hierarchy types, you can create applications that manage settings for individual users, but defer to a profile or organizationwide default when necessary without storing and maintaining redundant,overlapping information.


Force.com Connect Offline

Force.com provides a solution for offline access called Force.com Connect Offline. It
allows read and write access to Force.com data while you’re disconnected from the network.
When you’re connected again, the data you’ve created or modified offline is synchronized
and reconciled with Force.com, and any new records created by other users
while you were disconnected are cached on your computer.
You should consider two viewpoints when getting to know Force.com Connect
Offline. First, an administrator configures the feature for users, specifying the data available
for offline access.Then there are the users themselves, who must be running a Windows
operating system.They use a dedicated client application to access Force.com when disconnected,
in place of their normal Web browsing application.


Administration of Force.com Connect Offline


Two independent tracks exist within offline configuration. One is called the Briefcase, and
it allows users to directly control the data they need to access offline.The Briefcase is limited
to sales objects: accounts, contacts, opportunities, and leads.This option is not discussed
further because it is a CRM-specific feature and does not work with custom
objects.
The full version of offline configuration is performed by administrators at the profile
level. It allows any custom object to be available for offline access and provides filters to
limit the amount of data.
To define your own offline configuration, in the Administration Setup area, click Desktop
Administration -->Offline Briefcase Configurations. .
Two profiles are granted access to a data set made up of records from seven
objects.
The majority of the work in creating an offline configuration is in defining the data
sets.A data set is simply a group of records cached on users’ machines that they can interact
with while disconnected from the network. Data sets consist of the following components:
 Objects: Select one or more objects to enable for offline access. Objects can be
nested in a hierarchy, leveraging relationships between objects to filter records.

Record Ownership Filters: Four options are available for restricting data by
owner.The default is to include all records the user has access to read.Two other
options filter on owner, limiting records to those owned by the user directly or by
the user and its subordinates in the role hierarchy.The final option provides search
access to all records but doesn’t actually synchronize the data.
Field Filters: Field filters restrict data based on their values. Filters consist of a
field, an operator to compare the values, and a static value. Multiple filters are additive
by default but can be chained together in more complex ways using the
Advanced Filter Conditions.
Record Limits:You can set a maximum number of records to retrieve for a given
data set. If you do not set a limit, Force.com internally limits the data set to 5,000
records per object.



Using Force.com Connect Offline
In the Personal Setup area, click Desktop Integration ➝ Force.com Connect Offline.
Click the Install Now button to download the desktop client. It is available only for Windows
operating systems.After proceeding through the installation program, you should
have an icon on your desktop and in your Start menu called Offline Edition. Launch it
and enter your username and password in the login dialog. Be sure to include your security
token after your password.


After you’re logged in and the initial synchronization is performed, you should see the
tabs associated with objects included in your offline configuration.You are now working
offline. Figure 4-12 shows a detail record in the offline client application.The user interface
is similar to the standard Force.com native user interface, with some elements
removed.The list of applications in the upper-right corner is gone, so the tabs from all
applications are shown together in a single line

At this point, you can browse your offline data sets, search, create new records, edit existing
records, and delete records. Click the Synchronize Briefcase link in the upper-right
corner to send your changes back to Force.com when you’re connected to the network.
If conflicts occur between the data entered offline and data in Force.com, you get the
opportunity to manually reconcile the changes.  Each pair of conflicting changes is
 displayed side-by-side, and you decide which version of the data is correct.












Tags

Tags are keywords that users can place on records to make them easier to find.These keywords
can be private to a specific user or shared among all users.Tagging can reduce the
complexity of your objects by providing a catch-all way for users to search, without additional
dedicated search fields.The primary disadvantage is that the search is unstructured.
Tags are always strings and cannot be treated as numbers or dates.

Enabling Tags

Initially, tags are disabled.To enable them, go to the App Setup area and click Customize
-->Tags -->Tag Settings. One check box enables personal tags, and the other enables public
tags. Personal tags placed on a record are visible only to the user creating the tags. Public
tags are visible to all users. Public tags can be configured to appear on reports, documents,
notes, and dashboards.
To finish, select the page layouts to enable tagging on. Selected page layouts are
enhanced with a gray subheading containing controls for viewing and editing tags.

Using Tags

Visit a record whose page layout has tagging enabled on it. Click the Add Tags link.
Depending on how you’ve configured tags, you could see an input field for public tags,
private tags, or both. Enter tags separated by commas.

When you’re done, your record contains a list of your tags across the top.
If you create a tag on a second record, notice that Force.com assists you by suggesting
tags that you’ve added on other records.This helps make the tags consistent, improving the
quality of search results.

To search using tags, enter a tag in the search sidebar.The tags section of the search
results returns the matching tags, as well as other tags found in the same records as your
search tag. Click a tag to view a list of records that contain the tag.

Field History Tracking

Field history tracking provides an audit trail of changes to one or more fields of your
objects.This audit trail is accessible in the native user interface by adding a special related
list to your page layout and also in your own custom code. No user can remove or edit
entries in the audit trail, not even a system administrator.
To get started with field history tracking, follow these steps:
1. Go to your custom object’s definition page and click the Edit button.
2. In the Optional Features section, selectTrack Field History and click the Save button.
3. Click the Set HistoryTracking button in the Custom Fields & Relationships section.
4. Check off the fields you would like to track.Your screen should resemble what’s
shown in Figure 4-8.You can track up to 25 fields per object.You cannot track the
history of formula, roll-up summary, or auto-number fields.
5. Edit the page layout for your object and add the related list corresponding to your
object’s history.
6. To test, find a record to change in your object. Edit the value of one of the fields
you’ve enabled field history tracking on.When the edit is complete, notice that the
field history related list contains the details, as shown in Figure 4-9.This field history
related list cannot be customized, but you can create your own custom user interface
for viewing field history using Visualforce.

Tuesday 7 May 2013


Roll-Up Summary Fields

Summarizing data in SQL databases is a routine matter of invoking GROUP BY and an
aggregate function like SUM. Force.com’s SOQL query language supports summarization
as well but comes with limitations. Built-in reporting in Force.com provides some summarization
functionality, but it’s an independent feature with its own user interface, not
integrated with your custom application’s user interface. For the flexibility to use summary
data anywhere, Force.com requires that it be calculated incrementally, either by the
database itself or in Apex code. As a result, planning for summary-level data as the database
is designed is best.
Roll-up summary fields are the mechanism for instructing the database that you would
like summary data to be calculated without custom code or ad-hoc queries.You specify

the child object to summarize, the function to apply to the child records, and filter criteria
on the child records.The database then takes care of keeping the roll-up summary values
up to date as child records are created, modified, and deleted. For example, given an
Invoice Header object and Invoice Line Item child object, you could use a roll-up summary
field on the Invoice Header to maintain a running count of invoice line items.
Roll-up summary fields are added to objects using the same process as adding other
types of fields.After you have provided a label and selected the Roll-Up Summary Field
type
The summary calculation consists of three parts:
Summarized Object: A drop-down list contains the objects you are permitted to
summarize.This is restricted to child objects in a Master-Detail relationship with
the object on which you’re creating the roll-up summary field. Lookup relationships
are not supported.

 Roll-Up Type: Select the calculation to be performed on the child records and the
field of the child object to perform it on.The fields available in this list depend on
the calculation. If your calculation is Sum, the list contains fields of type Number,
Currency, and Percent.With Min or Max, you can also summarize Date and
Date/Time fields. Note that you cannot roll up other roll-up summary fields or formula
fields that contain references to other objects, merge fields, or functions
returning dynamic values, such as TODAY and NOW.


Filter Criteria: By default, all records are included in the summary calculation.
Alternatively, you can also specify one or more filter criteria to restrict the records
involved in the calculation. Build filter criteria by selecting a field to filter, the
operator to apply, and the value. If you add more than one criteria, the effect is
additive. All filter criteria must be satisfied for the record to be included in the summary
calculation.

After you have specified the summary calculation and saved the new field, Force.com
begins calculating the summary values on existing records.This can take up to 30 minutes.
An icon is displayed beside the field to indicate that the calculation is running.
You can define at most ten roll-up summary fields per object. Make a point of creating
them toward the end of your database design process, because they make changing your
objects more difficult. For example, you can’t convert a Master-Detail relationship to a
Lookup relationship without first removing the roll-up summary fields.





Using Record Types

You’ve learned how to define record types and how they help determine which page layout
is shown to a user and the picklist values within it. But how does a record get
assigned a record type in the first place?
If a user has access to only one record type, that record type is automatically assigned
to the record.Things become more interesting for users with access to more than one
record type.The first step of creating a new record becomes selecting its record type.

Users who find this extra step in record creation unnecessary can disable it by visiting
their Personal Setup area and clicking My Personal Information ➝ Record Type Selection.
Here they can opt to always use the default record type.The default record type is
chosen by the administrator and stored in the user’s profile.
A record begins life as a particular record type, but its type can be changed later by the
record owner. If the Record Type field is added to your page layout, you’ll see a Change
link beside it. After the record type is changed, the Force.com user interface automatically enters edit mode on the record to allow you to fix any picklist values that are no longer valid.



Securing Record Types

Users are granted access to record types according to their profiles. Profiles contain a section
called Record Type Settings. Every one of your custom objects is displayed there,
along with a list of the record types the profile is allowed to access and an Edit link.
the result of clicking the Edit link on a custom object called Resource in
the System Administrator profile. It shows that the System Administrator profile is allowed
to access two record types.The default record type is Internal, and the impact of this is
discussed in the subsequent section.

Another part of security is field visibility,which is partially determined by the page
layout. Record types add another dimension of configurability for assigning page layouts
to users.Without record types, the page layout is determined by a user’s profile. But with
record types, you have the additional option of splitting the decision by record type.You reach the
screen by clicking the Page Layout Assignment button in the Page Layouts section of the
object definition.

In this screen, an administrator can quickly review and modify the page layouts
assigned to all combinations of record type and profile.

Defining Record Types

Record types are defined at the object level after an object is created. In the object definition
is a section called Record Types for creating, editing, and deleting record types. Click
the New button there to start.

Every object has a default record type called Master. It contains the master list of values
for all picklist fields in the object. New record types are cloned from the Master
record type if no other record types exist, and given a name, label, and description. Normally
record types are in an active state, which makes them available to users who are creating
and editing records. Deactivating a record type is required before it can be deleted.

The list at the bottom of the page is a shortcut for adding this record type to many
profiles at once.You can skip it. If you do use it, do so with caution. If you add your
record type to many profiles and later decide you want to delete it, you must manually
visit each profile to remove the record type first. Record types cannot be deleted if they
are referenced by profiles.

The next page allows you to associate your new record type with one or more page
layouts.This determines which native user interface is shown when a user creates or edits
a record of this type.The default is to show one page layout to all users, regardless of their
profiles.This page can also be skipped.There is another user interface to do the same
thing, but across multiple record types and profiles simultaneously.

After the record type is saved, it enters an edit mode. Edit mode permits the maintenance
of picklist values for the record type.The list of picklist type fields in the object is
shown, with Edit links beside each.These Edit links take you to , a screen that
allows picklist values to be customized. Here you can select all, or a subset of the picklist
values, and provide a custom default value.


This is just one way to manipulate the picklist values of a record type.When adding new
picklist values in an object with more than one record type defined, you are asked which
record types they apply to. By default, new picklist values
are added only to the Master record type, leaving other record types unchanged.

Monday 6 May 2013


How to disable a Record Type in Salesforce

How to disable a Record Type in Salesforce Using record types you can provide different sales/business processes to your users with different picklist values and different page layouts.

When creating a new record type you can choose if you want to enable it for one or several profiles. If you enable it, it will (if more than one are enabled ) appear as a choice that comes up before you create a new object.

Let’s take the Opportunity as an example. I need three record types and first I decide to have all three enabled, i.e. to have as choices in the beginning of a creation of an object instance.

Find the record types for the Opportunity here:



When you are creating a new record type you get the option to enable it for all or some profiles. If they are enabled they will appear as choices as explained before. Important though is thay they have to be active. If they are not active they can not be used.



Now we have three record types for the Opportunity:



And in the profile for the Contract Manager for example we can see that three Opportunity Record Types has been enabled.



To disable a record type from only one or some profiles you can simply click on edit and select or deselect which should be available.



But if you want to disable a record type from all profiles and don’t want to go through the work of entering each profile separately you simply open the record type and inactivate it. This way it will automatically be disabled and removed as selected from the profiles.




If you want to enable a record type again though after this you don’t seem to get the same option as when first creating the Record Type, i.e. to enable for one or several profiles at once. Instead you would have to enter each profile separately and reselect it again.

Sunday 5 May 2013


Record Types

Record types overload the native user interface behavior of a single object.This allows
you to get more mileage out of your existing objects or limit the complexity of a new
data model.

For example, Salesforce uses this feature in its CRM product. Person Accounts are a
record type of the Account object.Accounts ordinarily store information about businesses,
but the Person Account record type adapts Account to store information about
individuals. Salesforce opted to overload Account with a record type rather than creating
an entirely new object.
Before creating a separate object to represent every business entity, ask yourself
whether the entity is truly new or merely a slight variation of another entity.Where you
find slight variations, consider using a single object to do the work of many.The single
object contains a superset of the objects’ fields.The record type of each record determines
which variation of the business entity is stored. Force.com consults the record type and
the user’s profile to display the correct native user interface.
Even if you don’t plan to use the native user interface, record types can expand the
flexibility of your data model. By using record types, you gain an additional standard field
called RecordTypeId. In custom user interfaces, you can use this to drive different functionality.
Of course, you can always add your own custom field to accomplish the same
thing, but record types force you to make your design explicit at the native Force.com
level and provide tight integration with native Force.com security.
Record types can be tricky to configure because they interact with many other features
of Force.com.This section examines record types across three areas:
1. Defining Record Types: Record types enable picklist fields to be customized to
show different values for different record types of an object.They also add another
dimension of flexibility when designing page layouts.
2. Securing Record Types: Users gain access to record types through their profiles.
3. Using Record Types: The native user interface changes in some significant ways
when a user has rights to multiple record types.