October 31, 2011

Easy upgrade Eclipse(Helios) Force.com IDE to Winter’12 release.

After long wait, Force.com IDE team finally released an update for Winter’12 release. To see what’s new and supported platforms, please go here : http://wiki.developerforce.com/index.php/Force.com_IDE_Release_Notes
 
If you are doing clean install or using older version of Eclipse before 3.6 (Helios), you can check the install/update instructions in this wiki page. Though I don’t like those mentioned in this wiki update guide, as it requires you to open “Force.com start page”, that is smart enough to crash the eclipse or would take ages to open on faster internet connections. If you are on Eclipse Helios, my preferred way to update in a simpler way is as follows :
 

1. Goto “help > check for updates” in eclipse menu :  

eclipse check of updates menu

2. Let eclipse search for updates, until it comes with a dialog like this. Select “Force.com IDE” and hit “Next” button, as shown below:

Force.com IDE update dialog

3. Hit “Next” on the next screen :

force.com ide installation details dialog

4 : Accept the license terms and finish as usual :)

force.com ide upgrade license terms dialog

5. Let eclipse download the updates, once done you will get a notification to restart Eclipse. Restart it and you are all set to use Winter’12 IDE.

 

After restart you will notice this classic popup asking for Force.com project upgrades.

force.com upgrade project to winter'12 dialog
I usually do a clean checkout of project again, as I work on very small and selective metadata required at point of time. Why selective metadata, checkout this blog post for more details : http://www.tgerm.com/2010/03/fast-save-refresh-force-ide-eclipse.html

October 16, 2011

Winter’12–Social approving of records using ‘Chatter Approvals’ !

Everyone talking about Social Enterprise, Winter’12 release introduced “Chatter Approvals”. Approvals in Chatter are really fun and new social way of approving items, right inside and from Chatter feeds.

For more details about Chatter approvals, please check this Salesforce documentation.

Next, we will see how its social and fun to have Approvals in Chatter.

Exploring - Leave approvals in Chatter !

Manager approving leaves is common scenario in most of organizations. I tried exploring the same here with new Chatter approvals.

Leave management done using Salesforce

This great team uses Chatter for managing CRM and HRM operations like Leave management.

Leave Sobject

A simple custom Sobject called Leave is created to apply & approve leaves. Here are 4 key fields in it

  • Type(PickList) : EL, ML, etc (Earned Leave, Medical Leave)
  • Reason : Why this leave is required.
  • From Date & To Date.

Approval Process

We created standard approval process via Setup > App Setup > Create > Workflow & Approvals > Approval Process.

This approval process sends the record to approval to User’s manager. No more complexity for sake of fun.

Setting up Chatter Approvals

Here are the steps to make sure your org is ready for Chatter approvals.

  1. Enable approvals in chatter here, Setup > Customize > Chatter > Settings : Enable Chatter Approvals in Salesforce Setup Screens
  2. Enable Feed Tracking for Leave sobject here, Setup > Customize > Chatter > Feed Tracking.
  3. Chatter Approvals lets you create “Post Templates” for Chatter feed post. In a Chatter Post Template, one can pick upto 5 fields from Sobject, those fields will be shown in chatter feed post. Create a Post Tempalte for “Leave” sobject here :
    • Chatter Post Template in Salesforce Setup Menu
  4. In Chatter “Post Template” I selected 4 most relevant fields to a leave i.e. From Date, To Date, Leave Type and Reason. As shown here : Chatter Post Template

All set now to play with Chatter Approvals in leave. Next, we will see all this in action.

Leave approval fun via Chatter Approvals :)

Guys, next story is going to revolve around 3 characters in an enterprise. So, lets meet them :

Meet the cast – employees !

badboss scared employee depressed

Mr. Bad Ass, aka Boss/Manager

Mr. Depressoo, reports to Mr. BadAss

Mrs. Frustoo, also reporting to Mr. BadAss

 

Mr. Depresso wants Leave next week :-?

Mr. Depresso is a star performer working at least 60 hours a week to keep customers & more importantly Mr. Bad Ass happy. On the festive occasion of Diwali, he wants a break to meet family and friends. so applied for Leave of few days using “Leave” sobject in Salesforce CRM.

He creates a leave record and submits it for Approval :

Leave Sobject submitted for approval

Mr. Bad Ass Boss feels such leave plan is imaginary, it’s a Joke :)

As we have chatter approvals enabled Mr. Bad Ass get an update in his chatter feed about Mr. Depresso looking forward for a leave. So he adds a chatter comment, and laughs out on this leave request.

chatter approval post in salesforce chatter

Mr. Depressoo tries convincing boss about seriousness of Matter !

He writes back a chatter comment..

both approver and the one who applied commenting in chatter

Mr. Bad Ass boss is not in mood to understand, so he rejects from Chatter itself !

This is how a rejected leave would look in chatter. Mr. Bad Ass boss also added condolence chatter comment :

rejecting approval request from Chatter

Mrs. Frustoo a silent watcher of all this drama, finally speaks up !

Mrs. Frustoo is a kind hearted lady, suffering from same tortures of Mr. Bad ass. So, she decided to cheer up Mr. Depresoo..

somebody else commneting on the chatter approval feedpost

 

Moral of the Chatter Approvals – Story !

Doing Approvals via chatter is really social and fun. It really adds nice context to discuss the approval in chatter feeds. But but but, one needs to be careful about what’s going to be discussed in Approval’s chatter comments, if wrong information is shared to wrong guys, it might be sarcastic fun.

Looking forward for your views and comments !

October 12, 2011

Parse JSON by one line of code using Winter’12 JSON API !

Salesforce Winter’12 release came with a great new API addition to Apex stack i.e. JSONParser. This parser solves all the classic problems using open source Apex based JSONObject.cls, to know more about these problems read my previous post.

This post is an attempt to discuss how one can simplify both JSON operations like JSON serialization and deserialization(parsing) using the new System.JSON API.

Parsing JSON using Winter’12 API

The new JSON API is having decent documentation and most helpful post to start with is from Mr. Pat (aka MetaDaddy), you can read his post here.

Approach 1 - Parse JSON via Streaming Scary Tokens :((

Pat did a great job in describing how to parse JSON using the streaming token based approach. The streaming token is good from time/space complexity point of view, but if you have to parse a huge JSON structure, it become pain to write a parser using this, at least for me it was like $#$#%$^$. I was like understanding now what, is it START OBJECT, START ARRAY or FIELD… :((

Approach 2 – Using JSON.deserialize(…) method

Luckily, I found a very simple approach that can fit to “MOST” of the JSON parsing scenarios. I said most, because this approach will not work well, if your JSON structure is not naming the fields correctly.

This approach requires you to have well defined Apex classes mapped to each of the structure/entity represented in the JSON string. If your apex class exactly resembles the JSON structure you can parse the whole JSON in just one line of code. How ? we will see next.

Lets take the classical example of Departments, Employees and Addresses i.e. Department has many employees and employee can have multiple addresses.

Example JSON structure for one department :

{
   "name":"Engineering",
   "code":"ENGR",
   "employees":[
      {
         "name":"James Bond",
         "mobile":"123-456-7892",
         "isMale":true,
         "age":29,
         "addresses":[
            {
               "street":"900 Concar Drive",
               "state":"CA",
               "postalCode":94402,
               "isPrimary":true,
               "country":"USA",
               "city":"San mateo"
            },
            {
               "street":"800 Bridgepointe",
               "state":"CA",
               "postalCode":29230,
               "isPrimary":false,
               "country":"USA",
               "city":"Foster City"
            }
         ]
      },
      {
         "name":"Brad Pitt",
         "mobile":"987-456-7892",
         "isMale":true,
         "age":35,
         "addresses":[
            {
               "street":"900 Rough Drive",
               "state":"CA",
               "postalCode":13245,
               "isPrimary":true,
               "country":"USA",
               "city":"SFO"
            }
         ]
      }
   ]
}

Object model required for this JSON :

I have created following classes nested under a top level class called “JsonParserTests”.

public with sharing class JsonParserTests {
    
    class Department {
        public String name;
        public String code;
        public Employee[] employees;        
        
        public Department(String n, String c) {
            this.name = n;
            this.code = c;
            this.employees = new List<Employee>();
        }        
    } 
    
    class Employee {
        public String name;
        public Integer age;
        public String mobile;
        public boolean isMale;
        public Address[] addresses;
        
        public Employee(String n, Integer a, String m, boolean im) {
            this.name = n;
            this.age = a;
            this.mobile = m;
            this.isMale = im;
            this.addresses = new List<Address>();
        }
    }
    
    class Address {
        public String street;
        public String city;
        public String state;
        public Integer postalCode;
        public String country;
        public boolean isPrimary;
        
        public Address( String street, String city, String state, Integer postalCode, String country, boolean isPrimary) {
            this.street = street;
            this.city = city;
            this.state = state;
            this.postalCode = postalCode;
            this.country = country;
            this.isPrimary = isPrimary;
        }
    }
} 

 

Parsing the full JSON in one line of code.

Here is the method from System.JSON to do so :

// This department instance is having the full hierarchy
// of employees and addresses in it
Department d = (Department)JSON.deserialize(jsonToParse, JsonParserTests.Department.class);

The beauty of this JSON serialization is you get the full nested object hierarchy in JSON created in one go. Also, it just needs one script statement for the full parsing operation.

One might argue that the above nested classes more than one line of code. I would say its always good to visualize and work on Entities mapped to Classes/Types. Even if one is using streaming parser, they would have required similar nested classes by the end of parsing.

Approach 3 – Hybrid of Streaming Tokens and deserialize !

As I mentioned above in Approach 2 also, that all JSON strings can’t be deserialzed directly using “JSON.deserialize()” call. The JSON structure needs to be well formed with proper field names etc. The good news is one can use both streaming token parser and deserialization together i.e.

  • Parse partial JSON structure using streaming tokens
  • Parse part of JSON structure that can be mapped to an Apex class using “JSONParser.readValueAs()” API.

JSONParser.readValueAs() is almost similar to JSON.deserialize() call, only difference is it works on current token value, instead of taking the JSON string explicitly as param.

Here is an example of “JSONParser.readValueAs()” for the same department JSON structure, but using hybrid mode. Here we will only parse first employee object via JSONParser.readValueAs(..)

System.JSONParser parser = JSON.createParser(jsonToParse);
parser.nextToken(); // START OBJECT
parser.nextToken(); // name
parser.nextToken(); // engineering
parser.nextToken(); // employees
parser.nextToken(); // start array
parser.nextToken(); // start object
// only first employee object parsed.
Employee employee = (Employee)parser.readValueAs(JsonParserTests.Employee.class);  

 

Serializing JSON from Apex in one line of code !

Similar to the easy deserialization approach discussed above, one can serialize complete object graph too. For ex. the same above JSON structure for department can be created like this

Department engineering = new Department('Engineering', 'ENGR');

Employee e1 = new Employee('James Bond', 29,  '123-456-7892', true );
engineering.employees.add(e1);

e1.addresses.add(new Address('900 Concar Drive', 'San mateo', 'CA', 94402, 'USA', true));
e1.addresses.add(new Address('800 Bridgepointe', 'Foster City', 'CA', 29230, 'USA', false));

Employee e2 = new Employee('Brad Pitt', 35,  '987-456-7892', true );
engineering.employees.add(e2);
e2.addresses.add(new Address('900 Rough Drive', 'SFO', 'CA', 13245, 'USA', true));
// JSON string created and printed in debug logs
System.debug(JSON.serialize(engineering));

 

References

Your views and thoughts ?

Looking forward for your comments !!

Visualforce Code Templates/Snippets for Force.com IDE !

I recently saw a lot of action around Mac’s favorite editor TextMate. Force.com community has done a great job to create a full fledged IDE and various code templates for ease in working.

I like TextMate, but I am more inclined towards Force.com IDE, because of its platform neutral nature. Most of my force.com pals are either on Windows machines and few of the geeks are using Ubuntu too. So I am always more motivated towards doing something using Force.com IDE.

Force.com IDE is already doing a decent job on top of Eclipse. It gives a nice Visualforce editor, that gives syntax highlighting and code indentation based on standard Eclipse HTML Editor. I recently tried to create a couple of Visualforce code templates/snippets to quickly assist in creating the pages, and was successful in that attempt. Rest of the post describes how.

How to setup Visualforce code templates for Eclipse ?

Here are the steps

  1. Goto Eclipse > Preferences.
  2. Search for “Template” in the left pane preference filter box, as shown belowEclipse Preferences Pane with Template Search Text 
  3. Hit the “New” button on extreme right side to start creating a new Template, as shown :Create New template for visualforce tag
  4. In the dialog next, enter tag name in the text field labeled “Name” and code snippet in text area labeled “Pattern”. Also select context as “HTML Tag”, as shown below : Defining template name and pattern for visualforce
  5. Now, in any visualforce page in Force.com IDE, press CTRL + SPACE and start typing the tag name, like apex:p… In the content assist box, you will see the newly created template as shown below. Hit enter to get the template inserted in current code location.  Visualforce template based content assist box in Eclipse

Using the same steps as above, I have created a few templates for visualforce like

Field Label Template

Visualforce Field Label template

CRUD FLS Permission

Visualforce CRUD FLS check template

Creating a useful template library for Visualforce !

The good part about Eclipse templates is those can be exported and imported back via XML. I started creating a few code snippets/templates and the export for them is available in gist here.

One can easily import this GIST on the same template page using the “Import” button near the New one. Similarly exporting yours is easy too, just select templates to export and hit “Export” button.

Please join me to add more and better code templates for making Visualforce development easier in Eclipse.

October 11, 2011

Visualforce RelatedList CRUD FLS Security Tip !

Visualforce makes it very easy to create Salesforce look and feel pages. It also helps developers to get most of the Salesforce security guidelines implemented transparently, though developers need to take care of few items on their own. All these items are discussed in great details on DeveloperForce WIKI here. Motive of this post is to highlight a common mistake done by most of the developers from both security and quality point of view.

Code below is a very basic example of a visualforce page, to show some account details with a Contact related list only.

<apex:page standardController="Account">
    <apex:detail relatedList="false"/>
    <apex:relatedList list="Contacts"/>
</apex:page>

This page will work very well with all user’s, whose profiles are having at least read permission on “Contact” standard object. But but but, the same page will crash completely if user’s profile is not having at least READ permission on Contact, like this

Visualforce error on missing related list permission

So, its clear that Salesforce doesn’t transparently hides the related list on missing permissions, thus highly recommended to all Salesforce developers to add a security CRUD/FLS check on related lists too like this

<apex:page standardController="Account">
    <apex:detail relatedList="false"/>
     <!--
          Control rendering of related list by checking the relevant
          child sobject, via $ObjectType.Contact.accessible
     -->
    <apex:relatedList list="Contacts" rendered="{!$ObjectType.Contact.accessible}"/>
</apex:page>

Now, the page will atleast show the record details except the Contacts related list on Account and this is what should happen as per profile permissions.

I hope above fix will make life easy post go-live, no fear of facing a panic customer whose page is messed for a given profile :)

References

 

Want to explore more about Salesforce security ?

These articles will be a good read