Chatter Developer Preview is Live

If you didn’t attend today’s developer webinar, then you may not know that salesforce.com’s new Chatter feature is now in a developer preview.

Chatter is similar to twitter and facebook updates but all native to salesforce.com and accessible via the force.com API.

Check out the chatter resource page at: http://developer.force.com/chatter
Check out the chatter discussion board at: http://community.salesforce.com/sforce/board?board.id=chatter

There is already a lot of documentation up on the site and the force.com developer group is planning on hosting a contest for the best chatter based apps. Do you have a great idea, we’ll work with you to build it. Let us know in the comments!

Spring cleaning old integrations

Jesper Joergensen posted some interesting info last week about a new endpoint for the API that is currently available. The new endpoint is https://login.salesforce.com and according to Jesper will reduce your authentication time slightly.

While you’re at it, you may want to update your SOQL queries to take advantage of some of the new Aggregate Functions.

Check out the full post at http://blog.sforce.com/sforce/2010/02/new-api-login-endpoint.html

New Spring ’10 feature: SOQL Aggregate Functions

Our partner Arrowpointe has a great post about one of the new features in the Spring ’10 release, Aggregate functions.

The Salesforce Object Query Language (SOQL) is familiar to anyone with SQL experience, however, it has always lacked some more advanced functions. This gap along with some of the Apex governor limits can sometimes make it very difficult to slice and dice data to meet your needs. The new Aggregate functions are a huge improvement to SOQL and returns grouped query results so you don’t have to loop through them in your code.

Check out more details at www.arrowpointe.com

Batch Apex and Custom Settings Force.com Tech Talk

Taggart Matthiesen delivered an amazing tech talk last week on Batch Apex and Custom Settings functionality. Not only did he demonstrate some basic Batch Apex functionality but also gave some promising insight into the future of Apex (safeharbor applies of course).

Some of the big news items included:

  • Increasing the max size of collections to whatever the heap will support
  • Being able to schedule Batch Apex (currently in pilot)
  • Being able to do a mixed DML operation with custom settings

Great job Taggart, thanks for the extremely informative and educational session.

The webinar was recorded, so you can check it out here if you missed it:
http://wiki.developerforce.com/index.php/Tech_Talk:_Whats_New_in_Apex_Code

Let us know in the comments what you plan on using Batch Apex for!

Validating email addresses in Apex

Warning!!! This post is for the Uber-Apex Programmer and should not be attempted by novices. It may cause headaches, hair-loss, eye-strain and more, but it’s well worth it!

On two different occasions in the last week a client has needed email addresses in salesforce.com validated. The only true form of validation for an email address is to send an email and see if it bounces. This post doesn’t cover that. Instead, we’re focusing on the formatting of the email address.

According to a salesforce.com solution (login required), as of the Winter ’08 release, salesforce.com validates email addresses as follows:
1. For the local part of the email address we accept the following characters. (The local part is anything before the @ sign.)
abcdefg.hijklmnopqrstuvwxyz!#$%&’*/=?^_+-`{|}~0123456789
Note: The character dot “.” is supported; provided that it is not the first or last character in the local-part
2. For the domain part of the email address we accept. The domain part is anything after the @ in an email address:
0-9 and A-Z and a-z and dash “-“
3. Example email address:
abcdefg.hijklmnopqrstuvwxyz!#$%&’*/=?^_+-`{|}~0123456789@acme-inc.com

Our goal was to perform the same validation via Apex prior to saving the record. This can be done using a lot of String methods and If statements, but really this type of comparison is best done with a Regular Expession.

Apex already has built-in Pattern and Matcher Classes for this purpose, so all we had to do was come up with the right regular expression. Thanks to some tips at www.regular-expressions.info it was actually an easy task to complete. It was so easy, that we’re releasing this code into the wild for all of our customers (and competitors) to use.

String pat = '[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\*\\/\\=\\?\\^\\_\\+\\-\\`\\{\\|\\}\\~\'._%+-]+@[a-zA-Z0-9\\-.-]+\\.[a-zA-Z]+';
Boolean test = Pattern.matches(pat, email);

Dynamic Picklist Creation and Sorting

Here’s a way to dynamically create a Picklist in Apex, pre-sort the list, and present it in a Visualforce page. In Salesforce it’s not possible to dynamically change Picklist values without getting deep into Force.com API programming. If you wanted to prepare a list of all Contact field names and their labels including custom fields with current information, you would need to generate this dynamically with metadata. To accomplish this we can generate it in Apex and present it in a way that looks like a native Salesforce Picklist.

I’ve included usable code for grabbing Contact metadata so we can present the field Labels in the list and return the Value (Name, AccountId, OwnerId, CustomField1__c, CustomField2__c, etc.) The goal is to present the field labels in alphabetical order with “–None–” listed at the top. When selected this list will return the Id or actual name of the field as opposed to the presented field label. With these results you can use DML to get or set values in Contact.

Visualforce element:

<apex:pageBlockSectionItem >
   <apex:outputLabel value="Contact:" for="contactlist"/>
   <apex:selectList id="contactlist" value="{!contactField}" size="1">
      <apex:selectOptions value="{!contactFieldOptions}"/>
   </apex:selectList>
</apex:pageBlockSectionItem>

Value=”{!contactField}” is the public property defined in the Apex controller class:

public String contactField {get; set;}

//Function to load and sort Contact field metadata for binding to: “{!contactFieldOptions}”
public void loadContactFields()
{
              Map<String, Schema.SObjectField> m = Schema.SObjectType.Contact.fields.getMap();
              List<Schema.SObjectField> sof = m.values();
              contactFieldOptions = new List<selectOption>();
              Map<String, String> tmp = new Map<String, String>();
              List<String> tmp2 = new List<String>();

              for(Schema.SObjectField s : sof)
              {
                            tmp.put(s.getDescribe().getLabel(), s.getDescribe().getName()); // Reversed for sorting
                            tmp2.add(s.getDescribe().getLabel());
              }

              tmp2.sort(); // Sort by field label, not field name
              selectOption so = new selectOption('NONE', '--None--'); // Native SF look and feel
              contactFieldOptions.add(so); // Build the Select List

              for(String s : tmp2)
              {
                            so = new selectOption(tmp.get(s), s);
                            contactFieldOptions.add(so);
              }
}

Finally, you can use the result(s) for dynamic Apex operations such as SOQL:
s = Database.query(contactField + ‘, Namespace__CustomField1__c from Contact limit 1000′);

Dynamic Queries with Apex

Some of our recent projects have had very complex requirements that forced us to delve into unchartered terrority: Dynamic Apex. These requirements included changing the filter criteria for a query based on user input, custom merge functionality, and custom cloning a record to a different object. All of these functions are best written using Dynamic Apex. There is little documentation out there on using Dynamic Apex so we’ve decided to share our experiences with you. This is the first in a series of posts which will explain Dynamic Apex and how we used it for these projects.

Dynamic SOQL
With our partners Arrowpointe and Spark3, we recently integrated a php website with salesforce.com. Visitors to the website can browse through a list of contacts filtering on various attributes. In the past, this functionality would be written solely using the PHP Toolkit. However, to ensure consistency and reduce the amount of labor to transition to Force.com Sites, we used the PHP Toolkit to connect to salesforce and then call an Apex Web Service. Apex code does all the work to ensure that the data is queried with the correct criteria and then returned properly. Since the Where clause varies in our query we had to either use Dynamic SOQL or a large number of If/Then statements, we chose the former.

Below is a scaled down sample of code you can use to perform the same dynamic query. We’ve also provided you with the syntax for calling the function.

public class website_WebServices
{
    //Function to perform Dynamic SOQL query on Contacts
    public static List<Contact> getContacts(String whereClause)
    {
        //Sample list of Fields
        String fieldList = 'id, FirstName, LastName, Phone, Email ';

        //Define an Order By clause to sort your query
        String orderBy = ' Order By MailingState ';

        //Define your entire Query as a string
        String qryString = 'SELECT ' + fieldList + ' FROM Contact ' + whereClause + orderBy + ' limit 10';

        //Query salesforce with your Query string
        List<Contact> queryResults = Database.query(qryString);

        return queryResults;
    }

    //Sample Where Clause
    public static String whereClause = 'WHERE Lastname != null ';

    //Sample function to get a list of Contacts by passing the Where Clause to the getContacts function
    public static list<contact> contacts = getContacts(whereClause);

}