Published using Google Docs
A Nimble Introduction to the Force.com Platform

A Nimble Introduction to the Force.com Platform

Developing with Apex and Friends

The Force.com Trinity

Apex Triggers

Apex in Bulk

Testing Apex

Development Tools

No App is an Island

Learning Plans

Learning Plan - Videos

Learning Plan - Workbooks

Learning Plan - Guides

Salesforce CRM is the world's first-and-finest cloud application. The Force.com platform underlies Salesforce CRM, and the platform can be used to write any kind of application, whether it's connected to Salesforce CRM or not. The platform allows for deep customizations and rivals anything that can be done with a conventional, on-premises platform.

Many sophisticated customizations can be created in Salesforce CRM without installing development tools or writing a line of code. However, for developers ready to code, the sky really is the limit (in a good way!).

Compared to .NET or J2EE, developing on Force.com is both very familiar and very different. It's familiar because you still follow the same-old Software Delivery Lifecycle. You write code, queries, and unit tests using familiar syntaxes and tools. When QA signs-off, you push components from development to production. And when users come up with something that we can do to make their lives easier, we do it all over again.

Of course, there are some notable differences

OK, enough sizzle. How about some steak?

Developing with Apex and Friends

A differentiator between most platforms is its native languages. In the case of Force.com, the native languages are designed to feel familiar, while taking full advantage of the platform.

The Force.com Trinity

Upon upon a time, applications were mainly about ferrying data between a teletype interface and a relational database. As user interfaces became more sophisticated, and data models became more refined, the development community turned to object oriented programming to help us manage the complexity of modern applications. While OOP has proven its worth, the world of objects is very different that the world of data, and we swallow the pain with soothing terms like "object-relational impedance mismatch".

The Force.com platform solves mismatch issues with a set of three technologies designed to work together, hand-in-glove. Each tool has a familiar look and feel to popular, existing technologies.

Here's an example of a Visualforce page and controller. The controller plays the same role as a ASP.NET code-behind or JSF backing-bean.

Please note that we are showing a Visualforce page for completeness. In real life, most of the time, the standard user interface can be customized without bothering with a Visualforce page.

Simple Visualforce page with Development Mode enabled

<!-- Simple Visualforce page that can edit an Account name. -->

<apex:page standardController="Account" extensions="myControllerExtension">

        <p> {!greeting} </p>

        <apex:form>

            <apex:inputField value="{!Account.Name}"/> <p/>

            <apex:commandButton value="Save" action="{!Save}"/>

        </apex:form>

</apex:page>

// Controller that exposes data to a Visualforce page

public class myControllerExtension {

        private final Account myAccount;

public myControllerExtension(ApexPages.StandardController stdController) {

        myAccount = (Account) stdController.getRecord();

        }

        public String getGreeting() {

                    return 'Hello ' + myAccount.Name + ' (' + myAccount.Id + ')';

        }

}

In this example, without being told, the Controller can accept an Account Id passed as a parameter (?Id=001d000000EJZLJ) and uses it to resolve !Account references. Other behaviors, like the Save action and CSS styling are also provided by platform (and easy to override).

While Visualforce is a powerful customization option, Salesforce CRM has an extensible user interface design. Related lists, custom links and buttons, validation, and workflows can all be implemented without writing presentation code.

Apex Triggers

Originally, Apex was designed as a trigger language. Today, Apex is a strongly-typed, object-oriented language that is also used to add business logic to applications and to program controllers in the user interface. Apex has the usual array of features such as classes, interfaces, constants, class variables, and annotations (but it is not case sensitive).

And it still works great for triggers!

Force.com allows triggers to be associated with any standard or custom object. Triggers can fire before or after an record is created, updated, or deleted. Since Force.com likes to do things in sets or batches, for the sake of efficiency, a trigger is passed two sets of records - .new and .old.

Here's a trigger that loops through the .old set, to see if a record meets a business convention.

if (Trigger.isDelete) {

for (Account a : Trigger.old) {

if (a.Name !=  'okToDelete') {

a.addError('You can\'t delete this record!')

}

}  

In combination with SOQL, the Apex set features are quite powerful. Here's a trigger that fetches the Ids and Last Names for every contact associated with any of the triggering accounts.

Trigger t on Account (after update) {

        Contact[] myContacts = [

          SELECT Id, LastName

          FROM Contact

          WHERE AccountId IN :Trigger.new

];

     // ... Do something with the Accounts or Contact records

}

Note that the SOQL query is enclosed in braces, and that the Apex variable is escaped with a colon. Any Apex variable can participate in a SOQL query.

Apex in Bulk

If you need to work with a very large record set, Force.com offers a Bulk API that can be called from a scheduled Apex class. Using the API, the class runs asyncronously, giving Force.com the opportunity to deploy more immediate tasks around the scheduled task.

Here’s a Bulk API example that clears out an object, and sends you an email when it’s done.  

// From http://salesforcesource.blogspot.com/2010/02/utilizing-power-of-batch-apex-and-async.html

global class MassDeleteRecords implements Database.Batchable<sObject> {

global final string query;

global MassDeleteRecords (String q)

{

                  query = q;

}

global Database.QueryLocator start(Database.BatchableContext BC) {

return Database.getQueryLocator(query);

}

global void execute(Database.BatchableContext BC, List<sObject> scope) {

delete scope;

}

global void finish(Database.BatchableContext BC) {

 // Get the ID of the AsyncApexJob representing this batch job

 // from Database.BatchableContext.  

 // Query the AsyncApexJob object to retrieve the current job's information.

AsyncApexJob a = [

SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email

          FROM AsyncApexJob

WHERE Id =:BC.getJobId()];

 // Send an email to the Apex job's submitter

// notifying of job completion.

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

 String[] toAddresses = new String[] {a.CreatedBy.Email};

 mail.setToAddresses(toAddresses);

 mail.setSubject('Apex Sharing Recalculation ' + a.Status);

 mail.setPlainTextBody('The batch Apex job processed ' +

a.TotalJobItems + ' batches with '+

a.NumberOfErrors + ' failures.');

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

}

}

}

Testing Apex

Unit testing was baked into Apex from the git-go. Any custom code deployed to a production org must meet a 75% code coverage benchmark, or Force.com will decline to deploy the change set. Sorry, Charlie.

To help us pass muster, there are simple but effective Assert methods included with the global system object.

// From http://wiki.developerforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

// This trigger tags any accounts we create during user acceptance testing

trigger MarkAccountDescriptionsForTesting on Account (before insert) {
 for(Account a: Trigger.new){
   if (a.Name.toLowerCase().contains('test')){
     a.Description =
       'This Account may be left over from user acceptance testing. It should probably be deleted.';
        }
   }
}

// This test exercises our Account Description trigger

static testMethod void verifyAccountDescriptionsWhereOverwritten(){
   // Perform our data preparation.
   List<Account> accounts = new List<Account>{};
       
   for(Integer i = 0; i < 200; i++){
       Account a = new Account(Name = 'Test Account ' + i);
       accounts.add(a);
   }

   // Start the test, this changes governor limit context to
   // that of trigger rather than test.
   test.startTest();
                
   // Insert the Account records that cause the trigger to execute.
   insert accounts;
                
   // Stop the test, this changes limit context back to test from trigger.
   test.stopTest();
                
   // Query the database for the newly inserted records.
   List<Account> insertedAccounts = [SELECT Name, Description
                                     FROM Account
                                     WHERE Id IN :accounts];
                
   // Assert that the Description fields contains the proper value now.
   for(Account a : insertedAccounts){
     System.assertEquals(
       'This Account may be left over from user acceptance testing. It should probably be deleted.',
       a.Description);
   }
}

The best thing about unit testing with Apex is that any data we create during a test is automatically rolled back. Poof. Gone. No worries mate. Bob’s your uncle. By default, a unit test can’t even see any pre-existing data in an org, limiting your tests to your own test data -- which is very much a best practice!

Development Tools

While you can create Visualforce pages and Apex classes, run tests, all without leaving the comfort of a Force.com web application, you can also develop using conventional IDEs, like Eclipse. The Force.com IDE is built as an extension to Eclipse, so you have a top-shelf tool to help you build your world-class app.

But the IDE is not the only one tool in the Force.com shed. We also have SDKs for .NET, Ruby, Java, PHP, and Adobe Flex.  Data import and export helpers, like the Apex Data Loader and Excel Connector. New web-based tools like Workbench and third-party tools like Cloud9 and BrainForce. And integration tools for use with other platforms like Azure, AWS, Facebook, and Google Apps.

See the DeveloperForce Tool page for the full array of geeky goodness.

For more about the Force.com Super Friends, also see An Introduction to …

And if you are up for a second helping, there is also A Comprehensive Look at the Force.com Platform (30 page whitepaper).

No App is an Island

As much as we would like to do all of our work, all day, every day, in Salesforce, in real life, to provide a full menu of services, enterprises use a mix of systems. Towards that end, Salesforce offers a smorgasbord of APIs that should satisfy any flavor of integration.

Web Service / API

Description

More Information

SOAP Web Services API

(Real time tools)

Use the SOAP API to create, retrieve, update or delete records, such as accounts, leads, and custom objects. With more than 20 different calls, the API also allows you to maintain passwords, perform searches, and much more. Use the API in any language that supports Web services. (Apex Data Loader, Nimble Sync Tool)

Web Services API Developer Guide

REST API

(Real time user applications)

REST API provides a powerful, convenient, and simple Web services interface for interacting with Salesforce. It is an excellent choice of technology for use with mobile applications and Web 2.0 projects.

REST API Developer Guide

Bulk API

(Background tools)

Bulk API is based on REST principles, and is optimized for loading or deleting large sets of data. It allows you to query, insert, update, upsert, or delete a large number of records asynchronously by submitting a number of batches which are processed in the background by Salesforce. Bulk API is designed to make it simple to process data from a few thousand to millions of records.

Bulk API Developer Guide

Metadata API

(Source code transfer)

Use Metadata API to retrieve, deploy, create, update or delete customization information for your organization. The most common use is to migrate changes from a sandbox or testing organization to your production organization. The easiest way to access the functionality in Metadata API is to use the Force.com IDE (Eclipse) or Force.com Migration Tool (CLI/Ant).

Metadata API Developers Guide

Apex Callouts

(We call you.)

Apex is a strongly-typed programming language, with a C#/Java-like syntax, used for database triggers, web services, page controllers,  and more.

Apex Callouts enable Apex classes to invoke external web services. This allows you to connect to 3rd party web services such as Google, Amazon, Facebook, and any other external web service.

Apex Web Services and Callouts

Apex Web Services

(You call us.)

Apex Web Services allow you to write Apex logic and expose the logic as a web service that an external application can invoke. This allows you to expose your Apex scripts so that external applications can access your code and your Force.com application. In other words, you can write you own custom web services with Apex.

Apex Web Services and Callouts

Outbound Messaging

(We call you; you answer back.)

Outbound messaging is part of the workflow rule functionality in Salesforce. Workflow rules watch for specific kinds of field changes and trigger automatic Salesforce actions, such as sending email alerts, creating task records, or sending an outbound message. Outbound messaging allows you to specify that changes to fields within Salesforce can cause messages with field values to be sent to designated external servers.

Web Services API Developers Guide

Data Replication

The SOAP API supports data replication, which allows you to store and maintain a local, separate copy of your organization’s pertinent Salesforce data for specialized uses, such as data warehousing, data mining, custom reporting, analytics, and integration with other applications.

Web Services API Developers Guide

Streaming API

The Streaming API is useful when you want notifications to be pushed from the server (Salesforce) to one or more internal or external clients based on criteria that you define, using a publish/subscribe model.

Streaming API Developers Guide

Single Sign On Callout

The Single Sign On Callout feature enables your org to integrate with an external identity management system or perform web-based single sign-on to Salesforce using credentials entered into other application.

How to Implement Single Sign On

Force.com Connect

Composed of five mix-and-match integration solutions, Force.com Connect minimizes the risks of integration and lets businesses take full advantage of existing IT investments, at minimal effort and expense.

Force.com Connect: Five Paths to Success

(Read Me First)

See also Integrating with the Force.com platform.

One thing is certian, Force.com sure plays well with others.

Learning Plans

Over the years, Salesforce.com has created a cornucopia of learning resources for the Force.com platform and Salesforce CRM. The Developer Documentation portal does a great job of organizing resources, but it can still be hard to see the forest for the trees.

A great way to get started with Force.com is to plough through the workbooks and then review the longer developer and implementation guides.

Learning Plan - Videos

The Force.com channel on YouTube is a great first step. The first two listed here are light appetizers, and the next two are the main course and sweet pudding.

Learning Plan - Workbooks

Force.com offers a full set of hands-on tutorial workbooks. Chomping through the workbooks can be the best way to supercharge development.

The order given on the workbook page is as good as any. Cherry-pick a few, or do them all.

Learning Plan - Guides

For a full treatment of the platform, the most detail is provided in a set of book-length guides.

If that’s not enough, the Developer Document portal provides easy access to over a hundred articles, books, workbooks, and whitepapers, all updated three times a year, to keep pace with the relentless Force.com release cycle.

For an experienced developer, the Force.com platform provides its own blend of challenges, opportunities, and trade-offs. There’s a lot to learn, a lot to unlearn, and unlimited room to grow.


Nimble AMS™  is the enterprise Association Management System (AMS) built by NimbleUser and fueled by Force.com. Nimble AMS revolutionizes the traditional AMS model with Chatter, Sites, Apps, Mobile, Social, and more.                 

                                                                  

                                                                                        

NimbleUser, the creator of Nimble AMS, has been helping associations do more with technology for over twenty years. Using the Force.com platform, NimbleUser built out all of the customary AMS features, such as membership and events, along with self-service features so that constituents can interact with the association through mobile devices and the web.

Leverage the power of Salesforce to take your association to the next level. Chatter, Mobile, AppExchange, Content, Workflow, and thousands of other Salesforce features, work seamlessly with the traditional AMS features needed to run your organization.

Nimble AMS includes association management features such as:

Visit us on the AppExchange!

www.NimbleUser.com -